repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
adamahrens/AndroidExploration | ListMaker/app/src/main/java/com/appsbyahrens/listmaker/ListDataManager.kt | 1 | 962 | package com.appsbyahrens.listmaker
import android.content.Context
import android.preference.PreferenceManager
import android.support.v7.app.AppCompatActivity
class ListDataManager(val context: Context) {
fun save(list: TaskList) {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context).edit()
sharedPreferences.putStringSet(list.name, list.tasks.toHashSet())
sharedPreferences.apply()
}
fun getTaskLists(): ArrayList<TaskList> {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val contents = sharedPreferences.all
val taskLists = ArrayList<TaskList>()
for (taskList in contents) {
val hashSet = taskList.value as? HashSet<String>
hashSet.let { set ->
val list = TaskList(taskList.key, ArrayList(set))
taskLists.add(list)
}
}
return taskLists
}
} | mit | 2de7c998e15d54226d42837b65c9a7e2 | 31.1 | 93 | 0.677755 | 5.036649 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/writers/CreateExchangesAndSteps.kt | 1 | 6941 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers
import com.google.cloud.spanner.Value
import com.google.type.Date
import kotlinx.coroutines.flow.singleOrNull
import org.wfanet.measurement.common.toLocalDate
import org.wfanet.measurement.common.toProtoDate
import org.wfanet.measurement.gcloud.common.toCloudDate
import org.wfanet.measurement.gcloud.spanner.appendClause
import org.wfanet.measurement.gcloud.spanner.bind
import org.wfanet.measurement.gcloud.spanner.bufferInsertMutation
import org.wfanet.measurement.gcloud.spanner.bufferUpdateMutation
import org.wfanet.measurement.gcloud.spanner.set
import org.wfanet.measurement.gcloud.spanner.setJson
import org.wfanet.measurement.internal.common.Provider
import org.wfanet.measurement.internal.kingdom.Exchange
import org.wfanet.measurement.internal.kingdom.ExchangeDetails
import org.wfanet.measurement.internal.kingdom.ExchangeStep
import org.wfanet.measurement.internal.kingdom.ExchangeWorkflow
import org.wfanet.measurement.internal.kingdom.RecurringExchange
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.PROVIDER_PARAM
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.providerFilter
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.RecurringExchangeReader
class CreateExchangesAndSteps(private val provider: Provider) : SimpleSpannerWriter<Unit>() {
override suspend fun TransactionScope.runTransaction() {
val recurringExchangeResult: RecurringExchangeReader.Result = getRecurringExchange() ?: return
val recurringExchange = recurringExchangeResult.recurringExchange
val recurringExchangeId = recurringExchangeResult.recurringExchangeId
val modelProviderId = recurringExchangeResult.modelProviderId
val dataProviderId = recurringExchangeResult.dataProviderId
val nextExchangeDate = recurringExchange.nextExchangeDate
val workflow = recurringExchange.details.exchangeWorkflow
// Create the Exchange with the date equal to next exchange date.
createExchange(recurringExchangeId = recurringExchangeId, date = nextExchangeDate)
// Calculate the new next exchange date for the recurring exchange.
val nextNextExchangeDate =
nextExchangeDate.applyCronSchedule(recurringExchange.details.cronSchedule)
// Update recurring exchange with new next exchange date. Its state doesn't change.
updateRecurringExchange(
recurringExchangeId = recurringExchangeId,
nextExchangeDate = nextNextExchangeDate
)
// Create all steps for the Exchange, set them all to BLOCKED State initially.
createExchangeSteps(
workflow = workflow,
recurringExchangeId = recurringExchangeId,
date = nextExchangeDate,
modelProviderId = modelProviderId,
dataProviderId = dataProviderId
)
// Update all Steps States based on the workflow.
updateExchangeStepsToReady(
steps = workflow.stepsList.filter { step -> step.prerequisiteStepIndicesCount == 0 },
recurringExchangeId = recurringExchangeId,
date = nextExchangeDate
)
}
private suspend fun TransactionScope.getRecurringExchange(): RecurringExchangeReader.Result? {
return RecurringExchangeReader()
.fillStatementBuilder {
appendClause(
"""
WHERE State = @recurringExchangeState
AND NextExchangeDate <= CURRENT_DATE("+0")
AND ${providerFilter(provider)}
AND @exchangeState NOT IN (
SELECT Exchanges.State
FROM Exchanges
WHERE Exchanges.RecurringExchangeId = RecurringExchanges.RecurringExchangeId
ORDER BY Exchanges.Date DESC
LIMIT 1
)
ORDER BY NextExchangeDate
LIMIT 1
"""
.trimIndent()
)
bind("recurringExchangeState" to RecurringExchange.State.ACTIVE)
bind(PROVIDER_PARAM to provider.externalId)
bind("exchangeState" to Exchange.State.FAILED)
}
.execute(transactionContext)
.singleOrNull()
}
private fun TransactionScope.createExchange(recurringExchangeId: Long, date: Date) {
// TODO: Set ExchangeDetails with proper Audit trail hash.
val exchangeDetails = ExchangeDetails.getDefaultInstance()
transactionContext.bufferInsertMutation("Exchanges") {
set("RecurringExchangeId" to recurringExchangeId)
set("Date" to date.toCloudDate())
set("State" to Exchange.State.ACTIVE)
set("ExchangeDetails" to exchangeDetails)
setJson("ExchangeDetailsJson" to exchangeDetails)
}
}
private fun TransactionScope.updateRecurringExchange(
recurringExchangeId: Long,
nextExchangeDate: Date
) {
transactionContext.bufferUpdateMutation("RecurringExchanges") {
set("RecurringExchangeId" to recurringExchangeId)
set("NextExchangeDate" to nextExchangeDate.toCloudDate())
}
}
private fun TransactionScope.createExchangeSteps(
workflow: ExchangeWorkflow,
recurringExchangeId: Long,
date: Date,
modelProviderId: Long,
dataProviderId: Long
) {
for (step in workflow.stepsList) {
transactionContext.bufferInsertMutation("ExchangeSteps") {
set("RecurringExchangeId" to recurringExchangeId)
set("Date" to date.toCloudDate())
set("StepIndex" to step.stepIndex.toLong())
set("State" to ExchangeStep.State.BLOCKED)
set("UpdateTime" to Value.COMMIT_TIMESTAMP)
set(
"ModelProviderId" to
if (step.party == ExchangeWorkflow.Party.MODEL_PROVIDER) modelProviderId else null
)
set(
"DataProviderId" to
if (step.party == ExchangeWorkflow.Party.DATA_PROVIDER) dataProviderId else null
)
}
}
}
// TODO: Decide on the format for cronSchedule.
// See https://github.com/world-federation-of-advertisers/cross-media-measurement/issues/180.
private fun Date.applyCronSchedule(cronSchedule: String): Date {
return when (cronSchedule) {
"@daily" -> this.toLocalDate().plusDays(1).toProtoDate()
"@weekly" -> this.toLocalDate().plusWeeks(1).toProtoDate()
"@monthly" -> this.toLocalDate().plusMonths(1).toProtoDate()
"@yearly" -> this.toLocalDate().plusYears(1).toProtoDate()
else -> error("Cannot support this.")
}
}
}
| apache-2.0 | af60e69acae2b295f6c9d92b6be530b5 | 40.315476 | 98 | 0.738366 | 4.793508 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/reporting/deploy/postgres/SerializableErrors.kt | 1 | 1679 | // Copyright 2022 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.reporting.deploy.postgres
import io.r2dbc.postgresql.api.PostgresqlException
import kotlin.time.Duration.Companion.seconds
import kotlin.time.ExperimentalTime
import kotlin.time.TimeMark
import kotlin.time.TimeSource
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.retry
import kotlinx.coroutines.flow.single
object SerializableErrors {
private const val SERIALIZABLE_ERROR_CODE = "40001"
@OptIn(ExperimentalTime::class) private val SERIALIZABLE_RETRY_DURATION = 120.seconds
suspend fun <T> retrying(block: suspend () -> T): T {
return flow { emit(block()) }.withSerializableErrorRetries().single()
}
@OptIn(ExperimentalTime::class)
fun <T> Flow<T>.withSerializableErrorRetries(): Flow<T> {
val retryLimit: TimeMark = TimeSource.Monotonic.markNow().plus(SERIALIZABLE_RETRY_DURATION)
return this.retry { e ->
(retryLimit.hasNotPassedNow() &&
e is PostgresqlException &&
e.errorDetails.code == SERIALIZABLE_ERROR_CODE)
}
}
}
| apache-2.0 | 1a481720d2f82bdad24f43fbc9d52ea2 | 37.159091 | 95 | 0.756998 | 4.095122 | false | false | false | false |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/assets/AndroidAssetService.kt | 1 | 4853 | package io.rover.sdk.experiences.assets
import android.graphics.Bitmap
import io.rover.sdk.experiences.logging.log
import io.rover.sdk.experiences.platform.debugExplanation
import io.rover.sdk.core.streams.PublishSubject
import io.rover.sdk.core.streams.Publishers
import io.rover.sdk.core.streams.Scheduler
import io.rover.sdk.core.streams.doOnNext
import io.rover.sdk.core.streams.doOnSubscribe
import io.rover.sdk.core.streams.filter
import io.rover.sdk.core.streams.flatMap
import io.rover.sdk.core.streams.map
import io.rover.sdk.core.streams.observeOn
import io.rover.sdk.core.streams.onErrorReturn
import io.rover.sdk.core.streams.retry
import io.rover.sdk.core.streams.subscribe
import io.rover.sdk.core.streams.subscribeOn
import io.rover.sdk.core.streams.timeout
import org.reactivestreams.Publisher
import java.net.URL
import java.util.concurrent.TimeUnit
internal open class AndroidAssetService(
imageDownloader: ImageDownloader,
private val ioScheduler: Scheduler,
mainThreadScheduler: Scheduler
) : AssetService {
private val synchronousImagePipeline = BitmapWarmGpuCacheStage(
InMemoryBitmapCacheStage(
DecodeToBitmapStage(
AssetRetrievalStage(
imageDownloader
)
)
)
)
override fun imageByUrl(
url: URL
): Publisher<Bitmap> {
return receivedImages
.filter { it.url == url }
.map { it.bitmap }
.doOnSubscribe {
// kick off an initial fetch if one is not already running.
tryFetch(url)
}
}
override fun tryFetch(url: URL) {
requests.onNext(url)
}
override fun getImageByUrl(url: URL): Publisher<PipelineStageResult<Bitmap>> {
return Publishers.defer<PipelineStageResult<Bitmap>> {
Publishers.just(
// this block will be dispatched onto the ioExecutor by
// SynchronousOperationNetworkTask.
// ioExecutor is really only intended for I/O multiplexing only: it spawns many more
// threads than CPU cores. However, I'm bending that rule a bit by having image
// decoding occur inband. Thankfully, the risk of that spamming too many CPU-bound
// workloads across many threads is mitigated by the HTTP client library
// (HttpURLConnection, itself internally backed by OkHttp inside the Android
// standard library) limiting concurrent image downloads from the same origin, which
// most of the images in Rover experiences will be.
synchronousImagePipeline.request(url)
)
}.onErrorReturn { error ->
PipelineStageResult.Failed<Bitmap>(error, false) as PipelineStageResult<Bitmap>
}
}
private data class ImageReadyEvent(
val url: URL,
val bitmap: Bitmap
)
private val requests = PublishSubject<URL>()
private val receivedImages = PublishSubject<ImageReadyEvent>()
init {
val outstanding: MutableSet<URL> = mutableSetOf()
requests
.filter { url ->
synchronized(outstanding) { url !in outstanding }
}
.doOnNext { synchronized(outstanding) { outstanding.add(it) } }
.flatMap { url ->
getImageByUrl(url)
.timeout(10, TimeUnit.SECONDS)
// handle any unexpected failures in the image processing pipeline
.onErrorReturn {
PipelineStageResult.Failed<Bitmap>(it, false) as PipelineStageResult<Bitmap>
}
.map { result ->
if (result is PipelineStageResult.Failed<Bitmap> && result.retry) {
throw Exception("Do Retry.", result.reason)
}
result
}
.retry(3)
.map { Pair(url, it) }
.subscribeOn(ioScheduler)
}
.observeOn(mainThreadScheduler)
.subscribe({ (url, result) ->
synchronized(outstanding) { outstanding.remove(url) }
when (result) {
is PipelineStageResult.Successful -> {
receivedImages.onNext(
ImageReadyEvent(url, result.output)
)
}
is PipelineStageResult.Failed -> {
log.w("Failed to fetch image from URL $url: ${result.reason.debugExplanation()}")
}
}
}, {
log.w("image request failed ${it.debugExplanation()}")
})
}
}
| apache-2.0 | 3dc8846b7cbc83831b64e572f210e2da | 37.824 | 105 | 0.589326 | 5.071055 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/settings/SettingsFragment.kt | 1 | 8888 | package net.simonvt.cathode.settings
import android.Manifest.permission
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build.VERSION_CODES
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreference
import net.simonvt.android.colorpicker.ColorPickerDialog
import net.simonvt.android.colorpicker.ColorPickerSwatch.OnColorSelectedListener
import net.simonvt.cathode.R
import net.simonvt.cathode.common.ui.FragmentsUtils
import net.simonvt.cathode.common.ui.adapter.Adapters
import net.simonvt.cathode.common.util.Intents
import net.simonvt.cathode.common.util.VersionCodes
import net.simonvt.cathode.provider.DatabaseContract.EpisodeColumns
import net.simonvt.cathode.provider.ProviderSchematic.Episodes
import net.simonvt.cathode.settings.ShowOffsetDialog.ShowOffsetSelectedListener
import net.simonvt.cathode.settings.UpcomingTime.WEEKS_1
import net.simonvt.cathode.settings.UpcomingTimeDialog.UpcomingTimeSelectedListener
import net.simonvt.cathode.settings.hidden.HiddenItems
import net.simonvt.cathode.settings.login.LoginActivity
import timber.log.Timber
import javax.inject.Inject
class SettingsFragment @Inject constructor(private val upcomingTimePreference: UpcomingTimePreference) :
PreferenceFragmentCompat(), UpcomingTimeSelectedListener, OnColorSelectedListener,
ShowOffsetSelectedListener {
private lateinit var syncCalendar: SwitchPreference
private var isTablet: Boolean = false
override fun onCreate(inState: Bundle?) {
super.onCreate(inState)
isTablet = resources.getBoolean(R.bool.isTablet)
}
override fun onCreatePreferences(inState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.settings_general)
syncCalendar = findPreference<Preference>(Settings.CALENDAR_SYNC) as SwitchPreference
syncCalendar.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { preference, newValue ->
val checked = newValue as Boolean
syncCalendar.isChecked = checked
if (VersionCodes.isAtLeastM()) {
if (checked && !Permissions.hasCalendarPermission(activity)) {
requestPermission()
}
} else {
Accounts.requestCalendarSync(activity)
}
true
}
findPreference<Preference>("calendarColor")!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
val calendarColor =
Settings.get(activity).getInt(Settings.CALENDAR_COLOR, Settings.CALENDAR_COLOR_DEFAULT)
val size = if (isTablet) ColorPickerDialog.SIZE_LARGE else ColorPickerDialog.SIZE_SMALL
val dialog = ColorPickerDialog.newInstance(
R.string.preference_calendar_color,
Settings.CALENDAR_COLORS,
calendarColor,
5,
size
)
dialog.setTargetFragment(this@SettingsFragment, 0)
dialog.show(requireFragmentManager(), DIALOG_COLOR_PICKER)
if (Settings.get(activity).getBoolean(Settings.CALENDAR_SYNC, false)) {
Accounts.requestCalendarSync(activity)
}
true
}
findPreference<Preference>("notifications")!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
startActivity(
Intent(
activity,
NotificationSettingsActivity::class.java
)
)
true
}
findPreference<Preference>("hiddenItems")!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
startActivity(Intent(activity, HiddenItems::class.java))
true
}
findPreference<Preference>("upcomingTime")!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
val upcomingTime = UpcomingTime.fromValue(
Settings.get(activity).getLong(
Settings.UPCOMING_TIME,
WEEKS_1.cacheTime
)
)
val dialog = FragmentsUtils.instantiate(
requireFragmentManager(),
UpcomingTimeDialog::class.java,
UpcomingTimeDialog.getArgs(upcomingTime)
)
dialog.setTargetFragment(this@SettingsFragment, 0)
dialog.show(requireFragmentManager(), DIALOG_UPCOMING_TIME)
true
}
findPreference<Preference>(Settings.SHOWS_AVOID_SPOILERS)!!.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { preference, newValue ->
Adapters.notifyAdapters()
if (Settings.get(activity).getBoolean(Settings.CALENDAR_SYNC, false)) {
Accounts.requestCalendarSync(activity)
}
true
}
findPreference<Preference>(Settings.SHOWS_OFFSET)!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
val offset = FirstAiredOffsetPreference.getInstance().offsetHours
val dialog = FragmentsUtils.instantiate(
requireFragmentManager(),
ShowOffsetDialog::class.java,
ShowOffsetDialog.getArgs(offset)
)
dialog.setTargetFragment(this@SettingsFragment, 0)
dialog.show(requireFragmentManager(), DIALOG_SHOW_OFFSET)
true
}
val traktLink = findPreference<Preference>("traktLink")
val traktUnlink = findPreference<Preference>("traktUnlink")
traktLink!!.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val i = Intent(activity, LoginActivity::class.java)
i.putExtra(LoginActivity.EXTRA_TASK, LoginActivity.TASK_LINK)
startActivity(i)
true
}
traktUnlink!!.onPreferenceClickListener = Preference.OnPreferenceClickListener {
FragmentsUtils.instantiate(requireFragmentManager(), LogoutDialog::class.java)
.show(requireFragmentManager(), DIALOG_LOGOUT)
true
}
if (TraktLinkSettings.isLinked(activity)) {
preferenceScreen.removePreference(traktLink)
} else {
preferenceScreen.removePreference(traktUnlink)
}
findPreference<Preference>("about")!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
AboutDialog().show(requireFragmentManager(), DIALOG_ABOUT)
true
}
findPreference<Preference>("privacy")!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
Intents.openUrl(requireActivity(), getString(R.string.privacy_policy_url))
true
}
}
@RequiresApi(VERSION_CODES.M)
private fun requestPermission() {
requestPermissions(
arrayOf(permission.READ_CALENDAR, permission.WRITE_CALENDAR),
PERMISSION_REQUEST_CALENDAR
)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == PERMISSION_REQUEST_CALENDAR) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Timber.d("Calendar permission granted")
Accounts.requestCalendarSync(activity)
} else {
Timber.d("Calendar permission not granted")
}
}
}
override fun onUpcomingTimeSelected(value: UpcomingTime) {
upcomingTimePreference.set(value)
}
override fun onColorSelected(color: Int) {
val calendarColor =
Settings.get(activity).getInt(Settings.CALENDAR_COLOR, Settings.CALENDAR_COLOR_DEFAULT)
if (color != calendarColor) {
Settings.get(activity)
.edit()
.putInt(Settings.CALENDAR_COLOR, color)
.putBoolean(Settings.CALENDAR_COLOR_NEEDS_UPDATE, true)
.apply()
if (Permissions.hasCalendarPermission(activity)) {
Accounts.requestCalendarSync(activity)
}
}
}
override fun onShowOffsetSelected(offset: Int) {
val showOffset = FirstAiredOffsetPreference.getInstance().offsetHours
if (offset != showOffset) {
FirstAiredOffsetPreference.getInstance().set(offset)
val context = requireContext()
Thread(Runnable {
val values = ContentValues()
values.put(EpisodeColumns.LAST_MODIFIED, System.currentTimeMillis())
context.contentResolver.update(Episodes.EPISODES, values, null, null)
Accounts.requestCalendarSync(context)
}).start()
}
}
companion object {
private const val DIALOG_UPCOMING_TIME =
"net.simonvt.cathode.settings.SettingsFragment.upcomingTime"
private const val DIALOG_SHOW_OFFSET =
"net.simonvt.cathode.settings.SettingsFragment.showOffset"
private const val DIALOG_COLOR_PICKER =
"net.simonvt.cathode.settings.SettingsFragment.ColorPicker"
private const val DIALOG_LOGOUT = "net.simonvt.cathode.settings.SettingsFragment.logoutDialog"
private const val DIALOG_ABOUT = "net.simonvt.cathode.settings.SettingsFragment.aboutDialog"
private const val PERMISSION_REQUEST_CALENDAR = 11
}
}
| apache-2.0 | 44fb7e2779ddc05be48b0556c66a6458 | 34.552 | 104 | 0.721535 | 5.116868 | false | false | false | false |
debop/debop4k | debop4k-core/src/main/kotlin/debop4k/core/retry/AsyncRetryExecutor.kt | 1 | 5134 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.core.retry
import debop4k.core.loggerOf
import debop4k.core.retry.backoff.*
import debop4k.core.utils.Systems
import nl.komponents.kovenant.Promise
import java.lang.Exception
import java.util.concurrent.*
/**
* AsyncRetryExecutor
* @author debop [email protected]
*/
open class AsyncRetryExecutor
@JvmOverloads constructor(val scheduler: ScheduledExecutorService = DefaultExecutorService,
val retryPolicy: RetryPolicy = RetryPolicy.DEFAULT,
val backoff: Backoff = DEFAULT_BACKOFF,
val fixedDelay: Boolean = false) : RetryExecutor {
companion object {
@JvmField val DefaultExecutorService: ScheduledExecutorService
= Executors.newScheduledThreadPool(Systems.ProcessCount)
}
private val log = loggerOf(javaClass)
override fun doWithRetry(action: (RetryContext) -> Unit): Promise<Unit, Throwable> {
return getWithRetry { action(it) }
}
override fun <V> getWithRetry(callable: Callable<V>): Promise<V, Throwable> {
return getWithRetry { callable.call() }
}
override fun <V> getWithRetry(func: (RetryContext) -> V): Promise<V, Throwable> {
return scheduleImmediately(createTask(func))
}
override fun <V> getFutureWithRetry(func: (RetryContext) -> Promise<V, Throwable>): Promise<V, Throwable> {
return scheduleImmediately(createFutureTask(func))
}
/**
* 작업을 수행합니다.
*/
protected fun <V> scheduleImmediately(job: RetryJob<V>): Promise<V, Throwable> {
scheduler.schedule(job, 0, TimeUnit.MILLISECONDS)
return job.promise
}
private fun <V> createTask(func: (RetryContext) -> V): RetryJob<V>
= SyncRetryJob(func, this)
private fun <V> createFutureTask(func: (RetryContext) -> Promise<V, Throwable>): RetryJob<V>
= AsyncRetryJob<V>(func, this)
fun withScheduler(scheduler: ScheduledExecutorService): AsyncRetryExecutor
= AsyncRetryExecutor(scheduler, retryPolicy, backoff, fixedDelay)
fun withRetryPolicy(policy: RetryPolicy): AsyncRetryExecutor
= AsyncRetryExecutor(scheduler, policy, backoff, fixedDelay)
fun withBackoff(backoff: Backoff): AsyncRetryExecutor
= AsyncRetryExecutor(scheduler, retryPolicy, backoff, fixedDelay)
@JvmOverloads
fun withExponentialBackoff(initialDelayMillis: Long, multiplier: Double = DEFAULT_MULTIPLIER): AsyncRetryExecutor {
return withBackoff(ExponentialDelayBackoff(initialDelayMillis, multiplier))
}
@JvmOverloads
fun withFixedBackoff(delayMillis: Long = DEFAULT_PERIOD_MILLIS): AsyncRetryExecutor {
return withBackoff(FixedIntervalBackoff(delayMillis))
}
@JvmOverloads
fun withFixedRate(fixedDelay: Boolean = true): AsyncRetryExecutor {
return AsyncRetryExecutor(scheduler, retryPolicy, backoff, fixedDelay)
}
@JvmOverloads
fun withUniformJitter(range: Long = DEFAULT_RANDOM_RANGE_MILLIS): AsyncRetryExecutor
= withBackoff(backoff.withUniformJitter(range))
@JvmOverloads
fun withProportionalJitter(multiplier: Double = DEFAULT_MULTIPLIER): AsyncRetryExecutor
= withBackoff(backoff.withProportionalJitter(multiplier))
@JvmOverloads
fun withMinDelay(minDelayMillis: Long = DEFAULT_MIN_DELAY_MILLIS): AsyncRetryExecutor
= withBackoff(backoff.withMinDelay(minDelayMillis))
@JvmOverloads
fun withMaxDelay(maxDelayMillis: Long = DEFAULT_MAX_DELAY_MILLIS): AsyncRetryExecutor
= withBackoff(backoff.withMaxDelay(maxDelayMillis))
fun withMaxRetry(times: Int): AsyncRetryExecutor
= withRetryPolicy(retryPolicy.withMaxRetry(times))
fun dontRetry(): AsyncRetryExecutor
= withRetryPolicy(retryPolicy.dontRetry())
fun retryInfinitely(): AsyncRetryExecutor
= withMaxRetry(Int.MAX_VALUE)
fun withNoDelay(): AsyncRetryExecutor
= withBackoff(FixedIntervalBackoff(0L))
fun firstRetryNoDelay(): AsyncRetryExecutor
= withBackoff(backoff.withFirstRetryNoDelay())
fun retryOn(vararg retryOnExceptions: Class<out Exception>): AsyncRetryExecutor
= this.withRetryPolicy(retryPolicy.retryOn(*retryOnExceptions))
fun abortOn(vararg abortOnExceptions: Class<out Exception>): AsyncRetryExecutor
= this.withRetryPolicy(retryPolicy.abortOn(*abortOnExceptions))
fun retryIf(predicate: (Throwable?) -> Boolean): AsyncRetryExecutor
= this.withRetryPolicy(retryPolicy.retryIf(predicate))
fun abortIf(predicate: (Throwable?) -> Boolean): AsyncRetryExecutor
= this.withRetryPolicy(retryPolicy.abortIf(predicate))
} | apache-2.0 | 43562afc4409c8726004e538bb4a72cd | 35.564286 | 117 | 0.747362 | 4.322635 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/common/gui/FluidDisplayPiece.kt | 1 | 1746 | package net.ndrei.teslapoweredthingies.common.gui
import net.minecraft.client.renderer.GlStateManager
import net.minecraft.client.renderer.texture.TextureMap
import net.minecraftforge.fluids.Fluid
import net.minecraftforge.fluids.FluidStack
import net.ndrei.teslacorelib.gui.BasicContainerGuiPiece
import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer
import org.lwjgl.opengl.GL11
/**
* Created by CF on 2017-06-30.
*/
class FluidDisplayPiece(left: Int, top: Int, width: Int, height: Int, private val fluidGetter: () -> FluidStack?)
: BasicContainerGuiPiece(left, top, width, height) {
override fun drawBackgroundLayer(container: BasicTeslaGuiContainer<*>, guiX: Int, guiY: Int, partialTicks: Float, mouseX: Int, mouseY: Int) {
val fluid = this.fluidGetter() ?: return
this.drawFluid(container, fluid.fluid, guiX + this.left + 1, guiY + this.top + 1 , this.width - 2, this.height - 2)
}
private fun drawFluid(container: BasicTeslaGuiContainer<*>, fluid: Fluid?, x: Int, y: Int, w: Int, h: Int) {
if (fluid == null) {
return
}
val color = fluid.color
val still = fluid.flowing //.getStill(stack);
if (still != null) {
val sprite = container.mc.textureMapBlocks.getTextureExtry(still.toString()) ?: container.mc.textureMapBlocks.missingSprite
container.mc.textureManager.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE)
GL11.glColor3ub((color shr 16 and 0xFF).toByte(), (color shr 8 and 0xFF).toByte(), (color and 0xFF).toByte())
GlStateManager.enableBlend()
container.drawTexturedModalRect(
x, y, sprite!!, w, h)
GlStateManager.disableBlend()
}
}
}
| mit | 2997a3097733d6b0bf90bde772b033b9 | 42.65 | 145 | 0.683276 | 4.088993 | false | false | false | false |
FHannes/intellij-community | platform/projectModel-api/src/com/intellij/openapi/project/ProjectUtilCore.kt | 2 | 2188 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("ProjectUtilCore")
package com.intellij.openapi.project
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.roots.JdkOrderEntry
import com.intellij.openapi.roots.libraries.LibraryUtil
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.vfs.LocalFileProvider
import com.intellij.openapi.vfs.VirtualFile
fun displayUrlRelativeToProject(file: VirtualFile, url: String, project: Project, includeFilePath: Boolean, keepModuleAlwaysOnTheLeft: Boolean): String {
var result = url
val baseDir = project.baseDir
if (baseDir != null && includeFilePath) {
val projectHomeUrl = baseDir.presentableUrl
if (result.startsWith(projectHomeUrl)) {
result = "...${result.substring(projectHomeUrl.length)}"
}
}
if (SystemInfo.isMac && file.fileSystem is LocalFileProvider) {
val fileForJar = (file.fileSystem as LocalFileProvider).getLocalVirtualFileFor(file)
if (fileForJar != null) {
val libraryEntry = LibraryUtil.findLibraryEntry(file, project)
if (libraryEntry != null) {
if (libraryEntry is JdkOrderEntry) {
result = "$result - [${libraryEntry.jdkName}]"
}
else {
result = "$result - [${libraryEntry.presentableName}]"
}
}
else {
result = "$result - [${fileForJar.name}]"
}
}
}
val module = ModuleUtilCore.findModuleForFile(file, project) ?: return result
return if (!keepModuleAlwaysOnTheLeft && SystemInfo.isMac) {
"$result - [${module.name}]"
}
else {
"[${module.name}] - $result"
}
} | apache-2.0 | 24ee5cdc67852ba95d00770465a94c4c | 34.885246 | 153 | 0.70841 | 4.273438 | false | false | false | false |
grassrootza/grassroot-android-v2 | app/src/main/java/za/org/grassroot2/view/activity/GrassrootActivity.kt | 1 | 13438 | package za.org.grassroot2.view.activity
import android.accounts.AccountAuthenticatorResponse
import android.accounts.AccountManager
import android.accounts.AuthenticatorException
import android.accounts.OperationCanceledException
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.preference.PreferenceManager
import android.support.annotation.LayoutRes
import android.support.design.widget.Snackbar
import android.support.v4.app.DialogFragment
import android.support.v4.content.LocalBroadcastManager
import android.support.v7.app.AppCompatActivity
import android.support.v7.app.AppCompatDelegate
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.RelativeLayout
import android.widget.Toast
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.gcm.GoogleCloudMessaging
import dagger.Lazy
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.include_progress_bar.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import timber.log.Timber
import za.org.grassroot.messaging.dto.MessageDTO
import za.org.grassroot2.GrassrootApplication
import za.org.grassroot2.R
import za.org.grassroot2.dagger.AppComponent
import za.org.grassroot2.dagger.activity.ActivityComponent
import za.org.grassroot2.dagger.activity.ActivityModule
import za.org.grassroot2.model.task.Meeting
import za.org.grassroot2.service.GCMPreferences
import za.org.grassroot2.services.OfflineReceiver
import za.org.grassroot2.services.SyncOfflineDataService
import za.org.grassroot2.services.account.AuthConstants
import za.org.grassroot2.services.rest.AddTokenInterceptor
import za.org.grassroot2.util.AlarmManagerHelper
import za.org.grassroot2.util.UserPreference
import za.org.grassroot2.util.ViewAnimation
import za.org.grassroot2.view.GrassrootView
import za.org.grassroot2.view.dialog.GenericErrorDialog
import za.org.grassroot2.view.dialog.GenericMessageDialog
import za.org.grassroot2.view.dialog.GenericSuccessDialog
import za.org.grassroot2.view.dialog.NoConnectionDialog
import java.io.IOException
import java.util.*
import javax.inject.Inject
abstract class GrassrootActivity : AppCompatActivity(), GrassrootView {
@Inject lateinit var accountManagerProvider: Lazy<AccountManager>
@Inject lateinit var userPreference: UserPreference
@Inject lateinit var jsonMaper: ObjectMapper
@get:LayoutRes protected abstract val layoutResourceId: Int
protected abstract fun onInject(component: ActivityComponent)
private var mRegistrationBroadcastReceiver: BroadcastReceiver? = null
private var isReceiverRegistered: Boolean = false
private var authResponse: AccountAuthenticatorResponse? = null
private var authResultBundle: Bundle? = null
protected var disposables = CompositeDisposable()
private var component: ActivityComponent? = null
override val activity: Activity
get() = this
val activityModule: ActivityModule
get() = ActivityModule(this)
val componenet: ActivityComponent
get() {
if (component == null) {
component = appComponent.plus(activityModule)
}
return component!!
}
val appComponent: AppComponent
get() = (application as GrassrootApplication).appComponent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
setContentView(R.layout.base_progress_container)
setContentLayout(layoutResourceId)
componenet.inject(this)
onInject(componenet)
authResponse = intent.getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE)
if (authResponse != null) {
authResponse!!.onRequestContinued()
}
mRegistrationBroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val currentToken = sharedPreferences.getString(GCMPreferences.CURRENT_GCM_TOKEN, null)
Timber.i("GCM token check finished. Current token: %s", currentToken)
closeProgressBar()
}
}
}
private fun registerReceiver() {
if (!isReceiverRegistered) {
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver!!,
IntentFilter(GCMPreferences.GCM_REGISTRATION_COMPLETE))
isReceiverRegistered = true
}
}
private fun setContentLayout(resId: Int) {
val parent = findViewById<View>(R.id.main_layout) as RelativeLayout
val v = LayoutInflater.from(this).inflate(resId, parent, false)
parent.addView(v)
}
protected fun loggedIn(): Boolean {
val accounts = accountManagerProvider.get().getAccountsByType(AuthConstants.ACCOUNT_TYPE)
return accounts.size != 0 && !TextUtils.isEmpty(accountManagerProvider.get().getUserData(accounts[0], AuthConstants.USER_DATA_LOGGED_IN))
}
override fun showMessageDialog(text: String) {
val dialog = GenericMessageDialog.newInstance(text)
dialog.show(supportFragmentManager, DIALOG_TAG)
}
override fun handleNoConnection() {
if (!userPreference.connectionInfoDisplayed()) {
val dialog: DialogFragment
if (loggedIn()) {
dialog = NoConnectionDialog.newInstance(NoConnectionDialog.TYPE_AUTHORIZED)
} else {
dialog = NoConnectionDialog.newInstance(NoConnectionDialog.TYPE_NOT_AUTHORIZED)
}
dialog.show(supportFragmentManager, DIALOG_TAG)
userPreference.setNoConnectionInfoDisplayed(true)
AlarmManagerHelper.scheduleAlarmForBroadcastReceiver(this, OfflineReceiver::class.java)
}
}
override fun handleNoConnectionUpload() {
if (userPreference.connectionInfoDisplayed()) {
showNoConnectionMessage()
} else {
handleNoConnection()
}
}
override fun showSuccessSnackbar(successMsg: Int) {
Snackbar.make(findViewById(android.R.id.content), successMsg, Toast.LENGTH_SHORT).show()
}
override fun showErrorDialog(errorMsg: Int) {
val dialog = GenericErrorDialog.newInstance(errorMsg)
dialog.show(supportFragmentManager, DIALOG_TAG)
}
override fun showErrorSnackbar(errorTextRes: Int) {
Snackbar.make(findViewById(android.R.id.content), errorTextRes, Toast.LENGTH_SHORT).show()
}
override fun showSuccessDialog(textRes: Int, okayListener: View.OnClickListener) {
val dialog = GenericSuccessDialog.newInstance(textRes, null, okayListener)
dialog.show(supportFragmentManager, DIALOG_TAG)
}
override fun launchActivity(cls: Class<*>, args: Bundle) {
val i = Intent(this, cls)
i.putExtras(args)
startActivity(i)
}
/**
* Set the result that is to be sent as the result of the request that caused this
* Activity to be launched. If result is null or this method is never called then
* the request will be canceled.
*
* @param result this is returned as the result of the AbstractAccountAuthenticator request
*/
fun setAccountAuthenticatorResult(result: Bundle) {
authResultBundle = result
}
/**
* Sends the result or a Constants.ERROR_CODE_CANCELED error if a result isn't present.
*/
override fun finish() {
if (authResponse != null) {
// send the result bundle back if set, otherwise send an error.
if (authResultBundle != null) {
authResponse!!.onResult(authResultBundle)
} else {
authResponse!!.onError(AccountManager.ERROR_CODE_CANCELED,
"canceled")
}
authResponse = null
}
super.finish()
}
override fun closeKeyboard() {
val view = currentFocus
if (view != null) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
override fun showProgressBar() {
Timber.d("showing progress bar 1 in activity: %s", activity.toString())
progress?.let { ViewAnimation.fadeIn(progress!!) }
}
override fun closeProgressBar() {
Timber.d("showing progress bar 2 inside activity")
progress?.let { ViewAnimation.fadeOut(progress!!) }
}
override fun onPause() {
super.onPause()
EventBus.getDefault().unregister(this)
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver!!)
isReceiverRegistered = false
}
override fun onDestroy() {
super.onDestroy()
dismissDialogs()
if (!disposables.isDisposed) {
disposables.clear()
}
}
private fun dismissDialogs() {
val fragmentByTag = supportFragmentManager.findFragmentByTag(DIALOG_TAG)
if (fragmentByTag != null) {
(fragmentByTag as DialogFragment).dismiss()
}
}
override fun onResume() {
super.onResume()
EventBus.getDefault().register(this)
// if (loggedIn()) {
//
// if (checkPlayServices()) {
// Timber.e("Showing progress bar 3 in activity: %s", getActivity().toString());
// // start registration service in order to check token and register if not already registered
// showProgressBar();
// registerReceiver();
// Intent intent = new Intent(this, GCMRegistrationService.class);
// startService(intent);
// }
// }
}
@Subscribe(sticky = true)
fun tokenRefreshEvent(e: AddTokenInterceptor.TokenRefreshEvent) {
EventBus.getDefault().removeStickyEvent(e)
val accountManager = accountManagerProvider!!.get()
val accounts = accountManager.getAccountsByType(AuthConstants.ACCOUNT_TYPE)
accountManager.getAuthToken(accounts[0], AuthConstants.AUTH_TOKENTYPE, null, this, { future ->
try {
if (future.result.containsKey(AccountManager.KEY_AUTHTOKEN)) {
accountManager.setAuthToken(accounts[0], AuthConstants.AUTH_TOKENTYPE, future.result.getString(AccountManager.KEY_AUTHTOKEN))
accountManager.setUserData(accounts[0], AuthConstants.USER_DATA_CURRENT_TOKEN, future.result.getString(AccountManager.KEY_AUTHTOKEN))
}
} catch (e1: OperationCanceledException) {
e1.printStackTrace()
} catch (e1: IOException) {
e1.printStackTrace()
} catch (e1: AuthenticatorException) {
e1.printStackTrace()
}
}, null)
}
@Subscribe
fun notifyItemOutOfSync(e: SyncOfflineDataService.ObjectOutOfSyncEvent) {
if (e.syncable is Meeting) {
Snackbar.make(findViewById(android.R.id.content), e.msg!!, Snackbar.LENGTH_LONG).show()
}
}
override fun showNoConnectionMessage() {
Snackbar.make(findViewById(android.R.id.content), R.string.snackbar_offline, Snackbar.LENGTH_SHORT).show()
}
override fun hideKeyboard() {
val view = this.currentFocus
if (view != null) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
private fun checkPlayServices(): Boolean {
val apiAvailability = GoogleApiAvailability.getInstance()
val resultCode = apiAvailability.isGooglePlayServicesAvailable(this)
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show()
} else {
Timber.i("This device is not supported.")
finish()
}
return false
}
return true
}
override fun sendCGMMessage(messageDTO: MessageDTO) {
try {
val gcm = GoogleCloudMessaging.getInstance(this)
val data = Bundle()
val msgJson = jsonMaper!!.writeValueAsString(messageDTO)
data.putString("body", msgJson)
val id = UUID.randomUUID().toString()
val senderId = getString(R.string.gcm_sender_id)
gcm.send("[email protected]", id, data)
} catch (ex: Exception) {
Timber.e(ex)
}
}
companion object {
const val DIALOG_TAG = "dialog"
const val PLAY_SERVICES_RESOLUTION_REQUEST = 9000
}
}
| bsd-3-clause | 58e6ff18e6fe6cfbd0bdfa9ce0e6628e | 37.394286 | 153 | 0.680161 | 4.934998 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/GivenAHaltedPlaylistEngine/WhenSettingEngineToComplete.kt | 1 | 3833 | package com.lasthopesoftware.bluewater.client.playback.engine.GivenAHaltedPlaylistEngine
import com.lasthopesoftware.EmptyUrl
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.stringlist.FileStringListUtilities
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.KnownFileProperties
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.repository.FilePropertiesContainer
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.repository.IFilePropertiesContainerRepository
import com.lasthopesoftware.bluewater.client.browsing.library.access.ISpecificLibraryProvider
import com.lasthopesoftware.bluewater.client.browsing.library.access.PassThroughLibraryStorage
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.playback.engine.PlaybackEngine
import com.lasthopesoftware.bluewater.client.playback.engine.bootstrap.PlaylistPlaybackBootstrapper
import com.lasthopesoftware.bluewater.client.playback.engine.preparation.PreparedPlaybackQueueResourceManagement
import com.lasthopesoftware.bluewater.client.playback.file.preparation.FakeDeferredPlayableFilePreparationSourceProvider
import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CompletingFileQueueProvider
import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CyclicalFileQueueProvider
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.NowPlaying
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.NowPlayingRepository
import com.lasthopesoftware.bluewater.client.playback.volume.PlaylistVolumeManager
import com.lasthopesoftware.bluewater.shared.UrlKeyHolder
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.Test
class WhenSettingEngineToComplete {
companion object {
private val library = Library()
private var nowPlaying: NowPlaying? = null
@BeforeClass
@JvmStatic
fun before() {
val fakePlaybackPreparerProvider = FakeDeferredPlayableFilePreparationSourceProvider()
library.setId(1)
library.setSavedTracksString(
FileStringListUtilities.promiseSerializedFileStringList(
listOf(
ServiceFile(1),
ServiceFile(2),
ServiceFile(3),
ServiceFile(4),
ServiceFile(5)
)
).toFuture().get()
)
library.setNowPlayingId(0)
library.setRepeating(true)
val libraryProvider = mockk<ISpecificLibraryProvider>()
every { libraryProvider.library } returns Promise(library)
val libraryStorage = PassThroughLibraryStorage()
val filePropertiesContainerRepository = mockk<IFilePropertiesContainerRepository>()
every {
filePropertiesContainerRepository.getFilePropertiesContainer(UrlKeyHolder(EmptyUrl.url, ServiceFile(4)))
} returns FilePropertiesContainer(1, mapOf(Pair(KnownFileProperties.DURATION, "100")))
val repository = NowPlayingRepository(libraryProvider, libraryStorage)
val playbackEngine =
PlaybackEngine(
PreparedPlaybackQueueResourceManagement(
fakePlaybackPreparerProvider
) { 1 },
listOf(CompletingFileQueueProvider(), CyclicalFileQueueProvider()),
repository,
PlaylistPlaybackBootstrapper(PlaylistVolumeManager(1.0f))
)
playbackEngine.playToCompletion().toFuture().get()
nowPlaying = repository.nowPlaying.toFuture().get()
}
}
@Test
fun thenNowPlayingIsSetToNotRepeating() {
assertThat(nowPlaying!!.isRepeating).isFalse
}
}
| lgpl-3.0 | a63bf135bb2bd3b5ff6f94efe0720253 | 45.743902 | 128 | 0.833812 | 4.67439 | false | false | false | false |
ansman/okhttp | okhttp/src/test/java/okhttp3/internal/io/FileSystemTest.kt | 1 | 5220 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.io
import okhttp3.SimpleProvider
import okhttp3.TestUtil
import okio.buffer
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.io.TempDir
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ArgumentsSource
import java.io.File
import java.io.IOException
class FileSystemParamProvider: SimpleProvider() {
override fun arguments() = listOf(
FileSystem.SYSTEM to TestUtil.windows,
InMemoryFileSystem() to false,
WindowsFileSystem(FileSystem.SYSTEM) to true,
WindowsFileSystem(InMemoryFileSystem()) to true
)
}
/**
* Test that our file system abstraction is consistent and sufficient for OkHttp's needs. We're
* particularly interested in what happens when open files are moved or deleted on Windows.
*/
class FileSystemTest {
@TempDir lateinit var temporaryFolder: File
private lateinit var fileSystem: FileSystem
private var windows: Boolean = false
internal fun setUp(fileSystem: FileSystem, windows: Boolean) {
this.fileSystem = fileSystem
this.windows = windows
}
@ParameterizedTest
@ArgumentsSource(FileSystemParamProvider::class)
fun `delete open for writing fails on Windows`(
parameters: Pair<FileSystem, Boolean>
) {
setUp(parameters.first, parameters.second)
val file = File(temporaryFolder, "file.txt")
expectIOExceptionOnWindows {
fileSystem.sink(file).use {
fileSystem.delete(file)
}
}
}
@ParameterizedTest
@ArgumentsSource(FileSystemParamProvider::class)
fun `delete open for appending fails on Windows`(
parameters: Pair<FileSystem, Boolean>
) {
setUp(parameters.first, parameters.second)
val file = File(temporaryFolder, "file.txt")
file.write("abc")
expectIOExceptionOnWindows {
fileSystem.appendingSink(file).use {
fileSystem.delete(file)
}
}
}
@ParameterizedTest
@ArgumentsSource(FileSystemParamProvider::class)
fun `delete open for reading fails on Windows`(
parameters: Pair<FileSystem, Boolean>
) {
setUp(parameters.first, parameters.second)
val file = File(temporaryFolder, "file.txt")
file.write("abc")
expectIOExceptionOnWindows {
fileSystem.source(file).use {
fileSystem.delete(file)
}
}
}
@ParameterizedTest
@ArgumentsSource(FileSystemParamProvider::class)
fun `rename target exists succeeds on all platforms`(
parameters: Pair<FileSystem, Boolean>
) {
setUp(parameters.first, parameters.second)
val from = File(temporaryFolder, "from.txt")
val to = File(temporaryFolder, "to.txt")
from.write("source file")
to.write("target file")
fileSystem.rename(from, to)
}
@ParameterizedTest
@ArgumentsSource(FileSystemParamProvider::class)
fun `rename source is open fails on Windows`(
parameters: Pair<FileSystem, Boolean>
) {
setUp(parameters.first, parameters.second)
val from = File(temporaryFolder, "from.txt")
val to = File(temporaryFolder, "to.txt")
from.write("source file")
to.write("target file")
expectIOExceptionOnWindows {
fileSystem.source(from).use {
fileSystem.rename(from, to)
}
}
}
@ParameterizedTest
@ArgumentsSource(FileSystemParamProvider::class)
fun `rename target is open fails on Windows`(
parameters: Pair<FileSystem, Boolean>
) {
setUp(parameters.first, parameters.second)
val from = File(temporaryFolder, "from.txt")
val to = File(temporaryFolder, "to.txt")
from.write("source file")
to.write("target file")
expectIOExceptionOnWindows {
fileSystem.source(to).use {
fileSystem.rename(from, to)
}
}
}
@ParameterizedTest
@ArgumentsSource(FileSystemParamProvider::class)
fun `delete contents of parent of file open for reading fails on Windows`(
parameters: Pair<FileSystem, Boolean>
) {
setUp(parameters.first, parameters.second)
val parentA = File(temporaryFolder, "a").also { it.mkdirs() }
val parentAB = File(parentA, "b")
val parentABC = File(parentAB, "c")
val file = File(parentABC, "file.txt")
file.write("child file")
expectIOExceptionOnWindows {
fileSystem.source(file).use {
fileSystem.deleteContents(parentA)
}
}
}
private fun File.write(content: String) {
fileSystem.sink(this).buffer().use {
it.writeUtf8(content)
}
}
private fun expectIOExceptionOnWindows(block: () -> Unit) {
try {
block()
assertThat(windows).isFalse()
} catch (_: IOException) {
assertThat(windows).isTrue()
}
}
}
| apache-2.0 | 9d41647947d409d651bea7320353eaa1 | 28.828571 | 95 | 0.704981 | 4.209677 | false | true | false | false |
tasks/tasks | app/src/main/java/org/tasks/data/Filter.kt | 1 | 2679 | package org.tasks.data
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.todoroo.andlib.utility.AndroidUtilities
import com.todoroo.astrid.api.FilterListItem.NO_ORDER
import org.tasks.Strings
import org.tasks.themes.CustomIcons.FILTER
@Entity(tableName = "filters")
class Filter {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "_id")
@Transient
var id: Long = 0
@ColumnInfo(name = "title")
var title: String? = null
@ColumnInfo(name = "sql")
private var sql: String? = null
@ColumnInfo(name = "values")
var values: String? = null
@ColumnInfo(name = "criterion")
var criterion: String? = null
@ColumnInfo(name = "f_color")
private var color: Int? = 0
@ColumnInfo(name = "f_icon")
private var icon: Int? = -1
@ColumnInfo(name = "f_order")
var order = NO_ORDER
// TODO: replace dirty hack for missing column
fun getSql(): String = sql!!.replace("tasks.userId=0", "1")
fun setSql(sql: String?) {
this.sql = sql
}
val valuesAsMap: Map<String, Any>?
get() = if (Strings.isNullOrEmpty(values)) null else AndroidUtilities.mapFromSerializedString(values)
@Suppress("RedundantNullableReturnType")
fun getColor(): Int? = color ?: 0
fun setColor(color: Int?) {
this.color = color
}
@Suppress("RedundantNullableReturnType")
fun getIcon(): Int? = icon ?: FILTER
fun setIcon(icon: Int?) {
this.icon = icon
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Filter) return false
if (id != other.id) return false
if (title != other.title) return false
if (sql != other.sql) return false
if (values != other.values) return false
if (criterion != other.criterion) return false
if (color != other.color) return false
if (icon != other.icon) return false
if (order != other.order) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + (title?.hashCode() ?: 0)
result = 31 * result + (sql?.hashCode() ?: 0)
result = 31 * result + (values?.hashCode() ?: 0)
result = 31 * result + (criterion?.hashCode() ?: 0)
result = 31 * result + (color ?: 0)
result = 31 * result + (icon ?: 0)
result = 31 * result + order
return result
}
override fun toString(): String =
"Filter(id=$id, title=$title, sql=$sql, values=$values, criterion=$criterion, color=$color, icon=$icon, order=$order)"
} | gpl-3.0 | e3e5bdc0aa7c0d07fa5cf464ad5b1e26 | 27.817204 | 130 | 0.614782 | 3.980684 | false | false | false | false |
Light-Team/ModPE-IDE-Source | editorkit/src/main/kotlin/com/brackeys/ui/editorkit/utils/LinesCollection.kt | 1 | 2617 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.brackeys.ui.editorkit.utils
class LinesCollection : Iterable<LinesCollection.Line> {
val lineCount: Int
get() = lines.size
private val lines = mutableListOf(Line(0))
fun add(line: Int, index: Int) {
lines.add(line, Line(index))
}
fun remove(line: Int) {
if (line != 0) {
lines.removeAt(line)
}
}
fun clear() {
lines.clear()
lines.add(Line(0))
}
fun shiftIndexes(fromLine: Int, shiftBy: Int) {
if (fromLine <= 0) {
return
}
if (fromLine < lineCount) {
var i = fromLine
while (i < lineCount) {
val newIndex = getIndexForLine(i) + shiftBy
if (i <= 0 || newIndex > 0) {
lines[i].start = newIndex
} else {
remove(i)
i--
}
i++
}
}
}
fun getIndexForLine(line: Int): Int {
return if (line >= lineCount) {
-1
} else {
lines[line].start
}
}
fun getLineForIndex(index: Int): Int {
var first = 0
var last = lineCount - 1
while (first < last) {
val mid = (first + last) / 2
if (index < getIndexForLine(mid)) {
last = mid
} else if (index <= getIndexForLine(mid) || index < getIndexForLine(mid + 1)) {
return mid
} else {
first = mid + 1
}
}
return lineCount - 1
}
fun getLine(line: Int): Line {
if (line > -1 && line < lineCount) {
return lines[line]
}
return Line(0)
}
override fun iterator(): Iterator<Line> {
return lines.iterator()
}
data class Line(var start: Int) : Comparable<Line> {
override fun compareTo(other: Line): Int {
return start - other.start
}
}
} | apache-2.0 | bc27d3e4049e1e75204dff7af49ec89f | 24.920792 | 91 | 0.522736 | 4.304276 | false | false | false | false |
pedroSG94/rtmp-streamer-java | rtsp/src/main/java/com/pedro/rtsp/rtsp/commands/CommandsManager.kt | 1 | 9760 | /*
* Copyright (C) 2021 pedroSG94.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pedro.rtsp.rtsp.commands
import android.util.Base64
import android.util.Log
import com.pedro.rtsp.BuildConfig
import com.pedro.rtsp.rtsp.Protocol
import com.pedro.rtsp.rtsp.commands.SdpBody.createAacBody
import com.pedro.rtsp.rtsp.commands.SdpBody.createH264Body
import com.pedro.rtsp.rtsp.commands.SdpBody.createH265Body
import com.pedro.rtsp.utils.AuthUtil.getMd5Hash
import com.pedro.rtsp.utils.RtpConstants
import com.pedro.rtsp.utils.getVideoStartCodeSize
import java.io.BufferedReader
import java.io.IOException
import java.nio.ByteBuffer
import java.util.regex.Pattern
/**
* Created by pedro on 12/02/19.
*
* Class to create request to server and parse response from server.
*/
open class CommandsManager {
var host: String? = null
private set
var port = 0
private set
var path: String? = null
private set
var sps: ByteArray? = null
private set
var pps: ByteArray? = null
private set
private var cSeq = 0
private var sessionId: String? = null
private val timeStamp: Long
var sampleRate = 32000
var isStereo = true
var protocol: Protocol = Protocol.TCP
var videoDisabled = false
var audioDisabled = false
//For udp
val audioClientPorts = intArrayOf(5000, 5001)
val videoClientPorts = intArrayOf(5002, 5003)
val audioServerPorts = intArrayOf(5004, 5005)
val videoServerPorts = intArrayOf(5006, 5007)
//For H265
var vps: ByteArray? = null
private set
//For auth
var user: String? = null
private set
var password: String? = null
private set
companion object {
private const val TAG = "CommandsManager"
private var authorization: String? = null
}
init {
val uptime = System.currentTimeMillis()
timeStamp = uptime / 1000 shl 32 and ((uptime - uptime / 1000 * 1000 shr 32)
/ 1000) // NTP timestamp
}
private fun getData(byteBuffer: ByteBuffer?): ByteArray? {
return if (byteBuffer != null) {
val startCodeSize = byteBuffer.getVideoStartCodeSize()
val bytes = ByteArray(byteBuffer.capacity() - startCodeSize)
byteBuffer.position(startCodeSize)
byteBuffer[bytes, 0, bytes.size]
bytes
} else {
null
}
}
private fun encodeToString(bytes: ByteArray?): String {
bytes?.let {
return Base64.encodeToString(it, 0, it.size, Base64.NO_WRAP)
}
return ""
}
fun setVideoInfo(sps: ByteBuffer?, pps: ByteBuffer?, vps: ByteBuffer?) {
this.sps = getData(sps)
this.pps = getData(pps)
this.vps = getData(vps) //H264 has no vps so if not null assume H265
}
fun setAudioInfo(sampleRate: Int, isStereo: Boolean) {
this.isStereo = isStereo
this.sampleRate = sampleRate
}
fun setAuth(user: String?, password: String?) {
this.user = user
this.password = password
}
fun setUrl(host: String?, port: Int, path: String?) {
this.host = host
this.port = port
this.path = path
}
fun clear() {
sps = null
pps = null
vps = null
retryClear()
}
fun retryClear() {
cSeq = 0
sessionId = null
}
private val spsString: String
get() = encodeToString(sps)
private val ppsString: String
get() = encodeToString(pps)
private val vpsString: String
get() = encodeToString(vps)
private fun addHeaders(): String {
return "CSeq: ${++cSeq}\r\n" +
"User-Agent: ${BuildConfig.LIBRARY_PACKAGE_NAME} ${BuildConfig.VERSION_NAME}\r\n" +
(if (sessionId == null) "" else "Session: $sessionId\r\n") +
(if (authorization == null) "" else "Authorization: $authorization\r\n")
}
private fun createBody(): String {
var videoBody = ""
if (!videoDisabled) {
videoBody = if (vps == null) {
createH264Body(RtpConstants.trackVideo, spsString, ppsString)
} else {
createH265Body(RtpConstants.trackVideo, spsString, ppsString, vpsString)
}
}
var audioBody = ""
if (!audioDisabled) {
audioBody = createAacBody(RtpConstants.trackAudio, sampleRate, isStereo)
}
return "v=0\r\n" +
"o=- $timeStamp $timeStamp IN IP4 127.0.0.1\r\n" +
"s=Unnamed\r\n" +
"i=N/A\r\n" +
"c=IN IP4 $host\r\n" +
"t=0 0\r\n" +
"a=recvonly\r\n" +
videoBody + audioBody
}
private fun createAuth(authResponse: String): String {
val authPattern = Pattern.compile("realm=\"(.+)\",\\s+nonce=\"(\\w+)\"", Pattern.CASE_INSENSITIVE)
val matcher = authPattern.matcher(authResponse)
//digest auth
return if (matcher.find()) {
Log.i(TAG, "using digest auth")
val realm = matcher.group(1)
val nonce = matcher.group(2)
val hash1 = getMd5Hash("$user:$realm:$password")
val hash2 = getMd5Hash("ANNOUNCE:rtsp://$host:$port$path")
val hash3 = getMd5Hash("$hash1:$nonce:$hash2")
"Digest username=\"$user\", realm=\"$realm\", nonce=\"$nonce\", uri=\"rtsp://$host:$port$path\", response=\"$hash3\""
//basic auth
} else {
Log.i(TAG, "using basic auth")
val data = "$user:$password"
val base64Data = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT)
"Basic $base64Data"
}
}
//Commands
fun createOptions(): String {
val options = "OPTIONS rtsp://$host:$port$path RTSP/1.0\r\n" + addHeaders() + "\r\n"
Log.i(TAG, options)
return options
}
open fun createSetup(track: Int): String {
val udpPorts = if (track == RtpConstants.trackVideo) videoClientPorts else audioClientPorts
val params = if (protocol === Protocol.UDP) {
"UDP;unicast;client_port=${udpPorts[0]}-${udpPorts[1]};mode=record"
} else {
"TCP;unicast;interleaved=${2 * track}-${2 * track + 1};mode=record"
}
val setup = "SETUP rtsp://$host:$port$path/streamid=$track RTSP/1.0\r\n" +
"Transport: RTP/AVP/$params\r\n" +
addHeaders() + "\r\n"
Log.i(TAG, setup)
return setup
}
fun createRecord(): String {
val record = "RECORD rtsp://$host:$port$path RTSP/1.0\r\n" +
"Range: npt=0.000-\r\n" + addHeaders() + "\r\n"
Log.i(TAG, record)
return record
}
fun createAnnounce(): String {
val body = createBody()
val announce = "ANNOUNCE rtsp://$host:$port$path RTSP/1.0\r\n" +
"Content-Type: application/sdp\r\n" +
addHeaders() +
"Content-Length: ${body.length}\r\n\r\n" +
body
Log.i(TAG, announce)
return announce
}
fun createAnnounceWithAuth(authResponse: String): String {
authorization = createAuth(authResponse)
Log.i("Auth", "$authorization")
return createAnnounce()
}
fun createTeardown(): String {
val teardown = "TEARDOWN rtsp://$host:$port$path RTSP/1.0\r\n" + addHeaders() + "\r\n"
Log.i(TAG, teardown)
return teardown
}
//Response parser
fun getResponse(reader: BufferedReader?, method: Method = Method.UNKNOWN): Command {
reader?.let { br ->
return try {
var response = ""
var line: String?
while (br.readLine().also { line = it } != null) {
response += "${line ?: ""}\n"
//end of response
if (line?.length ?: 0 < 3) break
}
Log.i(TAG, response)
if (method == Method.UNKNOWN) {
Command.parseCommand(response)
} else {
val command = Command.parseResponse(method, response)
getSession(command.text)
if (command.method == Method.SETUP && protocol == Protocol.UDP) {
getServerPorts(command.text)
}
command
}
} catch (e: IOException) {
Log.e(TAG, "read error", e)
Command(method, cSeq, -1, "")
}
}
return Command(method, cSeq, -1, "")
}
private fun getSession(response: String) {
val rtspPattern = Pattern.compile("Session:(\\s?\\w+)")
val matcher = rtspPattern.matcher(response)
if (matcher.find()) {
sessionId = matcher.group(1) ?: ""
sessionId?.let {
val temp = it.split(";")[0]
sessionId = temp.trim()
}
}
}
private fun getServerPorts(response: String) {
var isAudio = true
val clientPattern = Pattern.compile("client_port=([0-9]+)-([0-9]+)")
val clientMatcher = clientPattern.matcher(response)
if (clientMatcher.find()) {
val port = (clientMatcher.group(1) ?: "-1").toInt()
isAudio = port == audioClientPorts[0]
}
val rtspPattern = Pattern.compile("server_port=([0-9]+)-([0-9]+)")
val matcher = rtspPattern.matcher(response)
if (matcher.find()) {
if (isAudio) {
audioServerPorts[0] = (matcher.group(1) ?: "${audioClientPorts[0]}").toInt()
audioServerPorts[1] = (matcher.group(2) ?: "${audioClientPorts[1]}").toInt()
} else {
videoServerPorts[0] = (matcher.group(1) ?: "${videoClientPorts[0]}").toInt()
videoServerPorts[1] = (matcher.group(2) ?: "${videoClientPorts[1]}").toInt()
}
}
}
//Unused commands
fun createPause(): String {
return ""
}
fun createPlay(): String {
return ""
}
fun createGetParameter(): String {
return ""
}
fun createSetParameter(): String {
return ""
}
fun createRedirect(): String {
return ""
}
} | apache-2.0 | c71d1e67b864d8ba6bf29f534fb3ce46 | 28.312312 | 123 | 0.629918 | 3.556851 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/RootParameter.kt | 1 | 1661 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.parameters
import uk.co.nickthecoder.paratask.TaskDescription
class RootParameter(val taskD: TaskDescription, description: String)
: SimpleGroupParameter("root", description = description) {
override fun findTaskD(): TaskDescription = taskD
override fun findRoot(): RootParameter? = this
fun valueParameters(): List<ValueParameter<*>> {
val result = mutableListOf<ValueParameter<*>>()
fun addAll(group: GroupParameter) {
group.children.forEach { child ->
if (child is ValueParameter<*>) {
result.add(child)
}
if (child is GroupParameter) {
addAll(child)
}
}
}
addAll(this)
return result
}
override fun copy() :RootParameter {
val result =RootParameter(taskD = taskD, description = description)
copyChildren(result)
return result
}
}
| gpl-3.0 | 8a70c9a2c7e76141e2110028ddd5932f | 30.339623 | 75 | 0.671884 | 4.814493 | false | false | false | false |
arturbosch/detekt | detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/KtLintLineColCalculator.kt | 1 | 2751 | package io.gitlab.arturbosch.detekt.formatting
/**
* This object provides helper methods for calculation line and column number based on provided offset.
*
* This code duplicates [KtLint.normalizeText] and [KtLint.calculateLineColByOffset] methods,
* since they are deprecated and probably will be removed in next releases.
*/
object KtLintLineColCalculator {
private const val UTF8_BOM = "\uFEFF"
fun normalizeText(text: String): String {
return text
.replace("\r\n", "\n")
.replace("\r", "\n")
.replaceFirst(UTF8_BOM, "")
}
fun calculateLineColByOffset(
text: String
): (offset: Int) -> Pair<Int, Int> {
return buildPositionInTextLocator(text)
}
private fun buildPositionInTextLocator(
text: String
): (offset: Int) -> Pair<Int, Int> {
val textLength = text.length
val arr = ArrayList<Int>()
var endOfLineIndex = -1
do {
arr.add(endOfLineIndex + 1)
endOfLineIndex = text.indexOf('\n', endOfLineIndex + 1)
} while (endOfLineIndex != -1)
arr.add(textLength + if (arr.last() == textLength) 1 else 0)
val segmentTree = SegmentTree(arr.toIntArray())
return { offset ->
val line = segmentTree.indexOf(offset)
if (line != -1) {
val col = offset - segmentTree.get(line).left
line + 1 to col + 1
} else {
1 to 1
}
}
}
private class SegmentTree(
sortedArray: IntArray
) {
init {
require(sortedArray.size > 1) { "At least two data points are required" }
sortedArray.reduce { current, next ->
require(current <= next) { "Data points are not sorted (ASC)" }
next
}
}
private val segments: List<Segment> = sortedArray
.dropLast(1)
.mapIndexed { index: Int, element: Int ->
Segment(element, sortedArray[index + 1] - 1)
}
fun get(i: Int): Segment = segments[i]
fun indexOf(v: Int): Int = binarySearch(v, 0, segments.size - 1)
private fun binarySearch(
v: Int,
l: Int,
r: Int
): Int = when {
l > r -> -1
else -> {
val i = l + (r - l) / 2
val s = segments[i]
if (v < s.left) {
binarySearch(v, l, i - 1)
} else {
if (s.right < v) binarySearch(v, i + 1, r) else i
}
}
}
}
private data class Segment(
val left: Int,
val right: Int
)
}
| apache-2.0 | 460c9bfbb4b304fdc683677a33b83404 | 27.957895 | 103 | 0.511087 | 4.24537 | false | false | false | false |
chimbori/crux | src/main/kotlin/com/chimbori/crux/api/Fields.kt | 1 | 1885 | package com.chimbori.crux.api
/** Well-known keys to use in [Resource.metadata]. */
public object Fields {
public const val TITLE: String = "title"
public const val DESCRIPTION: String = "description"
public const val SITE_NAME: String = "site-name"
public const val LANGUAGE: String = "language"
public const val DISPLAY: String = "display"
public const val ORIENTATION: String = "orientation"
public const val PUBLISHED_AT: String = "published_at"
public const val MODIFIED_AT: String = "modified_at"
public const val THEME_COLOR_HEX: String = "theme-color-hex"
public const val THEME_COLOR_HTML: String = "theme-color-html" // Named colors like "aliceblue"
public const val BACKGROUND_COLOR_HEX: String = "background-color-hex"
public const val BACKGROUND_COLOR_HTML: String = "background-color-html" // Named colors like "aliceblue"
public const val CANONICAL_URL: String = "canonical-url"
public const val AMP_URL: String = "amp-url"
public const val FAVICON_URL: String = "favicon-url"
public const val BANNER_IMAGE_URL: String = "banner-image-url"
public const val FEED_URL: String = "feed-url"
public const val VIDEO_URL: String = "video-url"
public const val WEB_APP_MANIFEST_URL: String = "web-app-manifest-url" // https://www.w3.org/TR/appmanifest/
public const val NEXT_PAGE_URL: String = "next-page-url"
public const val PREVIOUS_PAGE_URL: String = "previous-page-url"
// For image or video resources only.
public const val ALT_TEXT: String = "alt-text"
public const val WIDTH_PX: String = "width-px"
public const val HEIGHT_PX: String = "height-px"
// For articles (estimated reading time) and audio/video content (playback duration).
public const val DURATION_MS: String = "duration-ms"
public const val TWITTER_HANDLE: String = "twitter-handle"
public const val KEYWORDS_CSV: String = "keywords-csv"
}
| apache-2.0 | 8f36b6b06b811eafa3c1e39bf91230a8 | 47.333333 | 111 | 0.72679 | 3.625 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/validation/rules/NoFragmentCycles.kt | 1 | 3126 | package graphql.validation.rules
import graphql.language.FragmentDefinition
import graphql.language.FragmentSpread
import graphql.language.Node
import graphql.validation.IValidationContext
import graphql.validation.LanguageTraversal
import graphql.validation.QueryLanguageVisitor
import graphql.validation.ValidationErrorType
import graphql.validation.*
import java.util.*
class NoFragmentCycles(validationContext: IValidationContext,
validationErrorCollector: ValidationErrorCollector)
: AbstractRule(validationContext, validationErrorCollector) {
private val fragmentSpreads = LinkedHashMap<String, List<FragmentSpread>>()
init {
prepareFragmentMap()
}
private fun prepareFragmentMap() {
val definitions = validationContext.document.definitions
for (definition in definitions) {
if (definition is FragmentDefinition) {
val fragmentDefinition = definition
fragmentSpreads.put(fragmentDefinition.name, gatherSpreads(fragmentDefinition))
}
}
}
private fun gatherSpreads(fragmentDefinition: FragmentDefinition): List<FragmentSpread> {
val fragmentSpreads = ArrayList<FragmentSpread>()
val visitor = object : QueryLanguageVisitor {
override fun enter(node: Node, path: List<Node>) {
if (node is FragmentSpread) {
fragmentSpreads.add(node)
}
}
override fun leave(node: Node, path: List<Node>) {
}
}
LanguageTraversal().traverse(fragmentDefinition, visitor)
return fragmentSpreads
}
override fun checkFragmentDefinition(fragmentDefinition: FragmentDefinition) {
val spreadPath = ArrayList<FragmentSpread>()
detectCycleRecursive(fragmentDefinition.name, fragmentDefinition.name, spreadPath)
}
private fun detectCycleRecursive(fragmentName: String,
initialName: String,
spreadPath: MutableList<FragmentSpread>) {
val fragmentSpreads = this.fragmentSpreads[fragmentName]
if (fragmentSpreads != null) {
outer@ for (fragmentSpread in fragmentSpreads) {
if (fragmentSpread.name == initialName) {
val message = "Fragment cycles not allowed"
addError(ErrorFactory().newError(ValidationErrorType.FragmentCycle, spreadPath, message))
continue
}
for (spread in spreadPath) {
if (spread == fragmentSpread) {
continue@outer
}
}
spreadPath.add(fragmentSpread)
detectCycleRecursive(fragmentSpread.name, initialName, spreadPath)
spreadPath.removeAt(spreadPath.size - 1)
}
} else {
val message = "Fragment $fragmentName not found"
addError(ErrorFactory().newError(ValidationErrorType.FragmentCycle, spreadPath, message))
}
}
}
| mit | a84dea6669c1e1c35b3a1cd2004b1ecc | 35.348837 | 109 | 0.634677 | 5.427083 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/controllers/login/SsoLoginActivity.kt | 1 | 2131 | package de.xikolo.controllers.login
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import com.yatatsu.autobundle.AutoBundleField
import de.xikolo.App
import de.xikolo.R
import de.xikolo.controllers.base.BaseActivity
import de.xikolo.controllers.dialogs.CreateTicketDialog
import de.xikolo.controllers.dialogs.CreateTicketDialogAutoBundle
import de.xikolo.controllers.webview.WebViewFragmentAutoBundle
import de.xikolo.extensions.observe
class SsoLoginActivity : BaseActivity() {
companion object {
val TAG = SsoLoginActivity::class.java.simpleName
}
@AutoBundleField
lateinit var url: String
@AutoBundleField
lateinit var title: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_blank)
setupActionBar()
setTitle(title)
val tag = "content"
val fragment = WebViewFragmentAutoBundle.builder(url)
.inAppLinksEnabled(true)
.externalLinksEnabled(true)
.build()
val fragmentManager = supportFragmentManager
if (fragmentManager.findFragmentByTag(tag) == null) {
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.content, fragment, tag)
transaction.commit()
}
App.instance.state.login
.observe(this) { isLoggedIn ->
if (isLoggedIn) {
finish()
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.helpdesk, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_helpdesk -> {
val dialog = CreateTicketDialogAutoBundle.builder().build()
dialog.show(supportFragmentManager, CreateTicketDialog.TAG)
return true
}
}
return super.onOptionsItemSelected(item)
}
}
| bsd-3-clause | ef7f79f9e254b98029bf5d99c6cda4bb | 29.014085 | 75 | 0.659784 | 5.037825 | false | false | false | false |
arturbosch/TiNBo | tinbo-ascii/src/main/kotlin/io/gitlab/arturbosch/tinbo/ascii/Ascii.kt | 1 | 2934 | package io.gitlab.arturbosch.tinbo.ascii
import io.gitlab.arturbosch.tinbo.api.marker.Command
import org.springframework.shell.core.annotation.CliCommand
import org.springframework.shell.core.annotation.CliOption
import java.awt.Color
import java.awt.Image
import java.awt.image.BufferedImage
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import javax.imageio.ImageIO
/**
* @author Artur Bosch
*/
class Ascii : Command {
override val id: String = "plugins"
@CliCommand("plugin ascii", help = "Converts an given image to ascii art.")
fun run(@CliOption(key = ["", "path"]) path: String?,
@CliOption(key = ["invert"], unspecifiedDefaultValue = "false",
specifiedDefaultValue = "true") invert: Boolean): String {
return path?.let {
val path1 = Paths.get(path)
if (Files.notExists(path1)) return "Specified path does not exist!"
if (!isImage(path1)) return "Given path points not to an image (jpg or png)."
val image = ImageIO.read(path1.toFile())
val resizeImage = resizeImage(image, 76, 0)
return ASCII(invert).convert(resizeImage)
} ?: "Provided path does not exist"
}
private fun isImage(path: Path): Boolean {
val stringPath = path.toString().toLowerCase()
fun endsWith(sub: String): Boolean = stringPath.endsWith(sub)
return endsWith("jpg") || endsWith("jpeg") || endsWith("png")
}
private fun resizeImage(image: BufferedImage, width: Int, height: Int): BufferedImage {
var cWidth = width
var cHeight = height
if (cWidth < 1) {
cWidth = 1
}
if (cHeight <= 0) {
val aspectRatio = cWidth.toDouble() / image.width * 0.5
cHeight = Math.ceil(image.height * aspectRatio).toInt()
}
val resized = BufferedImage(cWidth, cHeight, BufferedImage.TYPE_INT_RGB)
val scaled = image.getScaledInstance(cWidth, cHeight, Image.SCALE_DEFAULT)
resized.graphics.drawImage(scaled, 0, 0, null)
return resized
}
class ASCII(private val negative: Boolean = false) {
fun convert(image: BufferedImage): String {
val sb = StringBuilder((image.width + 1) * image.height)
for (y in 0 until image.height) {
if (sb.isNotEmpty()) sb.append("\n")
(0 until image.width)
.asSequence()
.map { Color(image.getRGB(it, y)) }
.map { it.red.toDouble() * 0.30 + it.blue.toDouble() * 0.59 + it.green.toDouble() * 0.11 }
.map { if (negative) returnStrNeg(it) else returnStrPos(it) }
.forEach { sb.append(it) }
}
return sb.toString()
}
private fun returnStrPos(g: Double) = when {
g >= 230.0 -> ' '
g >= 200.0 -> '.'
g >= 180.0 -> '*'
g >= 160.0 -> ':'
g >= 130.0 -> 'o'
g >= 100.0 -> '&'
g >= 70.0 -> '8'
g >= 50.0 -> '#'
else -> '@'
}
private fun returnStrNeg(g: Double) = when {
g >= 230.0 -> '@'
g >= 200.0 -> '#'
g >= 180.0 -> '8'
g >= 160.0 -> '&'
g >= 130.0 -> 'o'
g >= 100.0 -> ':'
g >= 70.0 -> '*'
g >= 50.0 -> '.'
else -> ' '
}
}
}
| apache-2.0 | 3d61961f5f3a6f15396cf3d9a7dd71aa | 29.247423 | 96 | 0.635992 | 3.11465 | false | false | false | false |
oboehm/jfachwert | src/main/kotlin/de/jfachwert/med/PZN.kt | 1 | 5127 | /*
* Copyright (c) 2020 by Oliver Boehm
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* (c)reated 25.05.2020 by oboehm
*/
package de.jfachwert.med
import de.jfachwert.AbstractFachwert
import de.jfachwert.PruefzifferVerfahren
import de.jfachwert.KSimpleValidator
import de.jfachwert.pruefung.LengthValidator
import java.util.*
/**
* Die Klasse PZN.
*
* @author oboehm
* @since 4.0 (25.05.2020)
*/
open class PZN
/**
* Erzeugt ein neues PZN-Objekt.
*
* @param code achtstellige Zahl
* @param validator Validator zur Pruefung der Zahl
*/
@JvmOverloads constructor(code: Int, validator: KSimpleValidator<Int> = VALIDATOR) : AbstractFachwert<Int, PZN>(code, validator) {
/**
* Erzeugt ein neues PZN-Objekt.
*
* @param code achtstellige Zahl
*/
constructor(code: String) : this(toInt(code)) {}
/**
* Die PZN ist 8-stellig und wird auch achtstellig ausgegeben.
*
* @return 8-stellige Zeichenkette mit PZN-Prefix
*/
override fun toString(): String {
return String.format("PZN-%08d", code)
}
companion object {
private val VALIDATOR = Validator()
private val WEAK_CACHE = WeakHashMap<Int, PZN>()
/**
* Liefert eine PZN zurueck.
*
* @param code 8-stellige Nummer
* @return die PZN
*/
@JvmStatic
fun of(code: Int): PZN {
return WEAK_CACHE.computeIfAbsent(code) { n: Int -> PZN(n) }
}
/**
* Liefert eine PZN zurueck.
*
* @param code 8-stellige Nummer
* @return die PZN
*/
@JvmStatic
fun of(code: String): PZN {
return of(toInt(code))
}
private fun toInt(s: String): Int {
return s.replace("PZN-", "", true).toInt()
}
}
/**
* Die Pruefziffer der PZN wird nach dem Modulo 11 berechnet. Dabei wird
* jede Ziffer der PZN mit einem unterschiedlichen Faktor von eins bis neun
* gewichtet. Ueber die Produkte wird die Summe gebildet und durch 11
* dividiert. Der verbleibende ganzzahlige Rest bildet die Pruefziffer.
* Bleibt als Rest die Zahl 10, dann wird diese Ziffernfolge nicht als PZN verwendet
*/
class Validator : KSimpleValidator<Int> {
/**
* Wenn der uebergebene Wert gueltig ist, soll er unveraendert
* zurueckgegeben werden, damit er anschliessend von der aufrufenden
* Methode weiterverarbeitet werden kann. Ist der Wert nicht gueltig,
* soll eine [javax.validation.ValidationException] geworfen
* werden.
*
* @param value Wert, der validiert werden soll
* @return Wert selber, wenn er gueltig ist
*/
override fun validate(value: Int): Int {
val n = VALIDATOR8.validate(value)
MOD11.validate(Integer.toString(n))
return n
}
companion object {
private val MOD11: PruefzifferVerfahren<String> = Mod11Verfahren()
private val VALIDATOR8 = LengthValidator<Int>(2, 8)
}
}
/**
* Die Pruefziffer der PZN wird nach dem Modulo 11 berechnet. Dabei wird
* jede Ziffer der PZN mit einem unterschiedlichen Faktor von 1 bis 9
* gewichtet. Ueber die Produkte wird die Summe gebildet und durch 11
* dividiert. Der verbleibende ganzzahlige Rest bildet die Pruefziffer.
* Bleibt als Rest die Zahl 10, dann wird diese Ziffernfolge nicht als PZN
* verwendet
*/
class Mod11Verfahren : PruefzifferVerfahren<String> {
/**
* Die Pruefziffer ist die letzte Ziffer.
*
* @param wert eine PZN
* @return ein Wert zwischen 0 und 9
*/
override fun getPruefziffer(wert: String): String {
return wert.last().toString()
}
/**
* Berechnet die Pruefziffer des uebergebenen Wertes.
*
* @param wert Wert
* @return errechnete Pruefziffer
*/
override fun berechnePruefziffer(wert: String): String {
val sum = getQuersumme(wert)
return Integer.toString((sum % 11) % 10)
}
private fun getQuersumme(wert: String): Int {
val digits = wert.toCharArray()
var sum = 0
val length = digits.size-1
val anfangsWichtung = 8 - length
for (i in 0 until length) {
val digit = Character.digit(digits[i], 10)
sum += digit * (anfangsWichtung + i)
}
return sum
}
}
}
| apache-2.0 | ba43336d7c08e1f308f6b3ea8d7e7bfe | 28.635838 | 130 | 0.611469 | 3.817573 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/net/TwidereDns.kt | 1 | 12104 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util.net
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import android.util.TimingLogger
import okhttp3.Dns
import org.mariotaku.ktextension.toIntOr
import de.vanita5.twittnuker.BuildConfig
import de.vanita5.twittnuker.TwittnukerConstants.HOST_MAPPING_PREFERENCES_NAME
import de.vanita5.twittnuker.constant.SharedPreferenceConstants.*
import org.xbill.DNS.*
import java.io.IOException
import java.net.InetAddress
import java.net.UnknownHostException
import java.util.*
import javax.inject.Singleton
@Singleton
class TwidereDns(val context: Context, private val preferences: SharedPreferences) : Dns {
private val hostMapping = context.getSharedPreferences(HOST_MAPPING_PREFERENCES_NAME,
Context.MODE_PRIVATE)
private val systemHosts = SystemHosts()
private var resolver: Resolver? = null
private var useResolver: Boolean = false
init {
reloadDnsSettings()
}
@Throws(UnknownHostException::class)
override fun lookup(hostname: String): List<InetAddress> {
try {
return resolveInternal(hostname, hostname, 0, useResolver)
} catch (e: IOException) {
if (e is UnknownHostException) throw e
throw UnknownHostException("Unable to resolve address " + e.message)
} catch (e: SecurityException) {
throw UnknownHostException("Security exception" + e.message)
}
}
@Throws(UnknownHostException::class)
fun lookupResolver(hostname: String): List<InetAddress> {
try {
return resolveInternal(hostname, hostname, 0, true)
} catch (e: IOException) {
if (e is UnknownHostException) throw e
throw UnknownHostException("Unable to resolve address " + e.message)
} catch (e: SecurityException) {
throw UnknownHostException("Security exception" + e.message)
}
}
fun reloadDnsSettings() {
this.resolver = null
useResolver = preferences.getBoolean(KEY_BUILTIN_DNS_RESOLVER, false)
}
fun putMapping(host: String, address: String) {
beginMappingTransaction {
this[host] = address
}
}
fun beginMappingTransaction(action: MappingTransaction.() -> Unit) {
hostMapping.edit().apply { action(MappingTransaction(this)) }.apply()
}
@Throws(IOException::class, SecurityException::class)
private fun resolveInternal(originalHost: String, host: String, depth: Int,
useResolver: Boolean): List<InetAddress> {
val logger = TimingLogger(RESOLVER_LOGTAG, "resolve")
// Return if host is an address
val fromAddressString = fromAddressString(originalHost, host)
if (fromAddressString != null) {
addLogSplit(logger, host, "valid ip address", depth)
dumpLog(logger, fromAddressString)
return fromAddressString
}
// Load from custom mapping
addLogSplit(logger, host, "start custom mapping resolve", depth)
val fromMapping = getFromMapping(host)
addLogSplit(logger, host, "end custom mapping resolve", depth)
if (fromMapping != null) {
dumpLog(logger, fromMapping)
return fromMapping
}
if (useResolver) {
// Load from /etc/hosts, since Dnsjava doesn't support hosts entry lookup
addLogSplit(logger, host, "start /etc/hosts resolve", depth)
val fromSystemHosts = fromSystemHosts(host)
addLogSplit(logger, host, "end /etc/hosts resolve", depth)
if (fromSystemHosts != null) {
dumpLog(logger, fromSystemHosts)
return fromSystemHosts
}
// Use DNS resolver
addLogSplit(logger, host, "start resolver resolve", depth)
val fromResolver = fromResolver(originalHost, host)
addLogSplit(logger, host, "end resolver resolve", depth)
if (fromResolver != null) {
dumpLog(logger, fromResolver)
return fromResolver
}
}
addLogSplit(logger, host, "start system default resolve", depth)
val fromDefault = Arrays.asList(*InetAddress.getAllByName(host))
addLogSplit(logger, host, "end system default resolve", depth)
dumpLog(logger, fromDefault)
return fromDefault
}
private fun dumpLog(logger: TimingLogger, addresses: List<InetAddress>) {
if (BuildConfig.DEBUG) return
Log.v(RESOLVER_LOGTAG, "Resolved " + addresses)
logger.dumpToLog()
}
private fun addLogSplit(logger: TimingLogger, host: String, message: String, depth: Int) {
if (BuildConfig.DEBUG) return
val sb = StringBuilder()
for (i in 0 until depth) {
sb.append(">")
}
sb.append(" ")
sb.append(host)
sb.append(": ")
sb.append(message)
logger.addSplit(sb.toString())
}
private fun fromSystemHosts(host: String): List<InetAddress>? {
try {
return systemHosts.resolve(host)
} catch (e: IOException) {
return null
}
}
@Throws(IOException::class)
private fun fromResolver(originalHost: String, host: String): List<InetAddress>? {
val resolver = this.getResolver()
val records = lookupHostName(resolver, host, true)
val addrs = ArrayList<InetAddress>(records.size)
for (record in records) {
addrs.add(addrFromRecord(originalHost, record))
}
if (addrs.isEmpty()) return null
return addrs
}
@Throws(UnknownHostException::class)
private fun getFromMapping(host: String): List<InetAddress>? {
return getFromMappingInternal(host, host, false)
}
@Throws(UnknownHostException::class)
private fun getFromMappingInternal(host: String, origHost: String, checkRecursive: Boolean): List<InetAddress>? {
if (checkRecursive && hostMatches(host, origHost)) {
// Recursive resolution, stop this call
return null
}
for ((key, value1) in hostMapping.all) {
if (hostMatches(host, key)) {
val value = value1 as String
val resolved = getResolvedIPAddress(origHost, value) ?: // Maybe another hostname
return getFromMappingInternal(value, origHost, true)
return listOf(resolved)
}
}
return null
}
private fun getResolver(): Resolver {
return this.resolver ?: run {
val tcp = preferences.getBoolean(KEY_TCP_DNS_QUERY, false)
val servers = preferences.getString(KEY_DNS_SERVER, null)?.split(';', ',', ' ') ?:
SystemDnsFetcher.get(context)
val resolvers = servers?.mapNotNull {
val segs = it.split("#", limit = 2)
if (segs.isEmpty()) return@mapNotNull null
if (!isValidIpAddress(segs[0])) return@mapNotNull null
return@mapNotNull SimpleResolver(segs[0]).apply {
if (segs.size == 2) {
val port = segs[1].toIntOr(-1)
if (port in 0..65535) {
setPort(port)
}
}
}
}
val resolver: Resolver
resolver = if (resolvers != null && resolvers.isNotEmpty()) {
ExtendedResolver(resolvers.toTypedArray())
} else {
SimpleResolver()
}
resolver.setTCP(tcp)
this.resolver = resolver
return@run resolver
}
}
@Throws(UnknownHostException::class)
private fun fromAddressString(host: String, address: String): List<InetAddress>? {
val resolved = getResolvedIPAddress(host, address) ?: return null
return listOf(resolved)
}
companion object {
private val RESOLVER_LOGTAG = "TwittnukerDns"
private fun hostMatches(host: String?, rule: String?): Boolean {
if (rule == null || host == null) return false
if (rule.startsWith(".")) return host.endsWith(rule, ignoreCase = true)
return host.equals(rule, ignoreCase = true)
}
@Throws(UnknownHostException::class)
fun getResolvedIPAddress(host: String,
address: String): InetAddress? {
var bytes = Address.toByteArray(address, Address.IPv4)
if (bytes != null)
return InetAddress.getByAddress(host, bytes)
bytes = Address.toByteArray(address, Address.IPv6)
if (bytes != null)
return InetAddress.getByAddress(host, bytes)
return null
}
private fun getInetAddressType(address: String): Int {
var bytes = Address.toByteArray(address, Address.IPv4)
if (bytes != null)
return Address.IPv4
bytes = Address.toByteArray(address, Address.IPv6)
if (bytes != null)
return Address.IPv6
return 0
}
fun isValidIpAddress(address: String): Boolean {
return getInetAddressType(address) != 0
}
@Throws(UnknownHostException::class)
private fun lookupHostName(resolver: Resolver, name: String, all: Boolean): Array<Record> {
try {
val lookup = newLookup(resolver, name, Type.A)
val a = lookup.run()
if (a == null) {
if (lookup.result == Lookup.TYPE_NOT_FOUND) {
// val aaaa = newLookup(resolver, name, Type.AAAA).run()
// if (aaaa != null) return aaaa
}
throw UnknownHostException("unknown host")
}
if (!all)
return a
// val aaaa = newLookup(resolver, name, Type.AAAA).run() ?: return a
// return a + aaaa
return a
} catch (e: TextParseException) {
throw UnknownHostException("invalid name")
}
}
@Throws(TextParseException::class)
private fun newLookup(resolver: Resolver, name: String, type: Int): Lookup {
val lookup = Lookup(name, type)
lookup.setResolver(resolver)
return lookup
}
@Throws(UnknownHostException::class)
private fun addrFromRecord(name: String, r: Record): InetAddress {
val addr: InetAddress
if (r is ARecord) {
addr = r.address
} else {
addr = (r as AAAARecord).address
}
return InetAddress.getByAddress(name, addr.address)
}
}
class MappingTransaction(private val editor: SharedPreferences.Editor) {
operator fun set(host: String, address: String) {
editor.putString(host, address)
}
fun remove(host: String) {
editor.remove(host)
}
}
} | gpl-3.0 | e66277a62368b644d81b4ba9ce6a14e2 | 35.681818 | 117 | 0.599223 | 4.702409 | false | false | false | false |
ejeinc/VR-MultiView-UDP | player/src/main/java/com/eje_c/player/MediaPlayerImpl.kt | 1 | 2808 | package com.eje_c.player
import android.content.Context
import android.graphics.SurfaceTexture
import android.media.MediaPlayer
import android.net.Uri
import android.view.Surface
class MediaPlayerImpl(
private val context: Context,
private val mp: MediaPlayer) : Player, MediaPlayer.OnInfoListener, MediaPlayer.OnCompletionListener {
private var surface: Surface? = null
init {
// Add event listeners
mp.setOnInfoListener(this)
mp.setOnCompletionListener(this)
}
override val duration: Long
get() = mp.duration.toLong()
override var currentPosition: Long
set(value) = mp.seekTo(value.toInt())
get() = mp.currentPosition.toLong()
override val isPlaying: Boolean
get() = mp.isPlaying
override var volume: Float = 1.0f
set(value) {
field = value
mp.setVolume(value, value)
}
override var onRenderFirstFrame: (() -> Unit)? = null
set(value) {
field = value
if (value != null) {
mp.setOnInfoListener { mediaPlayer, what, extra ->
when (what) {
MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START -> {
value()
return@setOnInfoListener true
}
else -> {
return@setOnInfoListener false
}
}
}
} else {
mp.setOnInfoListener(null)
}
}
override var onCompletion: (() -> Unit)? = null
override val videoWidth: Int
get() = mp.videoWidth
override val videoHeight: Int
get() = mp.videoHeight
override fun pause() = mp.pause()
override fun start() = mp.start()
override fun stop() = mp.stop()
override fun load(uri: Uri) {
mp.reset()
mp.setDataSource(context, uri)
mp.prepare()
}
override fun release() {
surface?.release()
mp.release()
}
override fun setOutput(surfaceTexture: SurfaceTexture) {
surface?.release()
surface = Surface(surfaceTexture)
mp.setSurface(surface)
}
override fun setOutput(surface: Surface) {
this.surface?.release()
this.surface = surface
mp.setSurface(surface)
}
override fun onCompletion(p0: MediaPlayer?) {
onCompletion?.invoke()
}
override fun onInfo(mediaPlayer: MediaPlayer, what: Int, extra: Int): Boolean {
when (what) {
MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START -> {
onRenderFirstFrame?.invoke()
return true
}
}
return false
}
}
| apache-2.0 | 3851aa82b985aa51d5d8400823707f7b | 23.849558 | 109 | 0.549145 | 4.883478 | false | false | false | false |
mswift42/apg | Stopwatch/app/src/main/java/mswift42/com/github/stopwatch/StopwatchActivity.kt | 1 | 2101 | package mswift42.com.github.stopwatch
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.View
import kotlinx.android.synthetic.main.activity_stopwatch.*
class StopwatchActivity : AppCompatActivity() {
private var seconds: Int = 0
private var running: Boolean = false
private var wasRunning: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_stopwatch)
if (savedInstanceState != null) {
seconds = savedInstanceState.getInt("seconds")
running = savedInstanceState.getBoolean("running")
wasRunning = savedInstanceState.getBoolean("wasRunning")
}
runTimer()
}
override fun onSaveInstanceState(savedInstanceState: Bundle?) {
savedInstanceState?.putInt("seconds", seconds)
savedInstanceState?.putBoolean("running", running)
savedInstanceState?.putBoolean("wasRunning", wasRunning)
}
fun onClickStart(view: View) {
running = true
}
fun onClickStop(view: View) {
running = false
}
fun onClickReset(view: View) {
running = false
seconds = 0
}
private fun runTimer(): Unit {
val handler = Handler()
val settimer = object : Runnable {
override fun run() {
val hours = seconds / 3600
val minutes = (seconds % 3600) / 60
val sec = seconds % 60
val time = String.format("%d:%02d:%02d", hours, minutes, seconds)
watchtimer.text = time
if (running) {
seconds++
}
handler.postDelayed(this, 1000)
}
}
handler.post(settimer)
}
override fun onStop() {
super.onStop()
wasRunning = running
running = false
}
override fun onStart() {
super.onStart()
if (wasRunning) {
running = true
}
}
} | gpl-3.0 | d615d131d041d1ae475c8a8c4d3303ab | 28.194444 | 81 | 0.592099 | 5.002381 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/PayWithGoogleUtils.kt | 1 | 2291 | package com.stripe.android
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.Currency
import java.util.Locale
import kotlin.math.pow
/**
* Public utility class for common Pay with Google-related tasks.
*/
object PayWithGoogleUtils {
/**
* Converts an integer price in the lowest currency denomination to a Google string value.
* For instance: (100L, USD) -> "1.00", but (100L, JPY) -> "100".
* @param price the price in the lowest available currency denomination
* @param currency the [Currency] used to determine how many digits after the decimal
* @return a String that can be used as a Pay with Google price string
*/
@JvmStatic
fun getPriceString(price: Int, currency: Currency): String {
val fractionDigits = currency.defaultFractionDigits
val totalLength = price.toString().length
val builder = StringBuilder()
if (fractionDigits == 0) {
for (i in 0 until totalLength) {
builder.append('#')
}
val noDecimalCurrencyFormat =
DecimalFormat(builder.toString(), DecimalFormatSymbols.getInstance(Locale.ROOT))
noDecimalCurrencyFormat.currency = currency
noDecimalCurrencyFormat.isGroupingUsed = false
return noDecimalCurrencyFormat.format(price)
}
val beforeDecimal = totalLength - fractionDigits
for (i in 0 until beforeDecimal) {
builder.append('#')
}
// So we display "0.55" instead of ".55"
if (totalLength <= fractionDigits) {
builder.append('0')
}
builder.append('.')
for (i in 0 until fractionDigits) {
builder.append('0')
}
val modBreak = 10.0.pow(fractionDigits.toDouble())
val decimalPrice = price / modBreak
// No matter the Locale, Android Pay requires a dot for the decimal separator, and Arabic
// numbers.
val symbolOverride = DecimalFormatSymbols.getInstance(Locale.ROOT)
val decimalFormat = DecimalFormat(builder.toString(), symbolOverride)
decimalFormat.currency = currency
decimalFormat.isGroupingUsed = false
return decimalFormat.format(decimalPrice)
}
}
| mit | 0542364100b72b5a45ab32173515c4d7 | 35.365079 | 97 | 0.649935 | 4.833333 | false | false | false | false |
peervalhoegen/SudoQ | sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/solverGenerator/solution/Solution.kt | 1 | 1240 | package de.sudoq.model.solverGenerator.solution
import de.sudoq.model.actionTree.Action
import java.util.*
/**
* A Solution step for the [Sudoku]. Comprises
* - a concrete [Action] that if applied to a [Sudoku] solves a [Cell]
* - [Derivation]s that lead to the solution (see [SolveDerivation] und [Action]).
*/
class Solution {
/**
* The [Action] that solves the [Cell] that belongs to the [Solution]
* or null if the Action doesn't solve a [Cell].
*/
var action: Action? = null
set(action) {
if (action != null) field = action
}
/**
* A list of [SolveDerivation]s that derive the [Action].
*/
private val derivations: MutableList<SolveDerivation> = ArrayList()
/**
* Adds a [SolveDerivation]
*
* @param derivation A SolveDerivation to add
*/
fun addDerivation(derivation: SolveDerivation) {
derivations.add(derivation)
}
/**
* Iterator over the SolveDerivations.
*
* @return An Iterator over the SolveDerivations
*/
val derivationIterator: Iterator<SolveDerivation>
get() = derivations.iterator()
fun getDerivations(): List<SolveDerivation> {
return derivations
}
} | gpl-3.0 | 25bc3597f5556a782defa7c6c69dc3d2 | 24.854167 | 82 | 0.633871 | 4.025974 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/VimeoAccount.kt | 1 | 1156 | @file:JvmName("VimeoAccountUtils")
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import java.util.Date
/**
* This class represents an authenticated user of Vimeo, either logged in or logged out.
*
* @param expiresOn The date and time that the token expires.
* @param refreshToken The refresh token string.
* @param scope The scope or scopes that the token supports.
* @param user The authenticated and logged in user.
* @param tokenType The token type.
*/
@JsonClass(generateAdapter = true)
data class VimeoAccount(
@Json(name = "access_token")
override val accessToken: String,
@Json(name = "expires_on")
val expiresOn: Date? = null,
@Json(name = "refresh_token")
val refreshToken: String? = null,
@Json(name = "scope")
val scope: String? = null,
@Json(name = "user")
val user: User? = null,
@Json(name = "token_type")
val tokenType: String? = null
) : AccessTokenProvider
/**
* True if the account represents a logged in user, false if it represents a logged out user.
*/
val VimeoAccount.isLoggedIn: Boolean
get() = user != null
| mit | b394ca8467a46d02060a3dedbca065d0 | 24.688889 | 93 | 0.696367 | 3.790164 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsStructItem.kt | 3 | 1917 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.search.SearchScope
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.macros.RsExpandedElement
import org.rust.lang.core.psi.RsElementTypes.UNION
import org.rust.lang.core.psi.RsPsiImplUtil
import org.rust.lang.core.psi.RsStructItem
import org.rust.lang.core.stubs.RsStructItemStub
import org.rust.lang.core.types.RsPsiTypeImplUtil
import org.rust.lang.core.types.ty.Ty
import javax.swing.Icon
val RsStructItem.union: PsiElement?
get() = node.findChildByType(UNION)?.psi
enum class RsStructKind {
STRUCT,
UNION
}
val RsStructItem.kind: RsStructKind get() {
val hasUnion = greenStub?.isUnion ?: (union != null)
return if (hasUnion) RsStructKind.UNION else RsStructKind.STRUCT
}
val RsStructItem.isTupleStruct get() = tupleFields != null
abstract class RsStructItemImplMixin : RsStubbedNamedElementImpl<RsStructItemStub>, RsStructItem {
constructor(node: ASTNode) : super(node)
constructor(stub: RsStructItemStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getIcon(flags: Int): Icon {
val baseIcon = when (kind) {
RsStructKind.STRUCT -> RsIcons.STRUCT
RsStructKind.UNION -> RsIcons.UNION
}
return iconWithVisibility(flags, baseIcon)
}
override val crateRelativePath: String? get() = RsPsiImplUtil.crateRelativePath(this)
override val declaredType: Ty get() = RsPsiTypeImplUtil.declaredType(this)
override fun getContext(): PsiElement? = RsExpandedElement.getContextImpl(this)
override fun getUseScope(): SearchScope = RsPsiImplUtil.getDeclarationUseScope(this) ?: super.getUseScope()
}
| mit | 5e8be446c2cbdfb23d1ff30123d3bf7f | 31.491525 | 111 | 0.754304 | 4.061441 | false | false | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/tasks/IssueTask.kt | 1 | 1080 | package com.github.jk1.ytplugin.tasks
import com.github.jk1.ytplugin.issues.model.Issue
import com.intellij.tasks.Task
import com.intellij.tasks.TaskRepository
import com.intellij.tasks.TaskType
import com.intellij.tasks.impl.LocalTaskImpl
import javax.swing.Icon
/**
* Adapter class to use YouTrack issues as Task Management plugin tasks
*/
class IssueTask(val issue: Issue, val repo: TaskRepository): Task() {
override fun getId(): String = issue.id
override fun getSummary(): String = issue.summary
override fun getDescription(): String = issue.description
override fun getCreated() = issue.createDate
override fun getUpdated() = issue.updateDate
override fun isClosed() = issue.resolved
override fun getComments() = issue.comments.map { it.asTaskManagerComment() }.toTypedArray()
override fun getIcon(): Icon = LocalTaskImpl.getIconFromType(type, isIssue)
override fun getType(): TaskType = TaskType.OTHER
override fun isIssue() = true
override fun getIssueUrl() = issue.url
override fun getRepository() = repo
} | apache-2.0 | ca7bf657969ad7931e9054d9808a7b59 | 27.447368 | 96 | 0.746296 | 4.37247 | false | false | false | false |
RSDT/Japp16 | app/src/main/java/nl/rsdt/japp/application/activities/MainActivity.kt | 1 | 12918 | package nl.rsdt.japp.application.activities
import android.app.AlertDialog
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.navigation.NavigationView
import com.google.android.material.snackbar.Snackbar
import nl.rsdt.japp.R
import nl.rsdt.japp.application.Japp
import nl.rsdt.japp.application.JappPreferences
import nl.rsdt.japp.application.fragments.CarFragment
import nl.rsdt.japp.application.fragments.HomeFragment
import nl.rsdt.japp.application.fragments.JappMapFragment
import nl.rsdt.japp.application.navigation.FragmentNavigationManager
import nl.rsdt.japp.application.navigation.NavigationManager
import nl.rsdt.japp.jotial.auth.Authentication
import nl.rsdt.japp.jotial.data.nav.Join
import nl.rsdt.japp.jotial.data.nav.Location
import nl.rsdt.japp.jotial.data.nav.Resend
import nl.rsdt.japp.jotial.data.structures.area348.AutoInzittendeInfo
import nl.rsdt.japp.jotial.maps.MapManager
import nl.rsdt.japp.jotial.maps.window.CustomInfoWindowAdapter
import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap
import nl.rsdt.japp.jotial.maps.wrapper.google.GoogleJotiMap
import nl.rsdt.japp.jotial.net.apis.AutoApi
import nl.rsdt.japp.service.AutoSocketHandler
import nl.rsdt.japp.service.LocationService
import nl.rsdt.japp.service.cloud.data.NoticeInfo
import nl.rsdt.japp.service.cloud.data.UpdateInfo
import nl.rsdt.japp.service.cloud.messaging.MessageManager
import org.acra.ACRA
import org.acra.ktx.sendWithAcra
import org.acra.log.ACRALog
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity(), IJotiMap.OnMapReadyCallback, NavigationView.OnNavigationItemSelectedListener, SharedPreferences.OnSharedPreferenceChangeListener, MessageManager.UpdateMessageListener {
/**
* Manages the GoogleMap.
*/
private var mapManager: MapManager = MapManager.instance
/**
* Manages the navigation between the fragments.
*/
private var navigationManager: NavigationManager = NavigationManager()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
JappPreferences.isFirstRun = false
/**
* Set a interceptor so that requests that give a 401 will result in a login activity.
*/
/*
Japp.setInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if(response.code() == 401) {
Authentication.startLoginActivity(MainActivity.this);
}
return response;
}
});
*/
/**
* Add this as a listener for UpdateMessages.
*/
Japp.updateManager?.add(this)
/**
* Register a on changed listener to the visible release_preferences.
*/
JappPreferences.visiblePreferences.registerOnSharedPreferenceChangeListener(this)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
/**
* Setup the MapManager.
*/
mapManager.onIntentCreate(intent)
mapManager.onCreate(savedInstanceState)
/**
* Setup the NavigationDrawer.
*/
val drawer = findViewById<DrawerLayout>(R.id.drawer_layout)
val toggle = ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer.addDrawerListener(toggle)
toggle.syncState()
/**
* Setup the NavigationView.
*/
val navigationView = findViewById<NavigationView>(R.id.nav_view)
navigationView.setNavigationItemSelectedListener(this)
/**
* Initialize the NavigationManager.
*/
navigationManager.initialize(this)
navigationManager.onSavedInstance(savedInstanceState)
}
public override fun onSaveInstanceState(savedInstanceState: Bundle) {
navigationManager.onSaveInstanceState(savedInstanceState)
mapManager.onSaveInstanceState(savedInstanceState)
val id = JappPreferences.accountId
if (id >= 0) {
val autoApi = Japp.getApi(AutoApi::class.java)
autoApi.getInfoById(JappPreferences.accountKey, id).enqueue(object :
Callback<AutoInzittendeInfo> {
override fun onResponse(call: Call<AutoInzittendeInfo>, response: Response<AutoInzittendeInfo>) {
if (response.code() == 200) {
val autoInfo = response.body()
if (autoInfo != null) {
val auto = autoInfo.autoEigenaar!!
AutoSocketHandler.join(Join(JappPreferences.accountUsername, auto))
}
}
}
override fun onFailure(call: Call<AutoInzittendeInfo>, t: Throwable) {
t.sendWithAcra()
Log.e(TAG, t.toString())
}
})
}
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState)
}
override fun onMapReady(map: IJotiMap) {
/**
* First set the custom InfoWindowAdapter and then invoke the onMapReady on the MapManager.
*/
if (map is GoogleJotiMap) {
map.setInfoWindowAdapter(CustomInfoWindowAdapter(layoutInflater, map.googleMap!!)) //// TODO: 07/08/17 change the GoogleMap to a JotiMap
} else {
//// TODO: 09/08/17 do stuff
}
mapManager.onMapReady(map)
mapManager.update()
}
/**
* TODO: don't use final here
*/
override fun onUpdateMessageReceived(info: UpdateInfo?) {
if (JappPreferences.isAutoUpdateEnabled) {
Snackbar.make(findViewById(R.id.container), getString(R.string.updating_type, info?.type), Snackbar.LENGTH_LONG).show()
mapManager.onUpdateMessageReceived(info)
} else {
Snackbar.make(findViewById(R.id.container), getString(R.string.update_available, info?.type), Snackbar.LENGTH_LONG)
.setAction(getString(R.string.update)) { mapManager.onUpdateMessageReceived(info) }
.show()
}
}
/**
* TODO: don't use final here
*/
override fun onNoticeMessageReceived(info: NoticeInfo?) {
this.runOnUiThread {
AlertDialog.Builder(this@MainActivity)
.setTitle(info?.title)
.setMessage(info?.body)
.setIcon(info?.drawable?:0)
.create()
.show()
}
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (JappPreferences.USE_OSM == key) {
recreate()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the options menu from XML
val inflater = menuInflater
inflater.inflate(R.menu.options_menu, menu)
/**
* TODO: fix search system
*/
//searchManager.onCreateOptionsMenu(menu);
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.refresh) {
mapManager.update()
/**
* Update the vos status on the home fragment.
*/
val fragment = navigationManager.getFragment(FragmentNavigationManager.FRAGMENT_HOME) as HomeFragment?
if (fragment?.isAdded==true) {
fragment.refresh()
}
val carfragment = navigationManager.getFragment(FragmentNavigationManager.FRAGMENT_CAR) as CarFragment?
carfragment?.refresh()
val id = JappPreferences.accountId
if (id >= 0) {
val autoApi = Japp.getApi(AutoApi::class.java)
autoApi.getInfoById(JappPreferences.accountKey, id).enqueue(object :
Callback<AutoInzittendeInfo> {
override fun onResponse(call: Call<AutoInzittendeInfo>, response: Response<AutoInzittendeInfo>) {
if (response.code() == 200) {
val autoInfo = response.body()
if (autoInfo != null) {
val auto = autoInfo.autoEigenaar!!
AutoSocketHandler.join(Join(JappPreferences.accountUsername, auto))
AutoSocketHandler.resend(Resend(auto))
}
}
}
override fun onFailure(call: Call<AutoInzittendeInfo>, t: Throwable) {
Log.e(TAG, t.message?:"error")
t.sendWithAcra()
}
})
}
return true
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
val drawer = findViewById<DrawerLayout>(R.id.drawer_layout)
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
if (navigationManager.hasBackStack()) {
navigationManager.onBackPressed()
} else {
super.onBackPressed()
}
}
}
public override fun onStart() {
super.onStart()
}
public override fun onResume() {
super.onResume()
navigationManager.setupMap(this)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
val action = intent.action
if (action != null && action == LocationService.ACTION_REQUEST_LOCATION_SETTING) {
val mapFragment = navigationManager.getFragment(FragmentNavigationManager.FRAGMENT_MAP) as JappMapFragment?
mapFragment?.movementManager?.requestLocationSettingRequest()
}
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == JappMapFragment.REQUEST_CHECK_SETTINGS) {
val mapFragment = navigationManager.getFragment(FragmentNavigationManager.FRAGMENT_MAP) as JappMapFragment?
mapFragment?.movementManager?.postResolutionResultToService(resultCode)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
val id = item.itemId
if (id == R.id.nav_home) {
navigationManager.switchTo(FragmentNavigationManager.FRAGMENT_HOME)
} else if (id == R.id.nav_map) {
navigationManager.switchTo(FragmentNavigationManager.FRAGMENT_MAP)
} else if (id == R.id.nav_settings) {
navigationManager.switchTo(FragmentNavigationManager.FRAGMENT_SETTINGS)
} else if (id == R.id.nav_car) {
navigationManager.switchTo(FragmentNavigationManager.FRAGMENT_CAR)
} else if (id == R.id.nav_about) {
navigationManager.switchTo(FragmentNavigationManager.FRAGMENT_ABOUT)
} else if (id == R.id.nav_help) {
navigationManager.switchTo(FragmentNavigationManager.FRAGMENT_HELP)
} else if (id == R.id.nav_log_out) {
Authentication.startLoginActivity(this)
}
val drawer = findViewById<DrawerLayout>(R.id.drawer_layout)
drawer.closeDrawer(GravityCompat.START)
return true
}
public override fun onStop() {
super.onStop()
}
public override fun onDestroy() {
super.onDestroy()
Japp.setInterceptor(null)
/**
* Remove this as UpdateMessageListener.
*/
Japp.updateManager?.remove(this)
/**
* Unregister this as OnSharedPreferenceChangeListener.
*/
JappPreferences.visiblePreferences.unregisterOnSharedPreferenceChangeListener(this)
mapManager.onDestroy()
navigationManager.onDestroy()
}
companion object {
/**
* Defines a tag for this class.
*/
val TAG = "MainActivity"
}
}
| apache-2.0 | 9814323ddd782319289cd1c58519c67c | 35.908571 | 210 | 0.627032 | 5.055969 | false | false | false | false |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/service/GeofencingRegistrationService.kt | 1 | 3414 | package de.tum.`in`.tumcampusapp.service
import android.Manifest
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.support.v4.app.JobIntentService
import android.support.v4.content.ContextCompat
import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofencingClient
import com.google.android.gms.location.GeofencingRequest
import com.google.android.gms.location.LocationServices
import de.tum.`in`.tumcampusapp.utils.Const
import de.tum.`in`.tumcampusapp.utils.Const.ADD_GEOFENCE_EXTRA
import de.tum.`in`.tumcampusapp.utils.Const.GEOFENCING_SERVICE_JOB_ID
import de.tum.`in`.tumcampusapp.utils.Utils
/**
* Service that receives Geofencing requests and registers them.
*/
class GeofencingRegistrationService : JobIntentService() {
private lateinit var locationClient: GeofencingClient
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
return Service.START_STICKY
}
override fun onCreate() {
super.onCreate()
locationClient = LocationServices.getGeofencingClient(baseContext)
Utils.log("Service started")
}
@SuppressLint("MissingPermission")
override fun onHandleWork(intent: Intent) {
if (!isLocationPermissionGranted()) {
return
}
val request = intent.getParcelableExtra<GeofencingRequest>(Const.ADD_GEOFENCE_EXTRA) ?: return
val geofenceIntent = Intent(this, GeofencingUpdateReceiver::class.java)
val geofencePendingIntent = PendingIntent.getBroadcast(
this, 0, geofenceIntent, PendingIntent.FLAG_UPDATE_CURRENT)
locationClient.addGeofences(request, geofencePendingIntent)
Utils.log("Registered new Geofence")
}
private fun isLocationPermissionGranted(): Boolean {
return ContextCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
}
companion object {
@JvmStatic fun startGeofencing(context: Context, work: Intent) {
enqueueWork(context, GeofencingRegistrationService::class.java, GEOFENCING_SERVICE_JOB_ID, work)
}
/**
* Helper method for creating an intent containing a geofencing request
*/
fun buildGeofence(context: Context, id: String, latitude: Double, longitude: Double, range: Float): Intent {
val intent = Intent(context, GeofencingRegistrationService::class.java)
val geofence = Geofence.Builder()
.setRequestId(id)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(latitude, longitude, range)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build()
val geofencingRequest = GeofencingRequest.Builder()
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER or GeofencingRequest.INITIAL_TRIGGER_EXIT)
.addGeofences(arrayListOf(geofence))
.build()
return intent.putExtra(ADD_GEOFENCE_EXTRA, geofencingRequest)
}
}
} | gpl-3.0 | cc7a3ccbd0b0c5955a867439ae550d9f | 38.709302 | 121 | 0.706796 | 4.969432 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/social/UserStyles.kt | 1 | 1258 | package com.habitrpg.android.habitica.models.social
import com.habitrpg.android.habitica.models.Avatar
import com.habitrpg.android.habitica.models.AvatarFlags
import com.habitrpg.android.habitica.models.user.Items
import com.habitrpg.android.habitica.models.user.Outfit
import com.habitrpg.android.habitica.models.user.Preferences
import com.habitrpg.android.habitica.models.user.Stats
import io.realm.RealmObject
import io.realm.annotations.RealmClass
@RealmClass(embedded = true)
open class UserStyles : RealmObject(), Avatar {
override val currentMount: String?
get() = items?.currentMount
override val currentPet: String?
get() = items?.currentPet
override val sleep: Boolean
get() = false
override val gemCount: Int
get() = 0
override val hourglassCount: Int
get() = 0
override val costume: Outfit?
get() = items?.gear?.costume
override val equipped: Outfit?
get() = items?.gear?.equipped
override val hasClass: Boolean
get() {
return false
}
override var stats: Stats? = null
override var preferences: Preferences? = null
override val flags: AvatarFlags?
get() = null
private var items: Items? = null
}
| gpl-3.0 | eeaada953078db856c22c8fb4943a180 | 27.590909 | 60 | 0.699523 | 4.308219 | false | false | false | false |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/blacklist/adapter/BlacklistAdapter.kt | 1 | 2221 | package com.sedsoftware.yaptalker.presentation.feature.blacklist.adapter
import androidx.collection.SparseArrayCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import com.sedsoftware.yaptalker.R
import com.sedsoftware.yaptalker.domain.device.Settings
import com.sedsoftware.yaptalker.presentation.base.adapter.YapEntityDelegateAdapter
import com.sedsoftware.yaptalker.presentation.model.DisplayedItemType
import com.sedsoftware.yaptalker.presentation.model.base.BlacklistedTopicModel
import javax.inject.Inject
class BlacklistAdapter @Inject constructor(
clickListener: BlacklistElementsClickListener,
settings: Settings
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var items: ArrayList<BlacklistedTopicModel>
private var delegateAdapters = SparseArrayCompat<YapEntityDelegateAdapter>()
init {
delegateAdapters.put(
DisplayedItemType.BLACKLISTED_TOPIC, BlacklistDelegateAdapter(clickListener, settings)
)
items = ArrayList()
setHasStableIds(true)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
delegateAdapters.get(viewType)!!.onCreateViewHolder(parent)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
delegateAdapters.get(getItemViewType(position))?.onBindViewHolder(holder, items[position])
with(holder.itemView) {
AnimationUtils.loadAnimation(context, R.anim.recyclerview_fade_in).apply {
startAnimation(this)
}
}
}
override fun onViewDetachedFromWindow(holder: ViewHolder) {
super.onViewDetachedFromWindow(holder)
holder.itemView.clearAnimation()
}
override fun getItemViewType(position: Int): Int =
items[position].getEntityType()
override fun getItemCount() =
items.size
override fun getItemId(position: Int) =
position.toLong()
fun setTopics(topics: List<BlacklistedTopicModel>) {
items.clear()
items.addAll(topics)
notifyDataSetChanged()
}
}
| apache-2.0 | 1160aa237e56ae9a08dcf1c4e7550137 | 33.169231 | 98 | 0.746511 | 5.177156 | false | false | false | false |
stoyicker/dinger | app/src/main/kotlin/app/settings/SettingsPreferenceFragmentCompat.kt | 1 | 2428 | package app.settings
import android.annotation.SuppressLint
import android.content.Intent
import android.content.startIntent
import android.net.Uri
import android.os.Bundle
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceFragmentCompat
import domain.autoswipe.ImmediatePostAutoSwipeUseCase
import io.reactivex.observers.DisposableCompletableObserver
import io.reactivex.schedulers.Schedulers
import org.stoyicker.dinger.R
internal class SettingsPreferenceFragmentCompat : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.prefs_settings, rootKey)
addTriggerToAutoswipeEnabledPreference()
initializeSharePreference()
initializeAboutTheAppPreference()
}
private fun addTriggerToAutoswipeEnabledPreference() {
findPreference(context?.getString(R.string.preference_key_autoswipe_enabled))
?.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, value ->
if (value is Boolean && value) {
ImmediatePostAutoSwipeUseCase(context!!, Schedulers.trampoline()).execute(
object : DisposableCompletableObserver() {
override fun onComplete() {
}
override fun onError(error: Throwable) {
}
})
}
true
}
}
private fun initializeSharePreference() {
findPreference(context?.getString(R.string.preference_key_share))
.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
@SuppressLint("InlinedApi")
flags += Intent.FLAG_ACTIVITY_NEW_DOCUMENT
putExtra(Intent.EXTRA_TEXT, context?.getString(
R.string.dinger_website_download))
}
context?.startIntent(Intent.createChooser(
intent, getString(R.string.action_share_title)))
true
}
}
private fun initializeAboutTheAppPreference() {
findPreference(context?.getString(R.string.preference_key_about_the_app))
.onPreferenceClickListener = Preference.OnPreferenceClickListener {
context?.startIntent(Intent(
Intent.ACTION_VIEW, Uri.parse(getString(R.string.dinger_website))))
true
}
}
companion object {
const val FRAGMENT_TAG = "SettingsPreferenceFragmentCompat"
}
}
| mit | 7b305fdecc1d7e649a0905d56b38ef17 | 34.705882 | 90 | 0.7257 | 4.995885 | false | false | false | false |
codehz/container | app/src/main/java/one/codehz/container/SpaceManagerActivity.kt | 1 | 3080 | package one.codehz.container
import android.app.ActivityManager
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Menu
import android.view.MenuItem
import one.codehz.container.adapters.SpaceManagerAdapter
import one.codehz.container.base.BaseActivity
import one.codehz.container.ext.MakeLoaderCallbacks
import one.codehz.container.ext.get
import one.codehz.container.ext.systemService
import one.codehz.container.models.SpaceManagerModel
import org.apache.commons.io.FileUtils
import java.io.File
class SpaceManagerActivity : BaseActivity(R.layout.space_manager) {
val contentList by lazy<RecyclerView> { this[R.id.content_list] }
val contentAdapter by lazy { SpaceManagerAdapter() }
val linearLayoutManager by lazy { LinearLayoutManager(this) }
companion object {
val APP_DATA = 0
val APP_OPT = 1
}
val appDataLoader by MakeLoaderCallbacks({ this }, { dataList[APP_DATA].amount = it; syncList() }) {
val data = filesDir.parent
FileUtils.byteCountToDisplaySize(FileUtils.sizeOfDirectoryAsBigInteger(File("$data/virtual/data")))
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.space_manager, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.clear_data -> {
systemService<ActivityManager>(Context.ACTIVITY_SERVICE).clearApplicationUserData()
true
}
android.R.id.home -> {
finish()
true
}
else -> false
}
val appOptLoader by MakeLoaderCallbacks({ this }, { dataList[APP_OPT].amount = it; syncList() }) {
val data = filesDir.parent
FileUtils.byteCountToDisplaySize(FileUtils.sizeOfDirectoryAsBigInteger(File("$data/virtual/opt")))
}
val dataList by lazy {
mutableListOf(
SpaceManagerModel(getString(R.string.space_application_in_container), ManageContainerApplicationStorageActivity::class),
SpaceManagerModel(getString(R.string.container_application_optimization_data), ManageContainerApplicationStorageActivity::class)
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setDisplayShowHomeEnabled(true)
}
with(contentList) {
adapter = contentAdapter
layoutManager = linearLayoutManager
itemAnimator = DefaultItemAnimator()
}
syncList()
supportLoaderManager.restartLoader(APP_DATA, null, appDataLoader)
supportLoaderManager.restartLoader(APP_OPT, null, appOptLoader)
}
val syncList: () -> Unit
get() = contentAdapter.updateModels(dataList.map { it.clone() })
} | gpl-3.0 | dc4e0440402b5d8b46e9d0bb89ff8575 | 34.413793 | 144 | 0.703247 | 4.652568 | false | false | false | false |
EventFahrplan/EventFahrplan | app/src/main/java/nerd/tuxmobil/fahrplan/congress/repositories/SessionsTransformer.kt | 1 | 3193 | package nerd.tuxmobil.fahrplan.congress.repositories
import androidx.annotation.VisibleForTesting
import nerd.tuxmobil.fahrplan.congress.models.RoomData
import nerd.tuxmobil.fahrplan.congress.models.ScheduleData
import nerd.tuxmobil.fahrplan.congress.models.Session
class SessionsTransformer @VisibleForTesting constructor(
private val roomProvider: RoomProvider
) {
companion object {
fun createSessionsTransformer(): SessionsTransformer {
val roomProvider = object : RoomProvider {
override val prioritizedRooms: List<String> = listOf(
"Saal 1",
"Saal 2",
"Saal G",
"Saal 6",
"Saal 17",
"Lounge"
)
override val deprioritizedRooms: List<String> = emptyList()
}
return SessionsTransformer(roomProvider)
}
}
/**
* Transforms the given [sessions] for the given [dayIndex] into a [ScheduleData] object.
*
* Apart from the [dayIndex] it contains a list of room names and their associated sessions
* (sorted by [Session.dateUTC]). Rooms names are added in a defined order: room names of
* prioritized rooms first, then all other room names in the order defined by the given session.
* After adding room names the original order [Session.roomIndex] is no longer of interest.
*/
fun transformSessions(dayIndex: Int, sessions: List<Session>): ScheduleData {
// Pre-populate the map with prioritized rooms
val roomMap = roomProvider.prioritizedRooms
.associateWith { mutableListOf<Session>() }
.toMutableMap()
val sortedSessions = sessions.sortedBy { it.roomIndex }
for (session in sortedSessions) {
val sessionsInRoom = roomMap.getOrPut(session.room) { mutableListOf() }
sessionsInRoom.add(session)
}
val roomDataList = roomMap.mapNotNull { (roomName, sessions) ->
if (sessions.isEmpty()) {
// Drop prioritized rooms without sessions
null
} else {
RoomData(
roomName = roomName,
sessions = sessions.sortedBy { it.dateUTC }.toList()
)
}
}.sortWithDeprioritizedRooms(roomProvider.deprioritizedRooms)
return ScheduleData(dayIndex, roomDataList)
}
}
interface RoomProvider {
val prioritizedRooms: List<String>
val deprioritizedRooms: List<String>
}
/**
* Moves all [RoomData] items with a room name contained in [deprioritizedRooms] to the end of the list.
* The order of room names in the [deprioritizedRooms] list is applied to the receiving list.
*/
private fun List<RoomData>.sortWithDeprioritizedRooms(deprioritizedRooms: List<String>): List<RoomData> {
if (deprioritizedRooms.isEmpty()) {
return this
}
val (tail, head) = partition { deprioritizedRooms.contains(it.roomName) }
val sortedTail = deprioritizedRooms.mapNotNull { room ->
tail.firstOrNull { room == it.roomName }
}
return head + sortedTail
}
| apache-2.0 | 0aeb8db7ece0aba0f0c92628c03d07cf | 35.701149 | 105 | 0.637645 | 4.702504 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mcp/srg/StandardSrgParser.kt | 1 | 1750 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.srg
import com.demonwav.mcdev.util.MemberReference
import com.google.common.collect.ImmutableBiMap
import java.nio.file.Files
import java.nio.file.Path
object StandardSrgParser : SrgParser {
override fun parseSrg(path: Path): McpSrgMap {
val classMapBuilder = ImmutableBiMap.builder<String, String>()
val fieldMapBuilder = ImmutableBiMap.builder<MemberReference, MemberReference>()
val methodMapBuilder = ImmutableBiMap.builder<MemberReference, MemberReference>()
val srgNames = hashMapOf<String, String>()
Files.lines(path).forEach { line ->
val parts = line.split(' ')
when (parts[0]) {
"CL:" -> {
val srg = parts[1].replace('/', '.')
val mcp = parts[2].replace('/', '.')
classMapBuilder.put(mcp, srg)
}
"FD:" -> {
val mcp = SrgMemberReference.parse(parts[1])
val srg = SrgMemberReference.parse(parts[2])
fieldMapBuilder.put(mcp, srg)
srgNames[srg.name] = mcp.name
}
"MD:" -> {
val mcp = SrgMemberReference.parse(parts[1], parts[2])
val srg = SrgMemberReference.parse(parts[3], parts[4])
methodMapBuilder.put(mcp, srg)
srgNames[srg.name] = mcp.name
}
}
}
return McpSrgMap(classMapBuilder.build(), fieldMapBuilder.build(), methodMapBuilder.build(), srgNames)
}
}
| mit | 678e8214dc3e632c457f0fc41c6dce3e | 34 | 110 | 0.560571 | 4.43038 | false | false | false | false |
RobotPajamas/Blueteeth | blueteeth/src/main/kotlin/com/robotpajamas/blueteeth/BlueteethDevice.kt | 1 | 14804 | package com.robotpajamas.blueteeth
import android.bluetooth.*
import android.content.Context
import android.os.Handler
import android.os.Looper
import com.robotpajamas.blueteeth.extensions.compositeId
import com.robotpajamas.blueteeth.extensions.getCharacteristic
import com.robotpajamas.blueteeth.models.*
import com.robotpajamas.dispatcher.Dispatch
import com.robotpajamas.dispatcher.Result
import com.robotpajamas.dispatcher.RetryPolicy
import com.robotpajamas.dispatcher.SerialDispatcher
import java.util.*
// TODO: Make this object threadsafe and async-safe (called twice in a row, should return a failure?)
class BlueteethDevice private constructor() : Device {
// TODO: The handler posts would be better if abstracted away - Does this need to be dependency injected for testing?
private var context: Context? = null
private val handler = Handler(Looper.getMainLooper())
private var bluetoothDevice: BluetoothDevice? = null
private var bluetoothGatt: BluetoothGatt? = null
private val subscriptionDescriptor = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
private var dispatcher = SerialDispatcher()
val name: String
get() = bluetoothDevice?.name ?: ""
val id: String
get() = bluetoothDevice?.address ?: ""
/** Connectable **/
private var autoReconnect = false
private var connectionHandler: ConnectionHandler? = null
var isConnected = false
private set
// Autoreconnect == true is a slow connection, false is fast
// https://stackoverflow.com/questions/22214254/android-ble-connect-slowly
override fun connect(timeout: Int?, autoReconnect: Boolean, block: ConnectionHandler?) {
BLog.d("connect: Attempting to connect: Timeout=$timeout, autoReconnect=$autoReconnect")
this.autoReconnect = autoReconnect
connectionHandler = block
// if (bluetoothGatt != null) {
// bluetoothGatt?.close()
// bluetoothGatt = null
// }
// TODO: Passing in a null context seems to work, but what are the consequences?
// TODO: Should I grab the application context from the BlueteethManager? Seems odd...
handler.post {
if (isConnected) {
BLog.d("connect: Already connected, returning - disregarding autoReconnect")
connected()
return@post
}
if (bluetoothGatt != null) {
bluetoothGatt?.connect()
} else {
bluetoothGatt = bluetoothDevice?.connectGatt(null, autoReconnect, mGattCallback)
}
}
}
override fun disconnect(autoReconnect: Boolean) {
BLog.d("disconnect: Disconnecting... autoReconnect=$autoReconnect")
this.autoReconnect = autoReconnect
handler.post {
bluetoothGatt?.disconnect() ?: BLog.d("disconnect: Cannot disconnect - GATT is null")
}
}
private fun connected() {
isConnected = true
connectionHandler?.invoke(isConnected)
}
// private fun connecting() {
//
// }
private fun disconnected() {
isConnected = false
// Clear all pending queue items
dispatcher.clear()
// Clear all subscriptions
notifications.clear()
// Call appropriate callbacks
connectionHandler?.invoke(isConnected)
}
/** Discoverable **/
override fun discoverServices(block: ServiceDiscovery?) {
BLog.d("discoverServices: Attempting to discover services")
val item = Dispatch<Boolean>(
id = "discoverServices", // TODO: Need something better than hardcoded string
timeout = 60, // Discovery can take a helluva long time depending on phone
retryPolicy = RetryPolicy.RETRY,
execution = { cb ->
if (!isConnected || bluetoothGatt == null) {
// TODO: Need proper exceptions/errors
cb(Result.Failure(RuntimeException("discoverServices: Device is not connected, or GATT is null")))
return@Dispatch
}
bluetoothGatt?.discoverServices()
},
completion = { result ->
result.onFailure {
BLog.e("Service discovery failed with $it")
}
block?.invoke(result)
})
dispatcher.enqueue(item)
}
/** Readable **/
override fun read(characteristic: UUID, service: UUID, block: ReadHandler) {
BLog.d("read: Attempting to read $characteristic")
val compositeId = service.toString() + characteristic.toString()
val item = Dispatch<ByteArray>(
id = compositeId,
timeout = 3,
retryPolicy = RetryPolicy.RETRY,
execution = { cb ->
if (!isConnected) {
cb(Result.Failure(RuntimeException("read: Device is not connected")))
return@Dispatch
}
val gattCharacteristic = bluetoothGatt?.getCharacteristic(characteristic, service)
?: run {
val error = "read: Failed to get Gatt Char: $characteristic in $service from $bluetoothGatt"
cb(Result.Failure(RuntimeException(error)))
return@Dispatch
}
bluetoothGatt?.readCharacteristic(gattCharacteristic)
}) { result ->
result.onFailure {
BLog.e("Read completion failed with $it")
}
block(result)
}
dispatcher.enqueue(item)
}
private val notifications = HashMap<String, ReadHandler>()
override fun subscribeTo(characteristic: UUID, service: UUID, block: ReadHandler) {
BLog.d("subscribeTo: Adding Notification listener to %s", characteristic.toString())
val compositeId = service.toString() + characteristic.toString()
val item = Dispatch<Boolean>(
id = subscriptionDescriptor.toString(),
timeout = 3,
retryPolicy = RetryPolicy.RETRY,
execution = { cb ->
if (!isConnected) {
cb(Result.Failure(RuntimeException("subscribe: Device is not connected")))
return@Dispatch
}
val gattCharacteristic = bluetoothGatt?.getCharacteristic(characteristic, service)
?: run {
val error = "subscribe: Failed to get Gatt Char: $characteristic in $service from $bluetoothGatt"
cb(Result.Failure(RuntimeException(error)))
return@Dispatch
}
val gattDescriptor = gattCharacteristic.getDescriptor(subscriptionDescriptor)
?: run {
val error = "subscribe: Descriptor not available - $compositeId"
cb(Result.Failure(RuntimeException(error)))
return@Dispatch
}
notifications[compositeId] = block
bluetoothGatt?.setCharacteristicNotification(gattCharacteristic, true)
gattDescriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
bluetoothGatt?.writeDescriptor(gattDescriptor)
}) { result ->
result.onFailure {
BLog.e("Read completion failed with $it")
}
}
dispatcher.enqueue(item)
}
/** Writable **/
override fun write(data: ByteArray, characteristic: UUID, service: UUID, type: Writable.Type, block: WriteHandler?) {
BLog.d("write: Attempting to write ${Arrays.toString(data)} to $characteristic")
val compositeId = service.toString() + characteristic.toString()
val item = Dispatch<Boolean>(
id = compositeId,
timeout = 3,
retryPolicy = RetryPolicy.RETRY,
execution = { cb ->
if (!isConnected) {
cb(Result.Failure(RuntimeException("write: Device is not connected, or GATT is null")))
return@Dispatch
}
val gattCharacteristic = bluetoothGatt?.getCharacteristic(characteristic, service)
?: run {
val error = "write: Failed to get Gatt Char: $characteristic in $service from $bluetoothGatt"
cb(Result.Failure(RuntimeException(error)))
return@Dispatch
}
gattCharacteristic.value = data
gattCharacteristic.writeType = when (type) {
Writable.Type.WITH_RESPONSE -> BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
Writable.Type.WITHOUT_RESPONSE -> BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
}
bluetoothGatt?.writeCharacteristic(gattCharacteristic)
}) { result ->
result.onFailure {
BLog.e("Write completion failed with $it")
}
block?.invoke(result)
}
dispatcher.enqueue(item)
}
internal constructor(context: Context, device: BluetoothDevice) : this() {
bluetoothDevice = device
// TODO: Need this for registering to the bonding process - ugly...
this.context = context
}
internal constructor(context: Context,
device: BluetoothDevice,
rssi: Int,
scanRecord: ByteArray) : this(context, device) {
// this.rssi = rssi
// mScanRecord = scanRecord
}
fun close() {
bluetoothGatt?.disconnect()
handler.post {
bluetoothGatt?.close()
bluetoothGatt = null
}
}
/***
* Should never really get here, only if someone forgets to call close() explicitly
* @throws Throwable
*/
@Throws(Throwable::class)
private fun finalize() {
try {
close()
} finally {
BLog.e("Could not close the BlueteethDevice")
}
}
private val mGattCallback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
super.onConnectionStateChange(gatt, status, newState)
BLog.d("onConnectionStateChange - gatt: $gatt, status: $status, newState: $newState")
// Removed check for GATT_SUCCESS - do we care? I think the current state is all that matters...
// TODO: When changing isConnected to a ConnectionState - account for STATE_CONNECTING as well
when (newState) {
BluetoothProfile.STATE_CONNECTED -> {
BLog.d("onConnectionStateChange - Connected")
connected()
}
BluetoothProfile.STATE_CONNECTING -> {
BLog.d("onConnectionStateChange - Connecting")
// connecting()
}
BluetoothProfile.STATE_DISCONNECTING -> {
BLog.d("onConnectionStateChange - Disconnecting")
}
BluetoothProfile.STATE_DISCONNECTED -> {
BLog.d("onConnectionStateChange - Disconnected")
disconnected()
}
}
}
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
super.onServicesDiscovered(gatt, status)
BLog.d("onServicesDiscovered - gatt: $gatt, status: $status")
val result: Result<Boolean> = when (status) {
BluetoothGatt.GATT_SUCCESS -> Result.Success(true)
else -> Result.Failure(RuntimeException("onServicesDiscovered - Failed with status: $status"))
}
dispatcher.dispatched<Boolean>("discoverServices")?.complete(result)
}
override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
super.onCharacteristicRead(gatt, characteristic, status)
BLog.d("onCharacteristicRead - gatt: $gatt, status: $status, characteristic: ${characteristic.compositeId}")
val result: Result<ByteArray> = when (status) {
BluetoothGatt.GATT_SUCCESS -> Result.Success(characteristic.value)
else -> Result.Failure(RuntimeException("onCharacteristicRead - Failed with status: $status"))
}
dispatcher.dispatched<ByteArray>(characteristic.compositeId)?.complete(result)
}
override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
super.onCharacteristicWrite(gatt, characteristic, status)
BLog.d("onCharacteristicWrite - gatt: $gatt, status: $status, characteristic: $characteristic")
val result: Result<Boolean> = when (status) {
BluetoothGatt.GATT_SUCCESS -> Result.Success(true)
else -> Result.Failure(RuntimeException("onCharacteristicWrite - Failed with status: $status"))
}
dispatcher.dispatched<Boolean>(characteristic.compositeId)?.complete(result)
}
override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
super.onCharacteristicChanged(gatt, characteristic)
BLog.d("OnCharacteristicChanged - gatt: $gatt, characteristic: ${characteristic.compositeId}")
notifications[characteristic.compositeId]?.invoke(Result.Success(characteristic.value))
}
override fun onDescriptorWrite(gatt: BluetoothGatt?, descriptor: BluetoothGattDescriptor?, status: Int) {
super.onDescriptorWrite(gatt, descriptor, status)
BLog.d("onDescriptorWrite - gatt: $gatt, descriptor: ${descriptor?.uuid?.toString()}, status: $status")
val result: Result<Boolean> = when (status) {
BluetoothGatt.GATT_SUCCESS -> Result.Success(true)
else -> Result.Failure(RuntimeException("onDescriptorWrite - Failed with status: $status"))
}
dispatcher.dispatched<Boolean>(descriptor?.uuid.toString())?.complete(result)
}
}
}
| apache-2.0 | e00f0b88effc7555f996320552d3117d | 41.662824 | 129 | 0.585112 | 5.395044 | false | false | false | false |
Etik-Tak/backend | src/main/kotlin/dk/etiktak/backend/controller/rest/ProductCategoryRestController.kt | 1 | 5024 | // Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* Rest controller responsible for handling product scans.
*/
package dk.etiktak.backend.controller.rest
import dk.etiktak.backend.controller.rest.json.add
import dk.etiktak.backend.model.contribution.TrustVote
import dk.etiktak.backend.model.user.Client
import dk.etiktak.backend.security.CurrentlyLoggedClient
import dk.etiktak.backend.service.client.ClientService
import dk.etiktak.backend.service.product.ProductCategoryService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import java.util.*
@RestController
@RequestMapping("/service/product/category")
class ProductCategoryRestController @Autowired constructor(
private val productCategoryService: ProductCategoryService,
private val clientService: ClientService) : BaseRestController() {
@RequestMapping(value = "/", method = arrayOf(RequestMethod.GET))
fun getProductCategory(
@CurrentlyLoggedClient loggedClient: Client?,
@RequestParam uuid: String): HashMap<String, Any> {
val client = if (loggedClient != null) clientService.getByUuid(loggedClient.uuid) else null
val productCategory = productCategoryService.getProductCategoryByUuid(uuid) ?: return notFoundMap("Product category")
return okMap().add(productCategory, client, productCategoryService)
}
@RequestMapping(value = "/create/", method = arrayOf(RequestMethod.POST))
fun createProductCategory(
@CurrentlyLoggedClient loggedClient: Client,
@RequestParam name: String): HashMap<String, Any> {
val client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client")
val productCategory = productCategoryService.createProductCategory(client, name)
return okMap().add(productCategory, client, productCategoryService)
}
@RequestMapping(value = "/edit/", method = arrayOf(RequestMethod.POST))
fun editProductLabel(
@CurrentlyLoggedClient loggedClient: Client,
@RequestParam productCategoryUuid: String,
@RequestParam(required = false) name: String?): HashMap<String, Any> {
var client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client")
var productCategory = productCategoryService.getProductCategoryByUuid(productCategoryUuid) ?: return notFoundMap("Product category")
name?.let {
productCategoryService.editProductCategoryName(client, productCategory, name,
modifyValues = {modifiedClient, modifiedProductCategory -> client = modifiedClient; productCategory = modifiedProductCategory})
}
return okMap().add(productCategory, client, productCategoryService)
}
@RequestMapping(value = "/trust/name/", method = arrayOf(RequestMethod.POST))
fun trustVoteProductCategoryName(
@CurrentlyLoggedClient loggedClient: Client,
@RequestParam productCategoryUuid: String,
@RequestParam vote: TrustVote.TrustVoteType): HashMap<String, Any> {
val client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client")
val productCategory = productCategoryService.getProductCategoryByUuid(productCategoryUuid) ?: return notFoundMap("Product category")
productCategoryService.trustVoteProductCategoryName(client, productCategory, vote)
return okMap().add(productCategory, client, productCategoryService)
}
}
| bsd-3-clause | c0fe77009ee5db55ea1ad0c942e1617e | 48.742574 | 147 | 0.751393 | 5.100508 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/ArmoireActivity.kt | 1 | 8766 | package com.habitrpg.android.habitica.ui.activities
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.widget.FrameLayout
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.InventoryRepository
import com.habitrpg.android.habitica.databinding.ActivityArmoireBinding
import com.habitrpg.android.habitica.helpers.AdHandler
import com.habitrpg.android.habitica.helpers.AdType
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.common.habitica.extensions.loadImage
import com.habitrpg.android.habitica.ui.viewmodels.MainUserViewModel
import com.habitrpg.android.habitica.ui.views.ads.AdButton
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaBottomSheetDialog
import com.habitrpg.common.habitica.extensions.dpToPx
import com.habitrpg.common.habitica.extensions.loadImage
import com.habitrpg.common.habitica.helpers.Animations
import com.plattysoft.leonids.ParticleSystem
import java.util.Locale
import javax.inject.Inject
class ArmoireActivity : BaseActivity() {
private var equipmentKey: String? = null
private var gold: Double? = null
private var hasAnimatedChanges: Boolean = false
private lateinit var binding: ActivityArmoireBinding
@Inject
internal lateinit var inventoryRepository: InventoryRepository
@Inject
internal lateinit var appConfigManager: AppConfigManager
@Inject
lateinit var userViewModel: MainUserViewModel
override fun getLayoutResId(): Int = R.layout.activity_armoire
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun getContentView(): View {
binding = ActivityArmoireBinding.inflate(layoutInflater)
return binding.root
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.goldView.currency = "gold"
binding.goldView.animationDuration = 1000
binding.goldView.animationDelay = 500
binding.goldView.minForAbbrevation = 1000000
binding.goldView.decimals = 0
userViewModel.user.observe(this) { user ->
if (gold == null) {
gold = user?.stats?.gp
}
val remaining = inventoryRepository.getArmoireRemainingCount()
binding.equipmentCountView.text = getString(R.string.equipment_remaining, remaining)
binding.noEquipmentView.visibility = if (remaining > 0) View.GONE else View.VISIBLE
}
if (appConfigManager.enableArmoireAds()) {
val handler = AdHandler(this, AdType.ARMOIRE) {
if (!it) {
return@AdHandler
}
Log.d("AdHandler", "Giving Armoire")
val user = userViewModel.user.value ?: return@AdHandler
val currentGold = user.stats?.gp ?: return@AdHandler
compositeSubscription.add(
userRepository.updateUser("stats.gp", currentGold + 100)
.flatMap { inventoryRepository.buyItem(user, "armoire", 100.0, 1) }
.subscribe({
configure(
it.armoire["type"] ?: "",
it.armoire["dropKey"] ?: "",
it.armoire["dropText"] ?: "",
it.armoire["value"] ?: ""
)
binding.adButton.state = AdButton.State.UNAVAILABLE
binding.adButton.visibility = View.INVISIBLE
hasAnimatedChanges = false
gold = null
}, ExceptionHandler.rx())
)
}
handler.prepare {
if (it && binding.adButton.state == AdButton.State.LOADING) {
binding.adButton.state = AdButton.State.READY
} else if (!it) {
binding.adButton.visibility = View.INVISIBLE
}
}
binding.adButton.updateForAdType(AdType.ARMOIRE, lifecycleScope)
binding.adButton.setOnClickListener {
binding.adButton.state = AdButton.State.LOADING
handler.show()
}
} else {
binding.adButton.visibility = View.GONE
}
binding.closeButton.setOnClickListener {
finish()
}
binding.equipButton.setOnClickListener {
equipmentKey?.let { it1 -> inventoryRepository.equip("equipped", it1).subscribe({}, ExceptionHandler.rx()) }
finish()
}
binding.dropRateButton.setOnClickListener {
showDropRateDialog()
}
intent.extras?.let {
val args = ArmoireActivityArgs.fromBundle(it)
equipmentKey = args.key
configure(args.type, args.key, args.text, args.value)
}
}
override fun onResume() {
super.onResume()
startAnimation()
}
private fun startAnimation() {
val gold = gold?.toInt()
if (hasAnimatedChanges) return
if (gold != null) {
binding.goldView.value = (gold).toDouble()
binding.goldView.value = (gold - 100).toDouble()
}
val container = binding.confettiAnchor
container.postDelayed(
{
createParticles(container, R.drawable.confetti_blue)
createParticles(container, R.drawable.confetti_red)
createParticles(container, R.drawable.confetti_yellow)
createParticles(container, R.drawable.confetti_purple)
}, 500
)
binding.iconView.startAnimation(Animations.bobbingAnimation())
binding.titleView.alpha = 0f
binding.subtitleView.alpha = 0f
binding.iconWrapper.post {
Animations.circularReveal(binding.iconWrapper, 300)
}
binding.leftSparkView.startAnimating()
binding.rightSparkView.startAnimating()
binding.titleView.animate().apply {
alpha(1f)
duration = 300
startDelay = 600
start()
}
binding.subtitleView.animate().apply {
alpha(1f)
duration = 300
startDelay = 900
start()
}
hasAnimatedChanges = true
}
private fun createParticles(container: FrameLayout, resource: Int) {
ParticleSystem(
container,
30,
ContextCompat.getDrawable(this, resource),
6000
)
.setRotationSpeed(144f)
.setScaleRange(1.0f, 1.6f)
.setSpeedByComponentsRange(-0.15f, 0.15f, 0.15f, 0.45f)
.setFadeOut(200, AccelerateInterpolator())
.emitWithGravity(binding.confettiAnchor, Gravity.TOP, 15, 2000)
}
fun configure(type: String, key: String, text: String, value: String? = "") {
binding.titleView.text = text.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
binding.equipButton.visibility = if (type == "gear") View.VISIBLE else View.GONE
when (type) {
"gear" -> {
binding.subtitleView.text = getString(R.string.armoireEquipment_new)
binding.iconView.loadImage("shop_$key")
}
"food" -> {
binding.subtitleView.text = getString(R.string.armoireFood_new)
binding.iconView.loadImage("Pet_Food_$key")
}
else -> {
@SuppressLint("SetTextI18n")
binding.titleView.text = "+${value} ${binding.titleView.text}"
binding.subtitleView.text = getString(R.string.armoireExp)
binding.iconView.setImageResource(R.drawable.armoire_experience)
val layoutParams = RelativeLayout.LayoutParams(108.dpToPx(this), 122.dpToPx(this))
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT)
binding.iconView.layoutParams = layoutParams
}
}
}
private fun showDropRateDialog() {
val dialog = HabiticaBottomSheetDialog(this)
dialog.setContentView(R.layout.armoire_drop_rate_dialog)
dialog.show()
}
}
| gpl-3.0 | 6dd3eabd7769328e1e38d88d9bc01fc9 | 37.787611 | 133 | 0.616587 | 4.84042 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryGroupingSpecPsiImpl.kt | 1 | 2184 | /*
* Copyright (C) 2016-2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import uk.co.reecedunn.intellij.plugin.core.sequences.children
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmSequenceType
import uk.co.reecedunn.intellij.plugin.xdm.types.XsAnyUriValue
import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathEQName
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryGroupingSpec
class XQueryGroupingSpecPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XQueryGroupingSpec {
// region PsiElement
override fun getUseScope(): SearchScope = LocalSearchScope(parent.parent)
// endregion
// region XQueryGroupingSpec
override val collation: XsAnyUriValue?
get() = children().filterIsInstance<XsAnyUriValue>().firstOrNull()
// endregion
// region XpmVariableBinding
override val variableName: XsQNameValue?
get() = children().filterIsInstance<XPathEQName>().firstOrNull()
// endregion
// region XpmAssignableVariable
override val variableType: XdmSequenceType?
get() = children().filterIsInstance<XdmSequenceType>().firstOrNull()
override val variableExpression: XpmExpression?
get() = children().filterIsInstance<XpmExpression>().firstOrNull()
// endregion
}
| apache-2.0 | da1f0ebec1d63d4f7c7671e2c8939fd3 | 37.315789 | 97 | 0.768315 | 4.53112 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-basex/main/uk/co/reecedunn/intellij/plugin/basex/query/session/BaseXQueryInfo.kt | 1 | 2671 | /*
* Copyright (C) 2019-2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.basex.query.session
import uk.co.reecedunn.intellij.plugin.xdm.types.impl.values.XsDuration
@Suppress("RegExpAnonymousGroup")
private val RE_TOTAL_TIME = "([0-9.]+) ms[ .]".toRegex()
private fun String.toBaseXInfoBlocks(): Sequence<String> {
return replace("\r\n", "\n").replace('\r', '\n').split("\n\n").asSequence().map {
when {
it.startsWith('\n') -> it.substring(1)
it.endsWith('\n') -> it.substring(0, it.length - 1)
else -> it
}
}
}
private fun String.parseBaseXInfoBlock(info: HashMap<String, Any>) {
@Suppress("UNCHECKED_CAST")
var profile = info["Profile"] as? HashMap<String, XsDuration>
split('\n').forEach { row ->
val data = row.split(": ")
if (data[1].endsWith(" ms")) {
if (profile == null) {
profile = HashMap()
info["Profile"] = profile!!
}
profile?.put(data[0], XsDuration.ms(data[1].substringBefore(" ms")))
if (data[0] == "Total Time") {
info[data[0]] = XsDuration.ms(data[1].substringBefore(" ms"))
}
} else {
info[data[0]] = data[1]
}
}
}
fun String.toBaseXInfo(): Map<String, Any> {
val info = HashMap<String, Any>()
toBaseXInfoBlocks().forEach { block ->
val part = block.substringBefore('\n')
when {
part.contains(": ") -> block.parseBaseXInfoBlock(info)
part == "Query Plan:" -> {
info["Query Plan"] = block.substringAfter('\n')
}
part == "Compiling:" -> {
info["Compilation"] = block.substringAfter('\n').split('\n').map { it.substring(2) }
}
part == "Optimized Query:" -> {
info["Optimized Query"] = block.substringAfter('\n')
}
else -> RE_TOTAL_TIME.find(block)?.let { total ->
info["Total Time"] = XsDuration.ms(total.groupValues[1])
}
}
}
return info
}
| apache-2.0 | 0482542671dce3c240ec5dd6c2fffc21 | 35.094595 | 100 | 0.571696 | 3.916422 | false | false | false | false |
google/private-compute-services | src/com/google/android/as/oss/policies/api/proto/AnnotationProto.kt | 1 | 2412 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package com.google.android.`as`.oss.policies.api.proto
import arcs.core.data.proto.AnnotationParamProto
import arcs.core.data.proto.AnnotationProto
import com.google.android.`as`.oss.policies.api.annotation.Annotation
import com.google.android.`as`.oss.policies.api.annotation.AnnotationParam
private fun AnnotationParamProto.decode(): AnnotationParam {
return when (valueCase) {
AnnotationParamProto.ValueCase.STR_VALUE -> AnnotationParam.Str(strValue)
AnnotationParamProto.ValueCase.NUM_VALUE -> AnnotationParam.Num(numValue)
AnnotationParamProto.ValueCase.BOOL_VALUE -> AnnotationParam.Bool(boolValue)
else -> throw UnsupportedOperationException("Invalid [AnnotationParam] type $valueCase.")
}
}
private fun AnnotationParam.encode(paramName: String): AnnotationParamProto {
val proto = AnnotationParamProto.newBuilder().setName(paramName)
when (this) {
is AnnotationParam.Bool -> proto.boolValue = value
is AnnotationParam.Str -> proto.strValue = value
is AnnotationParam.Num -> proto.numValue = value
}
return proto.build()
}
/** Converts a [AnnotationProto] into a [Annotation]. */
fun AnnotationProto.decode(): Annotation {
return Annotation(name = name, params = paramsList.associate { it.name to it.decode() })
}
/** Converts a [Annotation] into a [AnnotationProto]. */
fun Annotation.encode(): AnnotationProto {
return AnnotationProto.newBuilder()
.setName(name)
.addAllParams(params.map { (name, param) -> param.encode(name) })
.build()
}
| apache-2.0 | 34d776470dd8b219046648394d5fd478 | 36.107692 | 96 | 0.747098 | 3.986777 | false | false | false | false |
dhleong/ideavim | src/com/maddyhome/idea/vim/action/motion/select/SelectEscapeAction.kt | 1 | 1889 | /*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2019 The IdeaVim authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.maddyhome.idea.vim.action.motion.select
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.action.VimCommandAction
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.handler.VimActionHandler
import com.maddyhome.idea.vim.helper.inBlockSubMode
import javax.swing.KeyStroke
class SelectEscapeAction : VimCommandAction() {
override fun makeActionHandler(): VimActionHandler = object : VimActionHandler.SingleExecution() {
override fun execute(editor: Editor, context: DataContext, cmd: Command): Boolean {
val blockMode = editor.inBlockSubMode
VimPlugin.getVisualMotion().exitSelectMode(editor, true)
if (blockMode) editor.caretModel.removeSecondaryCarets()
return true
}
}
override val mappingModes: MutableSet<MappingMode> = MappingMode.S
override val keyStrokesSet: Set<List<KeyStroke>> = parseKeysSet("<esc>")
override val type: Command.Type = Command.Type.OTHER_READONLY
} | gpl-2.0 | 668f53a192f36da88e97534d50afab99 | 41 | 100 | 0.775013 | 4.372685 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/browse/components/BaseSourceItem.kt | 1 | 2363 | package eu.kanade.presentation.browse.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import eu.kanade.domain.source.model.Source
import eu.kanade.presentation.util.horizontalPadding
import eu.kanade.presentation.util.secondaryItemAlpha
import eu.kanade.tachiyomi.util.system.LocaleHelper
@Composable
fun BaseSourceItem(
modifier: Modifier = Modifier,
source: Source,
showLanguageInContent: Boolean = true,
onClickItem: () -> Unit = {},
onLongClickItem: () -> Unit = {},
icon: @Composable RowScope.(Source) -> Unit = defaultIcon,
action: @Composable RowScope.(Source) -> Unit = {},
content: @Composable RowScope.(Source, String?) -> Unit = defaultContent,
) {
val sourceLangString = LocaleHelper.getSourceDisplayName(source.lang, LocalContext.current).takeIf { showLanguageInContent }
BaseBrowseItem(
modifier = modifier,
onClickItem = onClickItem,
onLongClickItem = onLongClickItem,
icon = { icon.invoke(this, source) },
action = { action.invoke(this, source) },
content = { content.invoke(this, source, sourceLangString) },
)
}
private val defaultIcon: @Composable RowScope.(Source) -> Unit = { source ->
SourceIcon(source = source)
}
private val defaultContent: @Composable RowScope.(Source, String?) -> Unit = { source, sourceLangString ->
Column(
modifier = Modifier
.padding(horizontal = horizontalPadding)
.weight(1f),
) {
Text(
text = source.name,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.bodyMedium,
)
if (sourceLangString != null) {
Text(
modifier = Modifier.secondaryItemAlpha(),
text = sourceLangString,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.bodySmall,
)
}
}
}
| apache-2.0 | ac35aae59d39191f8eb968d3ef99d5e4 | 35.353846 | 128 | 0.677529 | 4.633333 | false | false | false | false |
suchaHassle/kotNES | src/Controller.kt | 1 | 738 | package kotNES
import asInt
class Controller {
enum class Buttons(val value: Int) {
A(0), B(1), Select(2), Start(3), Up(4), Down(5), Left(6), Right(7)
}
private var strobe: Boolean = false
private var buttonState = BooleanArray(8)
private var currButtonIndex: Int = 0
fun setButtonState(button: Buttons, state: Boolean) {
buttonState[button.value] = state
}
fun writeControllerInput(input: Int) {
strobe = (input and 1) == 1
if (strobe) currButtonIndex = 0
}
fun readControllerOutput(): Int {
if (currButtonIndex > 7) return 1
val state = buttonState[currButtonIndex]
if (!strobe) currButtonIndex++
return state.asInt()
}
} | mit | a188ec88525209eef050bda6a2a1761b | 23.633333 | 74 | 0.619241 | 3.967742 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt | 1 | 7460 | package info.nightscout.androidaps.plugins.source
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.transactions.CgmSourceTransaction
import info.nightscout.androidaps.interfaces.BgSource
import info.nightscout.androidaps.interfaces.Config
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSgv
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.receivers.DataWorker
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.XDripBroadcast
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP
import org.json.JSONObject
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class NSClientSourcePlugin @Inject constructor(
injector: HasAndroidInjector,
rh: ResourceHelper,
aapsLogger: AAPSLogger,
config: Config
) : PluginBase(PluginDescription()
.mainType(PluginType.BGSOURCE)
.fragmentClass(BGSourceFragment::class.java.name)
.pluginIcon(R.drawable.ic_nsclient_bg)
.pluginName(R.string.nsclientbg)
.shortName(R.string.nsclientbgshort)
.description(R.string.description_source_ns_client),
aapsLogger, rh, injector
), BgSource {
private var lastBGTimeStamp: Long = 0
private var isAdvancedFilteringEnabled = false
init {
if (config.NSCLIENT) {
pluginDescription
.alwaysEnabled(true)
.setDefault()
}
}
override fun advancedFilteringSupported(): Boolean {
return isAdvancedFilteringEnabled
}
override fun shouldUploadToNs(glucoseValue: GlucoseValue): Boolean = false
private fun detectSource(glucoseValue: GlucoseValue) {
if (glucoseValue.timestamp > lastBGTimeStamp) {
isAdvancedFilteringEnabled = arrayOf(
GlucoseValue.SourceSensor.DEXCOM_NATIVE_UNKNOWN,
GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE,
GlucoseValue.SourceSensor.DEXCOM_G5_NATIVE,
GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE_XDRIP,
GlucoseValue.SourceSensor.DEXCOM_G5_NATIVE_XDRIP
).any { it == glucoseValue.sourceSensor }
lastBGTimeStamp = glucoseValue.timestamp
}
}
// cannot be inner class because of needed injection
class NSClientSourceWorker(
context: Context,
params: WorkerParameters
) : Worker(context, params) {
@Inject lateinit var nsClientSourcePlugin: NSClientSourcePlugin
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP
@Inject lateinit var rxBus: RxBus
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var dataWorker: DataWorker
@Inject lateinit var repository: AppRepository
@Inject lateinit var xDripBroadcast: XDripBroadcast
@Inject lateinit var dexcomPlugin: DexcomPlugin
@Inject lateinit var nsClientPlugin: NSClientPlugin
init {
(context.applicationContext as HasAndroidInjector).androidInjector().inject(this)
}
private fun toGv(jsonObject: JSONObject): CgmSourceTransaction.TransactionGlucoseValue? {
val sgv = NSSgv(jsonObject)
return CgmSourceTransaction.TransactionGlucoseValue(
timestamp = sgv.mills ?: return null,
value = sgv.mgdl?.toDouble() ?: return null,
noise = null,
raw = sgv.filtered?.toDouble() ?: sgv.mgdl?.toDouble(),
trendArrow = GlucoseValue.TrendArrow.fromString(sgv.direction),
nightscoutId = sgv.id,
sourceSensor = GlucoseValue.SourceSensor.fromString(sgv.device)
)
}
@Suppress("SpellCheckingInspection")
override fun doWork(): Result {
var ret = Result.success()
val sgvs = dataWorker.pickupJSONArray(inputData.getLong(DataWorker.STORE_KEY, -1))
?: return Result.failure(workDataOf("Error" to "missing input data"))
xDripBroadcast.sendSgvs(sgvs)
if (!nsClientSourcePlugin.isEnabled() && !sp.getBoolean(R.string.key_ns_receive_cgm, false))
return Result.success(workDataOf("Result" to "Sync not enabled"))
try {
var latestDateInReceivedData: Long = 0
aapsLogger.debug(LTag.BGSOURCE, "Received NS Data: $sgvs")
val glucoseValues = mutableListOf<CgmSourceTransaction.TransactionGlucoseValue>()
for (i in 0 until sgvs.length()) {
val sgv = toGv(sgvs.getJSONObject(i)) ?: continue
if (sgv.timestamp < dateUtil.now() && sgv.timestamp > latestDateInReceivedData) latestDateInReceivedData = sgv.timestamp
glucoseValues += sgv
}
// Was that sgv more less 5 mins ago ?
if (T.msecs(dateUtil.now() - latestDateInReceivedData).mins() < 5L) {
rxBus.send(EventDismissNotification(Notification.NS_ALARM))
rxBus.send(EventDismissNotification(Notification.NS_URGENT_ALARM))
}
nsClientPlugin.updateLatestDateReceivedIfNewer(latestDateInReceivedData)
repository.runTransactionForResult(CgmSourceTransaction(glucoseValues, emptyList(), null, !nsClientSourcePlugin.isEnabled()))
.doOnError {
aapsLogger.error(LTag.DATABASE, "Error while saving values from NSClient App", it)
ret = Result.failure(workDataOf("Error" to it.toString()))
}
.blockingGet()
.also { result ->
result.updated.forEach {
xDripBroadcast.send(it)
nsClientSourcePlugin.detectSource(it)
aapsLogger.debug(LTag.DATABASE, "Updated bg $it")
}
result.inserted.forEach {
xDripBroadcast.send(it)
nsClientSourcePlugin.detectSource(it)
aapsLogger.debug(LTag.DATABASE, "Inserted bg $it")
}
}
} catch (e: Exception) {
aapsLogger.error("Unhandled exception", e)
ret = Result.failure(workDataOf("Error" to e.toString()))
}
return ret
}
}
} | agpl-3.0 | bfb6d5083700f89fe0fc974004c074e4 | 43.410714 | 141 | 0.662466 | 4.888598 | false | false | false | false |
kevinhinterlong/archwiki-viewer | app/src/main/java/com/jtmcn/archwiki/viewer/SearchResultsAdapter.kt | 2 | 1639 | package com.jtmcn.archwiki.viewer
import android.app.SearchManager
import android.content.Context
import android.database.MatrixCursor
import android.provider.BaseColumns
import androidx.cursoradapter.widget.CursorAdapter
import androidx.cursoradapter.widget.SimpleCursorAdapter
import com.jtmcn.archwiki.viewer.data.SearchResult
/**
* Helper for creating a [SimpleCursorAdapter] which will
* list the search results for a [android.widget.SearchView]
*/
object SearchResultsAdapter {
private val columnNames = arrayOf(BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1)
private val from = arrayOf(SearchManager.SUGGEST_COLUMN_TEXT_1)
private val to = intArrayOf(R.id.url)
/**
* Creates a cursor adapter given a [<].
* https://stackoverflow.com/questions/11628172/converting-an-arrayadapter-to-cursoradapter-for-use-in-a-searchview/11628527#11628527
*
* @param results the results to be placed in the adapter.
* @return the adapter.
*/
fun getCursorAdapter(context: Context, results: List<SearchResult>): CursorAdapter {
var id = 0
val cursor = MatrixCursor(columnNames)
for ((pageName) in results) {
val temp = arrayOfNulls<String>(2)
temp[0] = id.toString() // "_id"
temp[1] = pageName // "title"
cursor.addRow(temp)
id++
}
return SimpleCursorAdapter(
context,
R.layout.search_suggestions_list_item,
cursor,
from,
to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER
)
}
}
| apache-2.0 | 111b22a1755aec51c5d5b04aa3121514 | 32.44898 | 137 | 0.661379 | 4.335979 | false | false | false | false |
laminr/aeroknow | app/src/main/java/biz/eventually/atpl/ui/source/SourceRepository.kt | 1 | 3084 | package biz.eventually.atpl.ui.source
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import biz.eventually.atpl.R
import biz.eventually.atpl.common.RxBaseManager
import biz.eventually.atpl.data.DataProvider
import biz.eventually.atpl.data.NetworkStatus
import biz.eventually.atpl.data.dao.LastCallDao
import biz.eventually.atpl.data.dao.SourceDao
import biz.eventually.atpl.data.db.LastCall
import biz.eventually.atpl.data.db.Source
import biz.eventually.atpl.utils.hasInternetConnection
import com.google.firebase.perf.metrics.AddTrace
import io.reactivex.Maybe
import io.reactivex.rxkotlin.plusAssign
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import timber.log.Timber
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by Thibault de Lambilly on 20/03/17.
*
*/
@Singleton
class SourceRepository @Inject constructor(private val dataProvider: DataProvider, private val dao: SourceDao, private val lastCallDao: LastCallDao) : RxBaseManager() {
private var status: MutableLiveData<NetworkStatus> = MutableLiveData()
@AddTrace(name = "getSources", enabled = true)
fun getSources(): LiveData<List<Source>> {
return dao.getAll()
}
fun updateData() {
if (hasInternetConnection()) getWebData()
}
fun networkStatus(): LiveData<NetworkStatus> {
return status
}
private fun getWebData() {
doAsync {
val lastCall = lastCallDao.findByType(LastCall.TYPE_SOURCE)?.updatedAt ?: 0L
uiThread {
status.postValue(NetworkStatus.LOADING)
disposables += dataProvider
.dataGetSources(lastCall)
.subscribeOn(scheduler.network)
.observeOn(scheduler.main)
.subscribe({ sWeb ->
analyseData(sWeb)
status.postValue(NetworkStatus.SUCCESS)
}, { e ->
Timber.d("getSources: " + e)
status.postValue(NetworkStatus.ERROR)
})
}
}
}
private fun analyseData(sWeb: List<Source>) {
doAsync {
val sourceIds = dao.getIds()
sWeb.forEach { s ->
// Update
if (s.idWeb in sourceIds) {
s.idWeb?.let {
Maybe.just(it).observeOn(scheduler.disk).map {
val sourceDb = dao.findById(it)
sourceDb?.let {
it.name = s.name
dao.update(it)
}
}
}
}
// New
else {
dao.insert(s)
}
}
// update time reference
lastCallDao.updateOrInsert(LastCall(LastCall.TYPE_SOURCE, Date().time))
}
}
}
| mit | e3e46269050beb6f48049203c6718fee | 30.793814 | 168 | 0.566796 | 4.910828 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceWithEnumMapInspection.kt | 2 | 3353 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.callExpressionVisitor
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.types.typeUtil.isEnum
private val hashMapCreationFqNames = setOf(
"java.util.HashMap.<init>",
"kotlin.collections.HashMap.<init>",
"kotlin.collections.hashMapOf"
)
class ReplaceWithEnumMapInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return callExpressionVisitor(fun(element: KtCallExpression) {
if (!element.platform.isJvm()) return
val context = element.safeAnalyzeNonSourceRootCode()
val fqName = element.getResolvedCall(context)?.resultingDescriptor?.fqNameUnsafe?.asString() ?: return
if (!hashMapCreationFqNames.contains(fqName)) return
if (element.valueArguments.isNotEmpty()) return
val expectedType = context[BindingContext.EXPECTED_EXPRESSION_TYPE, element] ?: return
val firstArgType = expectedType.arguments.firstOrNull()?.type ?: return
if (!firstArgType.isEnum()) return
val enumClassName = firstArgType.constructor.declarationDescriptor?.fqNameUnsafe?.asString() ?: return
holder.registerProblem(element, KotlinBundle.message("replaceable.with.enummap"), ReplaceWithEnumMapFix(enumClassName))
})
}
private class ReplaceWithEnumMapFix(
private val enumClassName: String
) : LocalQuickFix {
override fun getFamilyName() = name
override fun getName() = KotlinBundle.message("replace.with.enum.map.fix.text")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val call = descriptor.psiElement as? KtCallExpression ?: return
val factory = KtPsiFactory(call)
val file = call.containingKtFile
val enumMapDescriptor = file.resolveImportReference(FqName("java.util.EnumMap")).firstOrNull() ?: return
ImportInsertHelper.getInstance(project).importDescriptor(call.containingKtFile, enumMapDescriptor)
call.replace(factory.createExpressionByPattern("EnumMap($0::class.java)", enumClassName))
}
}
} | apache-2.0 | fd5b5d5b9a9f6491f7e5ca9283c39d30 | 50.6 | 158 | 0.763495 | 5.034535 | false | false | false | false |
fashare2015/MVVM-JueJin | app/src/main/kotlin/com/fashare/mvvm_juejin/model/user/UserBean.kt | 1 | 3618 | package com.fashare.mvvm_juejin.model.user
import java.io.Serializable
/**
* role : editor
* username : 梁山boy
* selfDescription : 擅长面向基佬编程
* email :
* mobilePhoneNumber : 18818276018
* jobTitle : Android
* company : 上海
* avatarHd : https://avatars.githubusercontent.com/u/15076541?v=3
* avatarLarge : https://avatars.githubusercontent.com/u/15076541?v=3
* blogAddress : http://blog.csdn.net/a153614131
* deviceType : android
* editorType : markdown
* allowNotification : false
* emailVerified : false
* mobilePhoneVerified : false
* isAuthor : true
* isUnitedAuthor : false
* blacklist : false
* followeesCount : 116
* followersCount : 39
* postedPostsCount : 5
* postedEntriesCount : 5
* collectedEntriesCount : 238
* viewedEntriesCount : 1832
* subscribedTagsCount : 18
* totalCollectionsCount : 1349
* totalViewsCount : 35326
* totalCommentsCount : 73
* latestLoginedInAt : 2017-09-12T10:55:48.674Z
* createdAt : 2016-08-24T04:43:32.001Z
* updatedAt : 2017-09-12T12:10:05.860Z
* collectionSetCount : 28
* useLeancloudPwd : false
* objectId : 57bd25f4a34131005b211b84
* uid : 57bd25f4a34131005b211b84
*/
/**
* 用户信息
*/
class UserBean : Serializable {
var role: String? = null
var username: String? = null
var selfDescription: String? = null
var email: String? = null
var mobilePhoneNumber: String? = null
var jobTitle: String? = null
var company: String? = null
var avatarHd: String? = null
var avatarLarge: String? = null
var blogAddress: String? = null
var deviceType: String? = null
var editorType: String? = null
var allowNotification: Boolean = false
var emailVerified: Boolean = false
var mobilePhoneVerified: Boolean = false
var isAuthor: Boolean = false
var isUnitedAuthor: Boolean = false
var blacklist: Boolean = false
var followeesCount: Int = 0
var followersCount: Int = 0
var postedPostsCount: Int = 0
var postedEntriesCount: Int = 0
var collectedEntriesCount: Int = 0
var viewedEntriesCount: Int = 0
var subscribedTagsCount: Int = 0
var totalCollectionsCount: Int = 0
var totalViewsCount: Int = 0
var totalCommentsCount: Int = 0
var latestLoginedInAt: String? = null
var createdAt: String? = null
var updatedAt: String? = null
var collectionSetCount: Int = 0
var useLeancloudPwd: Boolean = false
var objectId: String? = null
var uid: String? = null
class CommunityBean: Serializable {
/**
* uid : 5885816355
* nickname : 墨镜猫jacky
*/
var weibo: WeiboBean? = null
/**
* nickname : Android王世昌
* uid : oDv1Eww5c17raaESRVI8l9M6zsuE
* expires_at : 1468246472191
*/
var wechat: WechatBean? = null
/**
* nickname : Jacky Wang
* uid : 17797018
* expires_at : 1468239341180
*/
var github: GithubBean? = null
class WeiboBean : Serializable{
var uid: String? = null
var nickname: String? = null
}
class WechatBean : Serializable{
var nickname: String? = null
var uid: String? = null
var expires_at: String? = null
}
class GithubBean : Serializable{
var nickname: String? = null
var uid: String? = null
var expires_at: String? = null
}
}
class TokenBean: Serializable{
var token: String? = null
var user_id: String? = null
var state: String? = null
}
}
| mit | 3a994231a13340ad7e8738cdb655c41c | 27.141732 | 69 | 0.6385 | 3.703627 | false | false | false | false |
johnjohndoe/Umweltzone | Umweltzone/src/main/java/de/avpptr/umweltzone/models/extensions/ChildZoneExtensions.kt | 1 | 2634 | /*
* Copyright (C) 2020 Tobias Preuss
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
@file:JvmName("ChildZoneExtensions")
package de.avpptr.umweltzone.models.extensions
import de.avpptr.umweltzone.contract.LowEmissionZoneNumbers
import de.avpptr.umweltzone.models.ChildZone
import info.metadude.kotlin.library.roadsigns.RoadSign
val ChildZone.roadSignType: RoadSign.Type
get() = when {
zoneNumber == LowEmissionZoneNumbers.NONE -> RoadSign.Type.None
zoneNumber == LowEmissionZoneNumbers.RED -> RoadSign.Type.EnvironmentalBadge.RedYellowGreen
zoneNumber == LowEmissionZoneNumbers.YELLOW -> RoadSign.Type.EnvironmentalBadge.YellowGreen
zoneNumber == LowEmissionZoneNumbers.GREEN -> RoadSign.Type.EnvironmentalBadge.Green
zoneNumber == LowEmissionZoneNumbers.LIGHT_BLUE && fileName == "lez_stuttgart" ->
RoadSign.Type.DieselProhibition.FreeAsOfEuro5VExceptDeliveryVehiclesStuttgart
zoneNumber == LowEmissionZoneNumbers.DARK_BLUE && fileName == "dpz_hamburg_max_brauer_allee" ->
RoadSign.Type.DieselProhibition.CarsFreeUntilEuro5VOpenForResidentsHamburg
zoneNumber == LowEmissionZoneNumbers.DARK_BLUE && fileName == "dpz_hamburg_stresemannstrasse" ->
RoadSign.Type.DieselProhibition.HgvsFreeUntilEuroVOpenForResidentsHamburg
zoneNumber == LowEmissionZoneNumbers.DARK_BLUE && fileName == "dpz_berlin" ->
RoadSign.Type.DieselProhibition.CarsFreeUntilEuro5VOpenForResidentsBerlin
zoneNumber == LowEmissionZoneNumbers.DARK_BLUE && fileName == "dpz_darmstadt_huegelstrasse" ->
RoadSign.Type.DieselProhibition.CarsFreeUntilEuro5PetrolUntilEuro2Darmstadt
zoneNumber == LowEmissionZoneNumbers.DARK_BLUE && fileName == "dpz_darmstadt_heinrichstrasse" ->
RoadSign.Type.DieselProhibition.HgvsCarsFreeUntilEuro5VPetrolUntilEuro2Darmstadt
else -> throw IllegalStateException("Unknown combination of zone number: '$zoneNumber' and file name: '$fileName'.")
}
| gpl-3.0 | ea0717d225ad3059924c7f5d060b09df | 55.042553 | 124 | 0.753607 | 3.925484 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/caches/project/VfsCodeBlockModificationListener.kt | 3 | 2460 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.caches.project
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.vfs.AsyncVfsEventsListener
import com.intellij.vfs.AsyncVfsEventsPostProcessor
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.matches
import org.jetbrains.kotlin.idea.caches.trackers.KotlinCodeBlockModificationListener
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.util.runInReadActionWithWriteActionPriority
import org.jetbrains.kotlin.idea.util.application.isDispatchThread
class VfsCodeBlockModificationListener: StartupActivity.Background {
override fun runActivity(project: Project) {
val disposable = KotlinPluginDisposable.getInstance(project)
val ocbModificationListener = KotlinCodeBlockModificationListener.getInstance(project)
val vfsEventsListener = AsyncVfsEventsListener { events: List<VFileEvent> ->
val projectRelatedVfsFileChange = events.any { event ->
val file = event.takeIf { it.isFromRefresh || it is VFileContentChangeEvent }?.file ?: return@any false
return@any runInReadActionWithWriteActionPriority { RootKindFilter.projectSources.matches(project, file) } ?: true
}
if (projectRelatedVfsFileChange) {
if (isDispatchThread()) {
ocbModificationListener.incModificationCount()
} else {
// it is not fully correct - OCB has to be triggered ASAP as we detect VFS-change out of IJ that
// can affect Kotlin resolve, we can't do that properly before Kotlin 1.6.0
// see [org.jetbrains.kotlin.descriptors.InvalidModuleNotifier]
invokeLater {
ocbModificationListener.incModificationCount()
}
}
}
}
AsyncVfsEventsPostProcessor.getInstance().addListener(vfsEventsListener, disposable)
}
} | apache-2.0 | 58a16d07357fb928f4bdb649aaa25e3b | 56.232558 | 158 | 0.728862 | 5.178947 | false | false | false | false |
ingokegel/intellij-community | platform/elevation/common/src/com/intellij/execution/process/mediator/daemon/DaemonLaunchOptions.kt | 12 | 4670 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.process.mediator.daemon
import com.intellij.execution.process.mediator.util.parseArgs
import java.nio.file.Path
import java.security.KeyFactory
import java.security.PublicKey
import java.security.spec.X509EncodedKeySpec
import java.util.*
import kotlin.system.exitProcess
data class DaemonLaunchOptions(
val trampoline: Boolean = false,
val daemonize: Boolean = false,
val leaderPid: Long? = null,
val machNamespaceUid: Int? = null,
val handshakeOption: HandshakeOption? = null,
val tokenEncryptionOption: TokenEncryptionOption? = null,
) {
interface CmdlineOption {
override fun toString(): String
}
// handling multiple handshake writers is too complicated w.r.t. resource management, and we never need it anyway
sealed class HandshakeOption(private val arg: String) : CmdlineOption {
override fun toString(): String = arg
object Stdout : HandshakeOption("--handshake-file=-")
class File(val path: Path) : HandshakeOption("--handshake-file=$path") {
constructor(s: String) : this(Path.of(s))
}
class Port(val port: Int) : HandshakeOption("--handshake-port=$port") {
constructor(s: String) : this(s.toInt())
}
}
class TokenEncryptionOption(val publicKey: PublicKey) {
constructor(s: String) : this(rsaPublicKeyFromBytes(Base64.getDecoder().decode(s)))
override fun toString(): String = "--token-encrypt-rsa=${Base64.getEncoder().encodeToString(publicKey.encoded)}"
companion object {
private fun rsaPublicKeyFromBytes(bytes: ByteArray) =
KeyFactory.getInstance("RSA").generatePublic(X509EncodedKeySpec(bytes))
}
}
fun asCmdlineArgs(): List<String> {
return listOf(
"--trampoline".takeIf { trampoline },
"--daemonize".takeIf { daemonize },
leaderPid?.let { "--leader-pid=$it" },
machNamespaceUid?.let { "--mach-namespace-uid=$it" },
handshakeOption,
tokenEncryptionOption,
).mapNotNull { it?.toString() }
}
override fun toString(): String {
return asCmdlineArgs().joinToString(" ")
}
companion object {
private fun printUsage(programName: String) {
System.err.println(
"Usage: $programName" +
" [ --trampoline ]" +
" [ --daemonize ]" +
" [ --leader-pid=pid ]" +
" [ --mach-namespace-uid=uid ]" +
" [ --handshake-file=file|- | --handshake-port=port ]" +
" [ --token-encrypt-rsa=public-key ]"
)
}
fun parseFromArgsOrDie(programName: String, args: Array<String>): DaemonLaunchOptions {
return try {
parseFromArgs(args)
}
catch (e: Exception) {
System.err.println(e.message)
printUsage(programName)
exitProcess(1)
}
}
private fun parseFromArgs(args: Array<String>): DaemonLaunchOptions {
var trampoline = false
var daemonize = false
var leaderPid: Long? = null
var machNamespaceUid: Int? = null
var handshakeOption: HandshakeOption? = null
var tokenEncryptionOption: TokenEncryptionOption? = null
for ((option, value) in parseArgs(args)) {
when (option) {
"--trampoline" -> trampoline = true
"--no-trampoline" -> trampoline = false
"--daemonize" -> daemonize = true
"--no-daemonize" -> daemonize = false
else -> requireNotNull(value) { "Missing '$option' value" }
}
value ?: continue
when (option) {
"--leader-pid" -> {
leaderPid = value.toLong()
}
"--mach-namespace-uid" -> {
machNamespaceUid = value.toInt()
}
"--handshake-file" -> {
handshakeOption =
if (value == "-") HandshakeOption.Stdout
else HandshakeOption.File(value)
}
"--handshake-port" -> {
handshakeOption = HandshakeOption.Port(value)
}
"--token-encrypt-rsa" -> {
tokenEncryptionOption = TokenEncryptionOption(value)
}
null -> throw IllegalArgumentException("Unrecognized positional argument '$value'")
else -> throw IllegalArgumentException("Unrecognized option '$option'")
}
}
return DaemonLaunchOptions(
trampoline = trampoline,
daemonize = daemonize,
leaderPid = leaderPid,
machNamespaceUid = machNamespaceUid,
handshakeOption = handshakeOption,
tokenEncryptionOption = tokenEncryptionOption,
)
}
}
}
| apache-2.0 | e7bb065f9bdbf7004c16ed96135e067b | 31.206897 | 140 | 0.631263 | 4.413989 | false | false | false | false |
icela/FriceEngine | src/org/frice/platform/Platforms.kt | 1 | 698 | /**
* Run your codes under a specific platform
* @author ice1000
* @since v1.7.12
*/
@file:JvmName("Platforms")
package org.frice.platform
/** for Windowses */
var onWindows: Runnable? = null
/** for Mac OS X */
var onMac: Runnable? = null
/** for Linuxes */
var onLinux: Runnable? = null
/** for SunOS and Solaris */
var onSolaris: Runnable? = null
/** for FreeBSD */
var onBSD: Runnable? = null
var isOnWindows = false @JvmName(" ### windows") internal set
var isOnMac = false @JvmName(" ### mac") internal set
var isOnLinux = false @JvmName(" ### linux") internal set
var isOnSolaris = false @JvmName(" ### solaris") internal set
var isOnBSD = false @JvmName(" ### bsd") internal set
| agpl-3.0 | cca34b31a8d8afe8756ce4f385fb9a79 | 23.068966 | 61 | 0.67192 | 3.421569 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/springUtils.kt | 4 | 1048 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.wizard.ui
import com.intellij.openapi.util.NlsSafe
import javax.swing.Spring
import javax.swing.SpringLayout
internal operator fun Spring.plus(other: Spring) = Spring.sum(this, other)
internal operator fun Spring.plus(gap: Int) = Spring.sum(this, Spring.constant(gap))
internal operator fun Spring.minus(other: Spring) = this + Spring.minus(other)
internal operator fun Spring.unaryMinus() = Spring.minus(this)
internal operator fun Spring.times(by: Float) = Spring.scale(this, by)
internal fun Int.asSpring() = Spring.constant(this)
internal operator fun SpringLayout.Constraints.get(@NlsSafe edgeName: String) = getConstraint(edgeName)
internal operator fun SpringLayout.Constraints.set(@NlsSafe edgeName: String, spring: Spring) {
setConstraint(edgeName, spring)
}
fun springMin(s1: Spring, s2: Spring) = -Spring.max(-s1, -s2)
| apache-2.0 | 7e092337381a5a7d2154a86d56751f9a | 46.636364 | 158 | 0.782443 | 3.651568 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/UsageReplacementStrategy.kt | 1 | 8095 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.codeInliner
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.util.ModalityUiUtil
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.compareDescriptors
import org.jetbrains.kotlin.idea.core.targetDescriptors
import org.jetbrains.kotlin.idea.intentions.ConvertReferenceToLambdaIntention
import org.jetbrains.kotlin.idea.intentions.SpecifyExplicitLambdaSignatureIntention
import org.jetbrains.kotlin.idea.references.KtSimpleReference
import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope
import org.jetbrains.kotlin.idea.base.util.reformatted
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
interface UsageReplacementStrategy {
fun createReplacer(usage: KtReferenceExpression): (() -> KtElement?)?
companion object {
val KEY = Key<Unit>("UsageReplacementStrategy.replaceUsages")
}
}
private val LOG = Logger.getInstance(UsageReplacementStrategy::class.java)
fun UsageReplacementStrategy.replaceUsagesInWholeProject(
targetPsiElement: PsiElement,
@NlsContexts.DialogTitle progressTitle: String,
@NlsContexts.Command commandName: String,
unwrapSpecialUsages: Boolean = true,
) {
val project = targetPsiElement.project
ProgressManager.getInstance().run(
object : Task.Modal(project, progressTitle, true) {
override fun run(indicator: ProgressIndicator) {
val usages = runReadAction {
val searchScope = KotlinSourceFilterScope.projectSources(GlobalSearchScope.projectScope(project), project)
ReferencesSearch.search(targetPsiElement, searchScope)
.filterIsInstance<KtSimpleReference<KtReferenceExpression>>()
.map { ref -> ref.expression }
}
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL) {
project.executeWriteCommand(commandName) {
[email protected](usages, unwrapSpecialUsages)
}
}
}
})
}
fun UsageReplacementStrategy.replaceUsages(usages: Collection<KtReferenceExpression>, unwrapSpecialUsages: Boolean = true) {
val usagesByFile = usages.groupBy { it.containingFile }
for ((file, usagesInFile) in usagesByFile) {
usagesInFile.forEach { it.putCopyableUserData(UsageReplacementStrategy.KEY, Unit) }
// we should delete imports later to not affect other usages
val importsToDelete = mutableListOf<KtImportDirective>()
var usagesToProcess = usagesInFile
while (usagesToProcess.isNotEmpty()) {
if (processUsages(usagesToProcess, importsToDelete, unwrapSpecialUsages)) break
// some usages may get invalidated we need to find them in the tree
usagesToProcess = file.collectDescendantsOfType { it.getCopyableUserData(UsageReplacementStrategy.KEY) != null }
}
file.forEachDescendantOfType<KtSimpleNameExpression> { it.putCopyableUserData(UsageReplacementStrategy.KEY, null) }
importsToDelete.forEach { it.delete() }
}
}
/**
* @return false if some usages were invalidated
*/
private fun UsageReplacementStrategy.processUsages(
usages: List<KtReferenceExpression>,
importsToDelete: MutableList<KtImportDirective>,
unwrapSpecialUsages: Boolean,
): Boolean {
val sortedUsages = usages.sortedWith { element1, element2 ->
if (element1.parent.textRange.intersects(element2.parent.textRange)) {
compareValuesBy(element2, element1) { it.startOffset }
} else {
compareValuesBy(element1, element2) { it.startOffset }
}
}
var invalidUsagesFound = false
for (usage in sortedUsages) {
try {
if (!usage.isValid) {
invalidUsagesFound = true
continue
}
if (unwrapSpecialUsages) {
val specialUsage = unwrapSpecialUsageOrNull(usage)
if (specialUsage != null) {
createReplacer(specialUsage)?.invoke()
continue
}
}
//TODO: keep the import if we don't know how to replace some of the usages
val importDirective = usage.getStrictParentOfType<KtImportDirective>()
if (importDirective != null) {
if (!importDirective.isAllUnder && importDirective.targetDescriptors().size == 1) {
importsToDelete.add(importDirective)
}
continue
}
createReplacer(usage)?.invoke()?.parent?.parent?.parent?.reformatted(true)
} catch (e: Throwable) {
if (e is ControlFlowException) throw e
LOG.error(e)
}
}
return !invalidUsagesFound
}
fun unwrapSpecialUsageOrNull(
usage: KtReferenceExpression
): KtSimpleNameExpression? {
if (usage !is KtSimpleNameExpression) return null
when (val usageParent = usage.parent) {
is KtCallableReferenceExpression -> {
if (usageParent.callableReference != usage) return null
val (name, descriptor) = usage.nameAndDescriptor
return ConvertReferenceToLambdaIntention.applyTo(usageParent)?.let {
findNewUsage(it, name, descriptor)
}
}
is KtCallElement -> {
for (valueArgument in usageParent.valueArguments.asReversed()) {
val callableReferenceExpression = valueArgument.getArgumentExpression() as? KtCallableReferenceExpression ?: continue
ConvertReferenceToLambdaIntention.applyTo(callableReferenceExpression)
}
val lambdaExpressions = usageParent.valueArguments.mapNotNull { it.getArgumentExpression() as? KtLambdaExpression }
if (lambdaExpressions.isEmpty()) return null
val (name, descriptor) = usage.nameAndDescriptor
val grandParent = usageParent.parent
for (lambdaExpression in lambdaExpressions) {
val functionDescriptor = lambdaExpression.functionLiteral.resolveToDescriptorIfAny() as? FunctionDescriptor ?: continue
if (functionDescriptor.valueParameters.isNotEmpty()) {
SpecifyExplicitLambdaSignatureIntention.applyTo(lambdaExpression)
}
}
return grandParent.safeAs<KtElement>()?.let {
findNewUsage(it, name, descriptor)
}
}
}
return null
}
private val KtSimpleNameExpression.nameAndDescriptor get() = getReferencedName() to resolveToCall()?.candidateDescriptor
private fun findNewUsage(
element: KtElement,
targetName: String?,
targetDescriptor: DeclarationDescriptor?
): KtSimpleNameExpression? = element.findDescendantOfType {
it.getReferencedName() == targetName && compareDescriptors(it.project, targetDescriptor, it.resolveToCall()?.candidateDescriptor)
}
| apache-2.0 | 7a11f7334ce66c9a3abe11bce221f251 | 40.943005 | 158 | 0.701544 | 5.429242 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/editor/MarkdownEnterHandler.kt | 4 | 5234 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.editor
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate.Result
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import org.intellij.plugins.markdown.injection.MarkdownCodeFenceUtils
import org.intellij.plugins.markdown.lang.formatter.settings.MarkdownCustomCodeStyleSettings
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownBlockQuote
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
import org.intellij.plugins.markdown.util.MarkdownPsiStructureUtil.isTopLevel
import org.intellij.plugins.markdown.util.MarkdownPsiUtil
/**
* Enter handler of Markdown plugin,
*
* It generates blockquotes on `enter`.
* Also it stops indentation when there is >= 2 new lines after text
*/
internal class MarkdownEnterHandler : EnterHandlerDelegateAdapter() {
/**
* During preprocessing indentation can be stopped if there are more than
* two new lines after last element of text in Markdown file.
*
* E.g. it means, that there will be no indent if you will hit enter two times
* after list item on any indent level.
*
* Also, for non-toplevel codefences indentation is implemented via preprocessing.
* The actual reason for it is that injection-based formatting does not work
* correctly in frankenstein-like injection (for example, for codefence inside blockquote)
*/
override fun preprocessEnter(file: PsiFile, editor: Editor, caretOffset: Ref<Int>, caretAdvance: Ref<Int>,
dataContext: DataContext, originalHandler: EditorActionHandler?): Result {
val offset = editor.caretModel.offset
val element = MarkdownPsiUtil.findNonWhiteSpacePrevSibling(file, offset) ?: return Result.Continue
if (!file.isValid || !shouldHandle(editor, dataContext, element)) return Result.Continue
if (shouldAbortIndentation(file, editor, caretOffset.get())) {
EditorModificationUtil.insertStringAtCaret(editor, "\n")
return Result.Stop
}
val fence = MarkdownCodeFenceUtils.getCodeFence(element)
if (fence != null && !fence.isTopLevel()) {
val indent = MarkdownCodeFenceUtils.getIndent(fence) ?: return Result.Continue
EditorModificationUtil.insertStringAtCaret(editor, "\n${indent}")
return Result.Stop
}
return Result.Continue
}
/**
* During post-processing `>` can be added if it is necessary
*/
override fun postProcessEnter(file: PsiFile, editor: Editor, dataContext: DataContext): Result {
val offset = editor.caretModel.offset
val element = MarkdownPsiUtil.findNonWhiteSpacePrevSibling(file, offset) ?: return Result.Continue
if (!file.isValid || !shouldHandle(editor, dataContext, element)) return Result.Continue
processBlockQuote(editor, element)
return Result.Continue
}
private fun processBlockQuote(editor: Editor, element: PsiElement) {
val quote = PsiTreeUtil.getParentOfType(element, MarkdownBlockQuote::class.java) ?: return
val markdown = CodeStyle.getCustomSettings(quote.containingFile, MarkdownCustomCodeStyleSettings::class.java)
var toAdd = ">"
if (markdown.FORCE_ONE_SPACE_AFTER_BLOCKQUOTE_SYMBOL) {
toAdd += " "
}
EditorModificationUtil.insertStringAtCaret(editor, toAdd)
}
/**
* Check if alignment process should not be performed for this offset at all.
*
* Alignment of enter would not be performed if there is >= 2 new lines after
* last text element.
*/
private fun shouldAbortIndentation(file: PsiFile, editor: Editor, offset: Int): Boolean {
//do not stop indentation after two spaces in code fences
if (
file !is MarkdownFile
|| file.findElementAt(offset - 1)?.let { MarkdownCodeFenceUtils.inCodeFence(it.node) } == true
) {
return false
}
val text = editor.document.charsSequence.toString()
var cur = offset - 1
while (cur > 0) {
val char = text.getOrNull(cur)
if (char == null) {
cur--
continue
}
if (char.isWhitespace().not()) {
break
}
if (char == '\n') {
return true
}
cur--
}
return false
}
private fun shouldHandle(editor: Editor, dataContext: DataContext, element: PsiElement): Boolean {
val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return false
if (!editor.document.isWritable) return false
if (InjectedLanguageManager.getInstance(project).getTopLevelFile(element) !is MarkdownFile) return false
return !editor.isViewer
}
} | apache-2.0 | 6ee18d5aa9743afd1d0e9bac44ab8297 | 37.211679 | 140 | 0.739778 | 4.599297 | false | false | false | false |
DeskChan/DeskChan | src/main/kotlin/info/deskchan/MessageData/GUI/ChooseFiles.kt | 2 | 1018 | package info.deskchan.MessageData.GUI
import info.deskchan.core.MessageData
/**
* Open file chooser dialog
*
* <b>Response type</b>: String or List<String>, as specified by @multiple parameter
*
* @property title Dialog title
* @property filters Files filters to use in dialog
* @property initialDirectory Directory to start
* @property initialFilename Initial filename
* @property multiple Select multiple files. False by default
* @property saveDialog Is current dialog is "Save file" type or it "Open file" type
* **/
@MessageData.Tag("gui:choose-file")
@MessageData.RequiresResponse
class ChooseFiles : MessageData {
var title: String? = null
var initialDirectory: String? = null
var initialFilename: String? = null
var multiple: Boolean? = null
var saveDialog: Boolean? = null
var filters: List<Filter>? = null
companion object {
val ResponseFormat: String? = null
}
class Filter(val description: String, val extensions: List<String>) : MessageData
} | lgpl-3.0 | 9c814fa93c77fd65c7b51e511371be25 | 27.305556 | 85 | 0.722986 | 4.241667 | false | false | false | false |
himikof/intellij-rust | src/main/kotlin/org/rust/ide/utils/PresentationUtils.kt | 1 | 8180 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.utils
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
class PresentationInfo(
element: RsNamedElement,
val type: String?,
val name: String,
private val declaration: DeclarationInfo
) {
private val location: String?
init {
location = element.containingFile?.let { " [${it.name}]" }.orEmpty()
}
val typeNameText: String get() = if (type == null) {
name
} else "$type `$name`"
val projectStructureItemText: String get() = "$name${declaration.suffix}"
val projectStructureItemTextWithValue: String get() = "$projectStructureItemText${declaration.value}"
val shortSignatureText = "<b>$name</b>${declaration.suffix.escaped}"
val signatureText: String = "${declaration.prefix}$shortSignatureText"
val quickDocumentationText: String
get() = if (declaration.isAmbiguous && type != null) {
"<i>$type:</i> "
} else {
""
} + "$signatureText${valueText.escaped}$location"
private val valueText: String get() = if (declaration.value.isEmpty()) {
""
} else {
" ${declaration.value}"
}
}
data class DeclarationInfo(
val prefix: String = "",
val suffix: String = "",
val value: String = "",
val isAmbiguous: Boolean = false
)
val RsNamedElement.presentationInfo: PresentationInfo? get() {
val elementName = name ?: return null
val declInfo = when (this) {
is RsFunction -> Pair("function", createDeclarationInfo(this, identifier, false, listOf(whereClause, retType, valueParameterList)))
is RsStructItem -> Pair("struct", createDeclarationInfo(this, identifier, false, if (blockFields != null) listOf(whereClause) else listOf(whereClause, tupleFields)))
is RsFieldDecl -> Pair("field", createDeclarationInfo(this, identifier, false, listOf(typeReference)))
is RsEnumItem -> Pair("enum", createDeclarationInfo(this, identifier, false, listOf(whereClause)))
is RsEnumVariant -> Pair("enum variant", createDeclarationInfo(this, identifier, false, listOf(tupleFields)))
is RsTraitItem -> Pair("trait", createDeclarationInfo(this, identifier, false, listOf(whereClause)))
is RsTypeAlias -> Pair("type alias", createDeclarationInfo(this, identifier, false, listOf(typeReference, typeParamBounds, whereClause), eq))
is RsConstant -> Pair("constant", createDeclarationInfo(this, identifier, false, listOf(expr, typeReference), eq))
is RsSelfParameter -> Pair("parameter", createDeclarationInfo(this, self, false, listOf(typeReference)))
is RsTypeParameter -> Pair("type parameter", createDeclarationInfo(this, identifier, true))
is RsLifetimeDecl -> Pair("lifetime", createDeclarationInfo(this, quoteIdentifier, true))
is RsModItem -> Pair("module", createDeclarationInfo(this, identifier, false))
is RsLabelDecl -> {
val p = parent
when (p) {
is RsLoopExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.loop)))
is RsForExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.expr, p.`in`, p.`for`)))
is RsWhileExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.condition, p.`while`)))
else -> Pair("label", createDeclarationInfo(this, quoteIdentifier, true))
}
}
is RsPatBinding -> {
val patOwner = topLevelPattern.parent
when (patOwner) {
is RsLetDecl -> Pair("variable", createDeclarationInfo(patOwner, identifier, false, listOf(patOwner.typeReference)))
is RsValueParameter -> Pair("value parameter", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.typeReference)))
is RsMatchArm -> Pair("match arm binding", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.patList.lastOrNull())))
is RsCondition -> Pair("condition binding", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.lastChild)))
else -> Pair("binding", createDeclarationInfo(this, identifier, true))
}
}
is RsFile -> {
val mName = modName
if (isCrateRoot) return PresentationInfo(this, "crate", "crate", DeclarationInfo())
else if (mName != null) return PresentationInfo(this, "mod", name.substringBeforeLast(".rs"), DeclarationInfo("mod "))
else Pair("file", DeclarationInfo())
}
else -> Pair(javaClass.simpleName, createDeclarationInfo(this, navigationElement, true))
}
return declInfo.second?.let { PresentationInfo(this, declInfo.first, elementName, it) }
}
val RsDocAndAttributeOwner.presentableQualifiedName: String? get() {
val qName = (this as? RsQualifiedNamedElement)?.qualifiedName
if (qName != null) return qName
if (this is RsMod) return modName
return name
}
private fun createDeclarationInfo(decl: RsCompositeElement, name: PsiElement?, isAmbiguous: Boolean, stopAt: List<PsiElement?> = emptyList(), valueSeparator: PsiElement? = null): DeclarationInfo? {
// Break an element declaration into elements. For example:
//
// pub const Foo: u32 = 100;
// ^^^^^^^^^ signature prefix
// ^^^ name
// ^^^^^ signature suffix
// ^^^^^ value
// ^ end
if (name == null) return null
// Remove leading spaces, comments and attributes
val signatureStart = generateSequence(decl.firstChild) { it.nextSibling }
.dropWhile { it is PsiWhiteSpace || it is PsiComment || it is RsOuterAttr }
.firstOrNull()
?.startOffsetInParent ?: return null
val nameStart = name.offsetIn(decl)
// pick (in order) elements we should stop at
// if they all fail, drop down to the end of the name element
val end = stopAt
.filterNotNull().firstOrNull()
?.let { it.startOffsetInParent + it.textLength }
?: nameStart + name.textLength
val valueStart = valueSeparator?.offsetIn(decl) ?: end
val nameEnd = nameStart + name.textLength
check(signatureStart <= nameStart && nameEnd <= valueStart
&& valueStart <= end && end <= decl.textLength)
val prefix = decl.text.substring(signatureStart, nameStart).escaped
val value = decl.text.substring(valueStart, end)
val suffix = decl.text.substring(nameEnd, end - value.length)
.replace("""\s+""".toRegex(), " ")
.replace("( ", "(")
.replace(" )", ")")
.replace(" ,", ",")
.trimEnd()
return DeclarationInfo(prefix, suffix, value, isAmbiguous)
}
private fun PsiElement.offsetIn(owner: PsiElement): Int =
ancestors.takeWhile { it != owner }.sumBy { it.startOffsetInParent }
val String.escaped: String get() = StringUtil.escapeXml(this)
fun breadcrumbName(e: RsCompositeElement): String? {
fun lastComponentWithoutGenerics(path: RsPath) = path.referenceName
return when (e) {
is RsMacroDefinition -> e.name?.let { "$it!" }
is RsModItem, is RsStructOrEnumItemElement, is RsTraitItem, is RsConstant ->
(e as RsNamedElement).name
is RsImplItem -> {
val typeName = run {
val typeReference = e.typeReference
(typeReference?.typeElement as? RsBaseType)?.path?.let { lastComponentWithoutGenerics(it) }
?: typeReference?.text
?: return null
}
val traitName = e.traitRef?.path?.let { lastComponentWithoutGenerics(it) }
val start = if (traitName != null) "$traitName for" else "impl"
"$start $typeName"
}
is RsFunction -> e.name?.let { "$it()" }
else -> null
}
}
| mit | 1570915a1bcd5731d46df2f04ca61977 | 42.743316 | 197 | 0.647922 | 4.753051 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-core/jvmAndNix/test/io/ktor/server/application/RouteScopedPluginTest.kt | 1 | 20069 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.application
import io.ktor.http.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import io.ktor.util.*
import io.ktor.util.pipeline.*
import kotlin.test.*
@Suppress("DEPRECATION")
class RouteScopedPluginTest {
@Test
fun testPluginInstalledTopLevel(): Unit = withTestApplication {
application.install(TestPlugin)
assertFailsWith<DuplicatePluginException> {
application.routing {
install(TestPlugin)
}
}
}
@Test
fun testPluginInstalledInRoutingScope() = withTestApplication {
val callbackResults = mutableListOf<String>()
application.routing {
route("root-no-plugin") {
route("first-plugin") {
install(TestPlugin) {
name = "foo"
desc = "test plugin"
pipelineCallback = { callbackResults.add(it) }
}
handle {
call.respond(call.receive<String>())
}
route("inner") {
route("new-plugin") {
install(TestPlugin) {
name = "bar"
pipelineCallback = { callbackResults.add(it) }
}
route("inner") {
handle {
call.respond(call.receive<String>())
}
}
handle {
call.respond(call.receive<String>())
}
}
handle {
call.respond(call.receive<String>())
}
}
}
handle {
call.respond(call.receive<String>())
}
}
}
on("making get request to /root-no-plugin") {
val result = handleRequest {
uri = "/root-no-plugin"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should not be invoked") {
assertEquals(0, callbackResults.size)
}
}
on("making get request to /root-no-plugin/first-plugin") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("foo test plugin", callbackResults[0])
callbackResults.clear()
}
}
on("making get request to /root-no-plugin/first-plugin/inner") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin/inner"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("foo test plugin", callbackResults[0])
callbackResults.clear()
}
}
on("making get request to /root-no-plugin/first-plugin/inner/new-plugin") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin/inner/new-plugin"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("bar defaultDesc", callbackResults[0])
callbackResults.clear()
}
}
on("making get request to /root-no-plugin/first-plugin/inner/new-plugin/inner") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin/inner/new-plugin/inner"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("bar defaultDesc", callbackResults[0])
callbackResults.clear()
}
}
}
@Test
fun testPluginDoNotReuseConfig() = withTestApplication {
val callbackResults = mutableListOf<String>()
application.routing {
route("root") {
install(TestPlugin) {
name = "foo"
desc = "test plugin"
pipelineCallback = { callbackResults.add(it) }
}
route("plugin1") {
install(TestPlugin) {
desc = "new desc"
pipelineCallback = { callbackResults.add(it) }
}
handle {
call.respond(call.receive<String>())
}
route("plugin2") {
install(TestPlugin) {
name = "new name"
pipelineCallback = { callbackResults.add(it) }
}
handle {
call.respond(call.receive<String>())
}
}
}
handle {
call.respond(call.receive<String>())
}
}
}
on("making get request to /root") {
val result = handleRequest {
uri = "/root"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("foo test plugin", callbackResults[0])
callbackResults.clear()
}
}
on("making get request to /root/plugin1") {
val result = handleRequest {
uri = "/root/plugin1"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("defaultName new desc", callbackResults[0])
callbackResults.clear()
}
}
on("making get request to /root/plugin1/plugin2") {
val result = handleRequest {
uri = "/root/plugin1/plugin2"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("new name defaultDesc", callbackResults[0])
callbackResults.clear()
}
}
}
@Test
fun testMultiplePluginInstalledAtTheSameRoute(): Unit = withTestApplication {
assertFailsWith<DuplicatePluginException> {
application.routing {
route("root") {
install(TestPlugin)
}
route("root") {
install(TestPlugin)
}
}
}
}
@Test
fun testAllPipelinesPlugin() = withTestApplication {
val callbackResults = mutableListOf<String>()
val receiveCallbackResults = mutableListOf<String>()
val sendCallbackResults = mutableListOf<String>()
val allCallbacks = listOf(callbackResults, receiveCallbackResults, sendCallbackResults)
application.routing {
route("root-no-plugin") {
route("first-plugin") {
install(TestAllPipelinesPlugin) {
name = "foo"
desc = "test plugin"
addCallbacks(callbackResults, receiveCallbackResults, sendCallbackResults)
}
handle {
call.respond(call.receive<String>())
}
route("inner") {
route("new-plugin") {
install(TestAllPipelinesPlugin) {
name = "bar"
addCallbacks(callbackResults, receiveCallbackResults, sendCallbackResults)
}
route("inner") {
handle {
call.respond(call.receive<String>())
}
}
handle {
call.respond(call.receive<String>())
}
}
handle {
call.respond(call.receive<String>())
}
}
}
handle {
call.respond(call.receive<String>())
}
}
}
on("making get request to /root-no-plugin") {
val result = handleRequest {
uri = "/root-no-plugin"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should not be invoked") {
allCallbacks.forEach {
assertEquals(0, it.size)
}
}
}
on("making get request to /root-no-plugin/first-plugin") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
allCallbacks.forEach {
assertEquals(1, it.size)
assertEquals("foo test plugin", it[0])
it.clear()
}
}
}
on("making get request to /root-no-plugin/first-plugin/inner") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin/inner"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
allCallbacks.forEach {
assertEquals(1, it.size)
assertEquals("foo test plugin", it[0])
it.clear()
}
}
}
on("making get request to /root-no-plugin/first-plugin/inner/new-plugin") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin/inner/new-plugin"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
allCallbacks.forEach {
assertEquals(1, it.size)
assertEquals("bar defaultDesc", it[0])
it.clear()
}
}
}
on("making get request to /root-no-plugin/first-plugin/inner/new-plugin/inner") {
val result = handleRequest {
uri = "/root-no-plugin/first-plugin/inner/new-plugin/inner"
method = HttpMethod.Post
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("callback should be invoked") {
allCallbacks.forEach {
assertEquals(1, it.size)
assertEquals("bar defaultDesc", it[0])
it.clear()
}
}
}
}
@Test
fun testCustomPhase() = withTestApplication {
val callbackResults = mutableListOf<String>()
application.routing {
route("root") {
install(TestPluginCustomPhase) {
name = "foo"
desc = "first plugin"
callback = { callbackResults.add(it) }
}
handle {
call.respond(call.receive<String>())
}
route("a") {
install(TestPluginCustomPhase) {
name = "bar"
desc = "second plugin"
callback = { callbackResults.add(it) }
}
handle {
call.respond(call.receive<String>())
}
}
}
}
on("making get request to /root") {
val result = handleRequest {
uri = "/root"
method = HttpMethod.Get
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("second callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("foo first plugin", callbackResults[0])
callbackResults.clear()
}
}
on("making get request to /root/a") {
val result = handleRequest {
uri = "/root/a"
method = HttpMethod.Get
setBody("test")
}
it("should be handled") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
it("second callback should be invoked") {
assertEquals(1, callbackResults.size)
assertEquals("bar second plugin", callbackResults[0])
callbackResults.clear()
}
}
}
private fun TestAllPipelinesPlugin.Config.addCallbacks(
callbackResults: MutableList<String>,
receiveCallbackResults: MutableList<String>,
sendCallbackResults: MutableList<String>
) {
pipelineCallback = { callbackResults.add(it) }
receivePipelineCallback = { receiveCallbackResults.add(it) }
sendPipelineCallback = { sendCallbackResults.add(it) }
}
}
class TestAllPipelinesPlugin private constructor(config: Config) {
private val pipelineCallback = config.pipelineCallback
private val receivePipelineCallback = config.receivePipelineCallback
private val sendPipelineCallback = config.sendPipelineCallback
private val name = config.name
private val desc = config.desc
fun install(pipeline: ApplicationCallPipeline) {
pipeline.intercept(ApplicationCallPipeline.Plugins) {
pipelineCallback("$name $desc")
}
pipeline.receivePipeline.intercept(ApplicationReceivePipeline.Before) {
receivePipelineCallback("$name $desc")
}
pipeline.sendPipeline.intercept(ApplicationSendPipeline.Before) {
sendPipelineCallback("$name $desc")
}
}
@KtorDsl
class Config(
name: String = "defaultName",
desc: String = "defaultDesc",
pipelineCallback: (String) -> Unit = {},
receivePipelineCallback: (String) -> Unit = {},
sendPipelineCallback: (String) -> Unit = {},
) {
var name: String = name
var desc: String = desc
var pipelineCallback = pipelineCallback
var receivePipelineCallback = receivePipelineCallback
var sendPipelineCallback = sendPipelineCallback
}
companion object Plugin : BaseRouteScopedPlugin<Config, TestAllPipelinesPlugin> {
override val key: AttributeKey<TestAllPipelinesPlugin> = AttributeKey("TestPlugin")
override fun install(pipeline: ApplicationCallPipeline, configure: Config.() -> Unit): TestAllPipelinesPlugin {
val config = Config().apply(configure)
val plugin = TestAllPipelinesPlugin(config)
return plugin.apply { install(pipeline) }
}
}
}
class TestPlugin private constructor(config: Config) {
private val pipelineCallback = config.pipelineCallback
private val name = config.name
private val desc = config.desc
fun install(pipeline: ApplicationCallPipeline) {
pipeline.intercept(ApplicationCallPipeline.Fallback) {
pipelineCallback("$name $desc")
}
}
@KtorDsl
class Config(
name: String = "defaultName",
desc: String = "defaultDesc",
pipelineCallback: (String) -> Unit = {}
) {
var name = name
var desc = desc
var pipelineCallback = pipelineCallback
}
companion object Plugin : BaseRouteScopedPlugin<Config, TestPlugin> {
override val key: AttributeKey<TestPlugin> = AttributeKey("TestPlugin")
override fun install(pipeline: ApplicationCallPipeline, configure: Config.() -> Unit): TestPlugin {
val config = Config().apply(configure)
val plugin = TestPlugin(config)
return plugin.apply { install(pipeline) }
}
}
}
class TestPluginCustomPhase private constructor(config: Config) {
private val callback = config.callback
private val name = config.name
private val desc = config.desc
fun install(pipeline: ApplicationCallPipeline) {
val phase = PipelinePhase("new phase")
pipeline.insertPhaseAfter(ApplicationCallPipeline.Plugins, phase)
pipeline.intercept(phase) {
callback("$name $desc")
}
}
@KtorDsl
class Config(
name: String = "defaultName",
desc: String = "defaultDesc",
callback: (String) -> Unit = {},
) {
var name = name
var desc = desc
var callback = callback
}
companion object Plugin : BaseRouteScopedPlugin<Config, TestPluginCustomPhase> {
override val key: AttributeKey<TestPluginCustomPhase> = AttributeKey("TestPlugin")
override fun install(pipeline: ApplicationCallPipeline, configure: Config.() -> Unit): TestPluginCustomPhase {
val config = Config().apply(configure)
val plugin = TestPluginCustomPhase(config)
return plugin.apply { install(pipeline) }
}
}
}
| apache-2.0 | a08a05f506e57323c74451557e23646f | 33.364726 | 119 | 0.496039 | 5.472866 | false | true | false | false |
google/accompanist | sample/src/main/java/com/google/accompanist/sample/MainActivity.kt | 1 | 5098 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DEPRECATION") // ListActivity
package com.google.accompanist.sample
import android.annotation.SuppressLint
import android.app.ListActivity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ListView
import android.widget.SimpleAdapter
import java.text.Collator
import java.util.ArrayList
import java.util.Collections
import java.util.Comparator
import java.util.HashMap
/**
* A [ListActivity] which automatically populates the list of sample activities in this app
* with the category `com.google.accompanist.sample.SAMPLE_CODE`.
*/
class MainActivity : ListActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
listAdapter = SimpleAdapter(
this,
getData(intent.getStringExtra(EXTRA_PATH)),
android.R.layout.simple_list_item_1,
arrayOf("title"),
intArrayOf(android.R.id.text1)
)
listView.isTextFilterEnabled = true
}
private fun getData(prefix: String?): List<Map<String, Any>> {
val myData = ArrayList<Map<String, Any>>()
val mainIntent = Intent(Intent.ACTION_MAIN, null)
mainIntent.addCategory("com.google.accompanist.sample.SAMPLE_CODE")
@SuppressLint("QueryPermissionsNeeded") // Only querying our own Activities
val list = packageManager.queryIntentActivities(mainIntent, 0)
val prefixPath: Array<String>?
var prefixWithSlash = prefix
if (prefix.isNullOrEmpty()) {
prefixPath = null
} else {
prefixPath = prefix.split("/".toRegex()).toTypedArray()
prefixWithSlash = "$prefix/"
}
val entries = HashMap<String, Boolean>()
list.forEach { info ->
val labelSeq = info.loadLabel(packageManager)
val label = labelSeq?.toString() ?: info.activityInfo.name
if (prefixWithSlash.isNullOrEmpty() || label.startsWith(prefixWithSlash)) {
val labelPath = label.split("/".toRegex()).toTypedArray()
val nextLabel = if (prefixPath == null) labelPath[0] else labelPath[prefixPath.size]
if (prefixPath?.size ?: 0 == labelPath.size - 1) {
addItem(
data = myData,
name = nextLabel,
intent = activityIntent(
info.activityInfo.applicationInfo.packageName,
info.activityInfo.name
)
)
} else {
if (entries[nextLabel] == null) {
addItem(
data = myData,
name = nextLabel,
intent = browseIntent(
if (prefix == "") nextLabel else "$prefix/$nextLabel"
)
)
entries[nextLabel] = true
}
}
}
}
Collections.sort(myData, sDisplayNameComparator)
return myData
}
private fun activityIntent(pkg: String, componentName: String): Intent {
val result = Intent()
result.setClassName(pkg, componentName)
return result
}
private fun browseIntent(path: String): Intent {
val result = Intent()
result.setClass(this, MainActivity::class.java)
result.putExtra(EXTRA_PATH, path)
return result
}
private fun addItem(data: MutableList<Map<String, Any>>, name: String, intent: Intent) {
val temp = mutableMapOf<String, Any>()
temp["title"] = name
temp["intent"] = intent
data += temp
}
override fun onListItemClick(l: ListView, v: View, position: Int, id: Long) {
val map = l.getItemAtPosition(position) as Map<*, *>
val intent = map["intent"] as Intent?
startActivity(intent)
}
companion object {
private const val EXTRA_PATH = "com.example.android.apis.Path"
private val sDisplayNameComparator = object : Comparator<Map<String, Any>> {
private val collator = Collator.getInstance()
override fun compare(map1: Map<String, Any>, map2: Map<String, Any>): Int {
return collator.compare(map1["title"], map2["title"])
}
}
}
}
| apache-2.0 | 3814e45e87bd5562b15939d67b31d887 | 33.680272 | 100 | 0.597685 | 4.846008 | false | false | false | false |
google/accompanist | sample/src/main/java/com/google/accompanist/sample/pager/DocsSamples.kt | 1 | 4875 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UNUSED_ANONYMOUS_PARAMETER")
package com.google.accompanist.sample.pager
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Tab
import androidx.compose.material.TabRow
import androidx.compose.material.TabRowDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.HorizontalPagerIndicator
import com.google.accompanist.pager.VerticalPager
import com.google.accompanist.pager.VerticalPagerIndicator
import com.google.accompanist.pager.pagerTabIndicatorOffset
import com.google.accompanist.pager.rememberPagerState
import kotlinx.coroutines.flow.collect
@OptIn(ExperimentalPagerApi::class)
@Composable
fun HorizontalPagerSample() {
// Display 10 items
HorizontalPager(count = 10) { page ->
// Our page content
Text(
text = "Page: $page",
modifier = Modifier.fillMaxWidth()
)
}
}
@OptIn(ExperimentalPagerApi::class)
@Composable
fun VerticalPagerSample() {
// Display 10 items
VerticalPager(count = 10) { page ->
// Our page content
Text(
text = "Page: $page",
modifier = Modifier.fillMaxWidth()
)
}
}
@OptIn(ExperimentalPagerApi::class)
@Composable
fun HorizontalPagerIndicatorSample() {
val pagerState = rememberPagerState()
Column {
// Display 10 items
HorizontalPager(count = 10) { page ->
// Our page content
Text(
text = "Page: $page",
modifier = Modifier.fillMaxWidth()
)
}
HorizontalPagerIndicator(
pagerState = pagerState,
modifier = Modifier.padding(16.dp),
)
}
}
@OptIn(ExperimentalPagerApi::class)
@Composable
fun VerticalPagerIndicatorSample() {
val pagerState = rememberPagerState()
Row {
// Display 10 items
VerticalPager(
count = 10,
state = pagerState,
) { page ->
// Our page content
Text(
text = "Page: $page",
modifier = Modifier.fillMaxWidth()
)
}
VerticalPagerIndicator(
pagerState = pagerState,
modifier = Modifier.padding(16.dp),
)
}
}
@Suppress("UNUSED_PARAMETER")
object AnalyticsService {
fun sendPageSelectedEvent(page: Int) = Unit
}
@OptIn(ExperimentalPagerApi::class)
@Composable
fun PageChangesSample() {
val pagerState = rememberPagerState()
LaunchedEffect(pagerState) {
// Collect from the a snapshotFlow reading the currentPage
snapshotFlow { pagerState.currentPage }.collect { page ->
AnalyticsService.sendPageSelectedEvent(page)
}
}
VerticalPager(
count = 10,
state = pagerState,
) { page ->
Text(text = "Page: $page")
}
}
@OptIn(ExperimentalPagerApi::class)
@Composable
fun PagerWithTabs(pages: List<String>) {
val pagerState = rememberPagerState()
TabRow(
// Our selected tab is our current page
selectedTabIndex = pagerState.currentPage,
// Override the indicator, using the provided pagerTabIndicatorOffset modifier
indicator = { tabPositions ->
TabRowDefaults.Indicator(
Modifier.pagerTabIndicatorOffset(pagerState, tabPositions)
)
}
) {
// Add tabs for all of our pages
pages.forEachIndexed { index, title ->
Tab(
text = { Text(title) },
selected = pagerState.currentPage == index,
onClick = { /* TODO */ },
)
}
}
HorizontalPager(
count = pages.size,
state = pagerState,
) { page ->
// TODO: page content
}
}
| apache-2.0 | 11f0ff33b56da349ec9c442a34537576 | 27.676471 | 86 | 0.656 | 4.66954 | false | false | false | false |
cfieber/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/CompleteStageHandler.kt | 1 | 9121 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spectator.api.Registry
import com.netflix.spectator.api.histogram.BucketCounter
import com.netflix.spinnaker.orca.ExecutionStatus
import com.netflix.spinnaker.orca.ExecutionStatus.*
import com.netflix.spinnaker.orca.events.StageComplete
import com.netflix.spinnaker.orca.ext.afterStages
import com.netflix.spinnaker.orca.ext.failureStatus
import com.netflix.spinnaker.orca.ext.firstAfterStages
import com.netflix.spinnaker.orca.ext.syntheticStages
import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.pipeline.graph.StageGraphBuilder
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.model.Task
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor
import com.netflix.spinnaker.orca.q.*
import com.netflix.spinnaker.q.Queue
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.ApplicationEventPublisher
import org.springframework.stereotype.Component
import java.time.Clock
import java.util.concurrent.TimeUnit
@Component
class CompleteStageHandler(
override val queue: Queue,
override val repository: ExecutionRepository,
@Qualifier("queueEventPublisher") private val publisher: ApplicationEventPublisher,
private val clock: Clock,
override val contextParameterProcessor: ContextParameterProcessor,
private val registry: Registry,
override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory
) : OrcaMessageHandler<CompleteStage>, StageBuilderAware, ExpressionAware {
override fun handle(message: CompleteStage) {
message.withStage { stage ->
if (stage.status in setOf(RUNNING, NOT_STARTED)) {
var status = stage.determineStatus()
try {
if (status in setOf(RUNNING, NOT_STARTED) || (status.isComplete && !status.isHalt)) {
// check to see if this stage has any unplanned synthetic after stages
var afterStages = stage.firstAfterStages()
if (afterStages.isEmpty()) {
stage.planAfterStages()
afterStages = stage.firstAfterStages()
}
if (afterStages.isNotEmpty() && afterStages.any { it.status == NOT_STARTED }) {
afterStages
.filter { it.status == NOT_STARTED }
.forEach { queue.push(StartStage(message, it.id)) }
return@withStage
} else if (status == NOT_STARTED) {
// stage had no synthetic stages or tasks, which is odd but whatever
log.warn("Stage ${stage.id} (${stage.type}) of ${stage.execution.id} had no tasks or synthetic stages!")
status = SKIPPED
}
} else if (status.isFailure) {
if (stage.planOnFailureStages()) {
stage.firstAfterStages().forEach {
queue.push(StartStage(it))
}
return@withStage
}
}
stage.status = status
stage.endTime = clock.millis()
} catch (e: Exception) {
log.error("Failed to construct after stages", e)
stage.status = TERMINAL
stage.endTime = clock.millis()
}
stage.includeExpressionEvaluationSummary()
repository.storeStage(stage)
// When a synthetic stage ends with FAILED_CONTINUE, propagate that status up to the stage's
// parent so that no more of the parent's synthetic children will run.
if (stage.status == FAILED_CONTINUE && stage.syntheticStageOwner != null) {
queue.push(message.copy(stageId = stage.parentStageId!!))
} else if (stage.status in listOf(SUCCEEDED, FAILED_CONTINUE, SKIPPED)) {
stage.startNext()
} else {
queue.push(CancelStage(message))
if (stage.syntheticStageOwner == null) {
log.debug("Stage has no synthetic owner, completing execution (original message: $message)")
queue.push(CompleteExecution(message))
} else {
queue.push(message.copy(stageId = stage.parentStageId!!))
}
}
publisher.publishEvent(StageComplete(this, stage))
trackResult(stage)
}
}
}
// TODO: this should be done out of band by responding to the StageComplete event
private fun trackResult(stage: Stage) {
// We only want to record durations of parent-level stages; not synthetics.
if (stage.parentStageId != null) {
return
}
val id = registry.createId("stage.invocations.duration")
.withTag("status", stage.status.toString())
.withTag("stageType", stage.type)
.let { id ->
// TODO rz - Need to check synthetics for their cloudProvider.
stage.context["cloudProvider"]?.let {
id.withTag("cloudProvider", it.toString())
} ?: id
}
BucketCounter
.get(registry, id, { v -> bucketDuration(v) })
.record((stage.endTime ?: clock.millis()) - (stage.startTime ?: 0))
}
private fun bucketDuration(duration: Long) =
when {
duration > TimeUnit.MINUTES.toMillis(60) -> "gt60m"
duration > TimeUnit.MINUTES.toMillis(30) -> "gt30m"
duration > TimeUnit.MINUTES.toMillis(15) -> "gt15m"
duration > TimeUnit.MINUTES.toMillis(5) -> "gt5m"
else -> "lt5m"
}
override val messageType = CompleteStage::class.java
/**
* Plan any outstanding synthetic after stages.
*/
private fun Stage.planAfterStages() {
var hasPlannedStages = false
builder().buildAfterStages(this) { it: Stage ->
repository.addStage(it)
hasPlannedStages = true
}
if (hasPlannedStages) {
this.execution = repository.retrieve(this.execution.type, this.execution.id)
}
}
/**
* Plan any outstanding synthetic on failure stages.
*/
private fun Stage.planOnFailureStages(): Boolean {
// Avoid planning failure stages if _any_ with the same name are already complete
val previouslyPlannedAfterStageNames = afterStages().filter { it.status.isComplete }.map { it.name }
val graph = StageGraphBuilder.afterStages(this)
builder().onFailureStages(this, graph)
val onFailureStages = graph.build().toList()
onFailureStages.forEachIndexed { index, stage ->
if (index > 0) {
// all on failure stages should be run linearly
graph.connect(onFailureStages.get(index - 1), stage)
}
}
val alreadyPlanned = onFailureStages.any { previouslyPlannedAfterStageNames.contains(it.name) }
return if (alreadyPlanned || onFailureStages.isEmpty()) {
false
} else {
removeNotStartedSynthetics() // should be all synthetics (nothing should have been started!)
appendAfterStages(onFailureStages) {
repository.addStage(it)
}
true
}
}
private fun Stage.removeNotStartedSynthetics() {
syntheticStages()
.filter { it.status == NOT_STARTED }
.forEach { stage ->
execution
.stages
.filter { it.requisiteStageRefIds.contains(stage.id) }
.forEach {
it.requisiteStageRefIds = it.requisiteStageRefIds - stage.id
repository.addStage(it)
}
stage.removeNotStartedSynthetics() // should be all synthetics!
repository.removeStage(execution, stage.id)
}
}
}
private fun Stage.hasPlanningFailure() =
context["beforeStagePlanningFailed"] == true
private fun Stage.determineStatus(): ExecutionStatus {
val syntheticStatuses = syntheticStages().map(Stage::getStatus)
val taskStatuses = tasks.map(Task::getStatus)
val planningStatus = if (hasPlanningFailure()) listOf(failureStatus()) else emptyList()
val allStatuses = syntheticStatuses + taskStatuses + planningStatus
val afterStageStatuses = afterStages().map(Stage::getStatus)
return when {
allStatuses.isEmpty() -> NOT_STARTED
allStatuses.contains(TERMINAL) -> TERMINAL
allStatuses.contains(STOPPED) -> STOPPED
allStatuses.contains(CANCELED) -> CANCELED
allStatuses.contains(FAILED_CONTINUE) -> FAILED_CONTINUE
allStatuses.all { it == SUCCEEDED } -> SUCCEEDED
afterStageStatuses.contains(NOT_STARTED) -> RUNNING // after stages were planned but not run yet
else -> TERMINAL
}
}
| apache-2.0 | 499f08932e01e7c1bd32f8914060144d | 38.145923 | 118 | 0.673172 | 4.574223 | false | false | false | false |
Philip-Trettner/GlmKt | GlmKt/src/glm/vec/Int/IntVec2.kt | 1 | 19684 | package glm
data class IntVec2(val x: Int, val y: Int) {
// Initializes each element by evaluating init from 0 until 1
constructor(init: (Int) -> Int) : this(init(0), init(1))
operator fun get(idx: Int): Int = when (idx) {
0 -> x
1 -> y
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
// Operators
operator fun inc(): IntVec2 = IntVec2(x.inc(), y.inc())
operator fun dec(): IntVec2 = IntVec2(x.dec(), y.dec())
operator fun unaryPlus(): IntVec2 = IntVec2(+x, +y)
operator fun unaryMinus(): IntVec2 = IntVec2(-x, -y)
operator fun plus(rhs: IntVec2): IntVec2 = IntVec2(x + rhs.x, y + rhs.y)
operator fun minus(rhs: IntVec2): IntVec2 = IntVec2(x - rhs.x, y - rhs.y)
operator fun times(rhs: IntVec2): IntVec2 = IntVec2(x * rhs.x, y * rhs.y)
operator fun div(rhs: IntVec2): IntVec2 = IntVec2(x / rhs.x, y / rhs.y)
operator fun rem(rhs: IntVec2): IntVec2 = IntVec2(x % rhs.x, y % rhs.y)
operator fun plus(rhs: Int): IntVec2 = IntVec2(x + rhs, y + rhs)
operator fun minus(rhs: Int): IntVec2 = IntVec2(x - rhs, y - rhs)
operator fun times(rhs: Int): IntVec2 = IntVec2(x * rhs, y * rhs)
operator fun div(rhs: Int): IntVec2 = IntVec2(x / rhs, y / rhs)
operator fun rem(rhs: Int): IntVec2 = IntVec2(x % rhs, y % rhs)
inline fun map(func: (Int) -> Int): IntVec2 = IntVec2(func(x), func(y))
fun toList(): List<Int> = listOf(x, y)
// Predefined vector constants
companion object Constants {
val zero: IntVec2 = IntVec2(0, 0)
val ones: IntVec2 = IntVec2(1, 1)
val unitX: IntVec2 = IntVec2(1, 0)
val unitY: IntVec2 = IntVec2(0, 1)
}
// Conversions to Float
fun toVec(): Vec2 = Vec2(x.toFloat(), y.toFloat())
inline fun toVec(conv: (Int) -> Float): Vec2 = Vec2(conv(x), conv(y))
fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat())
inline fun toVec2(conv: (Int) -> Float): Vec2 = Vec2(conv(x), conv(y))
fun toVec3(z: Float = 0f): Vec3 = Vec3(x.toFloat(), y.toFloat(), z)
inline fun toVec3(z: Float = 0f, conv: (Int) -> Float): Vec3 = Vec3(conv(x), conv(y), z)
fun toVec4(z: Float = 0f, w: Float = 0f): Vec4 = Vec4(x.toFloat(), y.toFloat(), z, w)
inline fun toVec4(z: Float = 0f, w: Float = 0f, conv: (Int) -> Float): Vec4 = Vec4(conv(x), conv(y), z, w)
// Conversions to Float
fun toMutableVec(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat())
inline fun toMutableVec(conv: (Int) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat())
inline fun toMutableVec2(conv: (Int) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
fun toMutableVec3(z: Float = 0f): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z)
inline fun toMutableVec3(z: Float = 0f, conv: (Int) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), z)
fun toMutableVec4(z: Float = 0f, w: Float = 0f): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z, w)
inline fun toMutableVec4(z: Float = 0f, w: Float = 0f, conv: (Int) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), z, w)
// Conversions to Double
fun toDoubleVec(): DoubleVec2 = DoubleVec2(x.toDouble(), y.toDouble())
inline fun toDoubleVec(conv: (Int) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x.toDouble(), y.toDouble())
inline fun toDoubleVec2(conv: (Int) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
fun toDoubleVec3(z: Double = 0.0): DoubleVec3 = DoubleVec3(x.toDouble(), y.toDouble(), z)
inline fun toDoubleVec3(z: Double = 0.0, conv: (Int) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), z)
fun toDoubleVec4(z: Double = 0.0, w: Double = 0.0): DoubleVec4 = DoubleVec4(x.toDouble(), y.toDouble(), z, w)
inline fun toDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (Int) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), z, w)
// Conversions to Double
fun toMutableDoubleVec(): MutableDoubleVec2 = MutableDoubleVec2(x.toDouble(), y.toDouble())
inline fun toMutableDoubleVec(conv: (Int) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x.toDouble(), y.toDouble())
inline fun toMutableDoubleVec2(conv: (Int) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
fun toMutableDoubleVec3(z: Double = 0.0): MutableDoubleVec3 = MutableDoubleVec3(x.toDouble(), y.toDouble(), z)
inline fun toMutableDoubleVec3(z: Double = 0.0, conv: (Int) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), z)
fun toMutableDoubleVec4(z: Double = 0.0, w: Double = 0.0): MutableDoubleVec4 = MutableDoubleVec4(x.toDouble(), y.toDouble(), z, w)
inline fun toMutableDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (Int) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), z, w)
// Conversions to Int
fun toIntVec(): IntVec2 = IntVec2(x, y)
inline fun toIntVec(conv: (Int) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
fun toIntVec2(): IntVec2 = IntVec2(x, y)
inline fun toIntVec2(conv: (Int) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
fun toIntVec3(z: Int = 0): IntVec3 = IntVec3(x, y, z)
inline fun toIntVec3(z: Int = 0, conv: (Int) -> Int): IntVec3 = IntVec3(conv(x), conv(y), z)
fun toIntVec4(z: Int = 0, w: Int = 0): IntVec4 = IntVec4(x, y, z, w)
inline fun toIntVec4(z: Int = 0, w: Int = 0, conv: (Int) -> Int): IntVec4 = IntVec4(conv(x), conv(y), z, w)
// Conversions to Int
fun toMutableIntVec(): MutableIntVec2 = MutableIntVec2(x, y)
inline fun toMutableIntVec(conv: (Int) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x, y)
inline fun toMutableIntVec2(conv: (Int) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
fun toMutableIntVec3(z: Int = 0): MutableIntVec3 = MutableIntVec3(x, y, z)
inline fun toMutableIntVec3(z: Int = 0, conv: (Int) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), z)
fun toMutableIntVec4(z: Int = 0, w: Int = 0): MutableIntVec4 = MutableIntVec4(x, y, z, w)
inline fun toMutableIntVec4(z: Int = 0, w: Int = 0, conv: (Int) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), z, w)
// Conversions to Long
fun toLongVec(): LongVec2 = LongVec2(x.toLong(), y.toLong())
inline fun toLongVec(conv: (Int) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong())
inline fun toLongVec2(conv: (Int) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
fun toLongVec3(z: Long = 0L): LongVec3 = LongVec3(x.toLong(), y.toLong(), z)
inline fun toLongVec3(z: Long = 0L, conv: (Int) -> Long): LongVec3 = LongVec3(conv(x), conv(y), z)
fun toLongVec4(z: Long = 0L, w: Long = 0L): LongVec4 = LongVec4(x.toLong(), y.toLong(), z, w)
inline fun toLongVec4(z: Long = 0L, w: Long = 0L, conv: (Int) -> Long): LongVec4 = LongVec4(conv(x), conv(y), z, w)
// Conversions to Long
fun toMutableLongVec(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong())
inline fun toMutableLongVec(conv: (Int) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong())
inline fun toMutableLongVec2(conv: (Int) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
fun toMutableLongVec3(z: Long = 0L): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z)
inline fun toMutableLongVec3(z: Long = 0L, conv: (Int) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), z)
fun toMutableLongVec4(z: Long = 0L, w: Long = 0L): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z, w)
inline fun toMutableLongVec4(z: Long = 0L, w: Long = 0L, conv: (Int) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), z, w)
// Conversions to Short
fun toShortVec(): ShortVec2 = ShortVec2(x.toShort(), y.toShort())
inline fun toShortVec(conv: (Int) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
fun toShortVec2(): ShortVec2 = ShortVec2(x.toShort(), y.toShort())
inline fun toShortVec2(conv: (Int) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
fun toShortVec3(z: Short = 0.toShort()): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z)
inline fun toShortVec3(z: Short = 0.toShort(), conv: (Int) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), z)
fun toShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort()): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z, w)
inline fun toShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (Int) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), z, w)
// Conversions to Short
fun toMutableShortVec(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort())
inline fun toMutableShortVec(conv: (Int) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort())
inline fun toMutableShortVec2(conv: (Int) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
fun toMutableShortVec3(z: Short = 0.toShort()): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z)
inline fun toMutableShortVec3(z: Short = 0.toShort(), conv: (Int) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), z)
fun toMutableShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort()): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z, w)
inline fun toMutableShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (Int) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), z, w)
// Conversions to Byte
fun toByteVec(): ByteVec2 = ByteVec2(x.toByte(), y.toByte())
inline fun toByteVec(conv: (Int) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
fun toByteVec2(): ByteVec2 = ByteVec2(x.toByte(), y.toByte())
inline fun toByteVec2(conv: (Int) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
fun toByteVec3(z: Byte = 0.toByte()): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z)
inline fun toByteVec3(z: Byte = 0.toByte(), conv: (Int) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), z)
fun toByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte()): ByteVec4 = ByteVec4(x.toByte(), y.toByte(), z, w)
inline fun toByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (Int) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), z, w)
// Conversions to Byte
fun toMutableByteVec(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte())
inline fun toMutableByteVec(conv: (Int) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte())
inline fun toMutableByteVec2(conv: (Int) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
fun toMutableByteVec3(z: Byte = 0.toByte()): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z)
inline fun toMutableByteVec3(z: Byte = 0.toByte(), conv: (Int) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), z)
fun toMutableByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte()): MutableByteVec4 = MutableByteVec4(x.toByte(), y.toByte(), z, w)
inline fun toMutableByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (Int) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), z, w)
// Conversions to Char
fun toCharVec(): CharVec2 = CharVec2(x.toChar(), y.toChar())
inline fun toCharVec(conv: (Int) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar())
inline fun toCharVec2(conv: (Int) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
fun toCharVec3(z: Char): CharVec3 = CharVec3(x.toChar(), y.toChar(), z)
inline fun toCharVec3(z: Char, conv: (Int) -> Char): CharVec3 = CharVec3(conv(x), conv(y), z)
fun toCharVec4(z: Char, w: Char): CharVec4 = CharVec4(x.toChar(), y.toChar(), z, w)
inline fun toCharVec4(z: Char, w: Char, conv: (Int) -> Char): CharVec4 = CharVec4(conv(x), conv(y), z, w)
// Conversions to Char
fun toMutableCharVec(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar())
inline fun toMutableCharVec(conv: (Int) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar())
inline fun toMutableCharVec2(conv: (Int) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
fun toMutableCharVec3(z: Char): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z)
inline fun toMutableCharVec3(z: Char, conv: (Int) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), z)
fun toMutableCharVec4(z: Char, w: Char): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z, w)
inline fun toMutableCharVec4(z: Char, w: Char, conv: (Int) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), z, w)
// Conversions to Boolean
fun toBoolVec(): BoolVec2 = BoolVec2(x != 0, y != 0)
inline fun toBoolVec(conv: (Int) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0, y != 0)
inline fun toBoolVec2(conv: (Int) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec3(z: Boolean = false): BoolVec3 = BoolVec3(x != 0, y != 0, z)
inline fun toBoolVec3(z: Boolean = false, conv: (Int) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), z)
fun toBoolVec4(z: Boolean = false, w: Boolean = false): BoolVec4 = BoolVec4(x != 0, y != 0, z, w)
inline fun toBoolVec4(z: Boolean = false, w: Boolean = false, conv: (Int) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), z, w)
// Conversions to Boolean
fun toMutableBoolVec(): MutableBoolVec2 = MutableBoolVec2(x != 0, y != 0)
inline fun toMutableBoolVec(conv: (Int) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0, y != 0)
inline fun toMutableBoolVec2(conv: (Int) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec3(z: Boolean = false): MutableBoolVec3 = MutableBoolVec3(x != 0, y != 0, z)
inline fun toMutableBoolVec3(z: Boolean = false, conv: (Int) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), z)
fun toMutableBoolVec4(z: Boolean = false, w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x != 0, y != 0, z, w)
inline fun toMutableBoolVec4(z: Boolean = false, w: Boolean = false, conv: (Int) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), z, w)
// Conversions to String
fun toStringVec(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec(conv: (Int) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec2(conv: (Int) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec3(z: String = ""): StringVec3 = StringVec3(x.toString(), y.toString(), z)
inline fun toStringVec3(z: String = "", conv: (Int) -> String): StringVec3 = StringVec3(conv(x), conv(y), z)
fun toStringVec4(z: String = "", w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z, w)
inline fun toStringVec4(z: String = "", w: String = "", conv: (Int) -> String): StringVec4 = StringVec4(conv(x), conv(y), z, w)
// Conversions to String
fun toMutableStringVec(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec(conv: (Int) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec2(conv: (Int) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec3(z: String = ""): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z)
inline fun toMutableStringVec3(z: String = "", conv: (Int) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), z)
fun toMutableStringVec4(z: String = "", w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z, w)
inline fun toMutableStringVec4(z: String = "", w: String = "", conv: (Int) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), z, w)
// Conversions to T2
inline fun <T2> toTVec(conv: (Int) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec2(conv: (Int) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec3(z: T2, conv: (Int) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), z)
inline fun <T2> toTVec4(z: T2, w: T2, conv: (Int) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), z, w)
// Conversions to T2
inline fun <T2> toMutableTVec(conv: (Int) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec2(conv: (Int) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec3(z: T2, conv: (Int) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), z)
inline fun <T2> toMutableTVec4(z: T2, w: T2, conv: (Int) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), z, w)
// Allows for swizzling, e.g. v.swizzle.xzx
inner class Swizzle {
val xx: IntVec2 get() = IntVec2(x, x)
val xy: IntVec2 get() = IntVec2(x, y)
val yx: IntVec2 get() = IntVec2(y, x)
val yy: IntVec2 get() = IntVec2(y, y)
val xxx: IntVec3 get() = IntVec3(x, x, x)
val xxy: IntVec3 get() = IntVec3(x, x, y)
val xyx: IntVec3 get() = IntVec3(x, y, x)
val xyy: IntVec3 get() = IntVec3(x, y, y)
val yxx: IntVec3 get() = IntVec3(y, x, x)
val yxy: IntVec3 get() = IntVec3(y, x, y)
val yyx: IntVec3 get() = IntVec3(y, y, x)
val yyy: IntVec3 get() = IntVec3(y, y, y)
val xxxx: IntVec4 get() = IntVec4(x, x, x, x)
val xxxy: IntVec4 get() = IntVec4(x, x, x, y)
val xxyx: IntVec4 get() = IntVec4(x, x, y, x)
val xxyy: IntVec4 get() = IntVec4(x, x, y, y)
val xyxx: IntVec4 get() = IntVec4(x, y, x, x)
val xyxy: IntVec4 get() = IntVec4(x, y, x, y)
val xyyx: IntVec4 get() = IntVec4(x, y, y, x)
val xyyy: IntVec4 get() = IntVec4(x, y, y, y)
val yxxx: IntVec4 get() = IntVec4(y, x, x, x)
val yxxy: IntVec4 get() = IntVec4(y, x, x, y)
val yxyx: IntVec4 get() = IntVec4(y, x, y, x)
val yxyy: IntVec4 get() = IntVec4(y, x, y, y)
val yyxx: IntVec4 get() = IntVec4(y, y, x, x)
val yyxy: IntVec4 get() = IntVec4(y, y, x, y)
val yyyx: IntVec4 get() = IntVec4(y, y, y, x)
val yyyy: IntVec4 get() = IntVec4(y, y, y, y)
}
val swizzle: Swizzle get() = Swizzle()
}
fun vecOf(x: Int, y: Int): IntVec2 = IntVec2(x, y)
operator fun Int.plus(rhs: IntVec2): IntVec2 = IntVec2(this + rhs.x, this + rhs.y)
operator fun Int.minus(rhs: IntVec2): IntVec2 = IntVec2(this - rhs.x, this - rhs.y)
operator fun Int.times(rhs: IntVec2): IntVec2 = IntVec2(this * rhs.x, this * rhs.y)
operator fun Int.div(rhs: IntVec2): IntVec2 = IntVec2(this / rhs.x, this / rhs.y)
operator fun Int.rem(rhs: IntVec2): IntVec2 = IntVec2(this % rhs.x, this % rhs.y)
| mit | 0b20a22ea69cc6984f3e30c915d9b5e0 | 69.805755 | 164 | 0.645753 | 3.29274 | false | false | false | false |
emoji-gen/Emoji-Android | app/src/main/java/moe/pine/emoji/view/setting/TeamListItemView.kt | 1 | 1397 | package moe.pine.emoji.view.setting
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.util.AttributeSet
import android.widget.LinearLayout
import kotlinx.android.synthetic.main.view_setting_team_list_item.view.*
import moe.pine.emoji.fragment.setting.DeleteTeamDialogFragment
import moe.pine.emoji.model.realm.SlackTeam
/**
* View for team list item
* Created by pine on May 14, 2017.
*/
class TeamListItemView : LinearLayout {
var team: SlackTeam? = null
set(value) {
this.text_view_setting_team_domain.text = value?.team.orEmpty()
this.text_view_setting_team_email.text = value?.email.orEmpty()
field = value
}
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onFinishInflate() {
super.onFinishInflate()
this.button_setting_team_delete.setOnClickListener { this.remove() }
}
private fun remove() {
val domain = this.team?.team ?: return
val activity = this.context as? AppCompatActivity
val dialog = DeleteTeamDialogFragment.newInstance(domain)
activity?.supportFragmentManager?.let { dialog.show(it, null) }
}
} | mit | c58efb8e0e23a8990892ddd6dd263502 | 35.789474 | 113 | 0.709377 | 4.195195 | false | false | false | false |
code-disaster/lwjgl3 | modules/generator/src/main/kotlin/org/lwjgl/generator/Structs.kt | 1 | 117108 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.generator
import java.io.*
import java.nio.file.*
private const val STRUCT = "struct"
private val KEYWORDS = JAVA_KEYWORDS + setOf(
// Object
"equals", "getClass", "hashCode", "notify", "notifyAll", "toString", "wait",
// Pointer
"address",
// AutoCloseable
"close",
// NativeResource
"free",
// Struct
"create", "callocStack", "calloc", "isNull", "malloc", "mallocStack", "sizeof"
)
private val BUFFER_KEYWORDS = setOf(
// Iterable
"iterator", "forEach", "spliterator",
// CustomBuffer
"address0", "capacity", "clear", "compact", "duplicate", "flip", "hasRemaining", "limit", "mark", "position", "remaining", "reset", "rewind",
"slice",
// StructBuffer
"apply", "get", "parallelStream", "put", "stream"
)
open class StructMember(
val nativeType: DataType,
val name: String,
val documentation: String,
val bits: Int
) : ModifierTarget<StructMemberModifier>() {
override fun validate(modifier: StructMemberModifier) = modifier.validate(this)
internal var getter: String? = null
fun getter(expression: String): StructMember {
this.getter = expression
return this
}
internal var setter: String? = null
fun setter(expression: String): StructMember {
this.setter = expression
return this
}
fun copyAccessors(member: StructMember): StructMember {
this.getter = member.getter
this.setter = member.setter
return this
}
internal val offsetField
get() = name.uppercase()
internal fun offsetField(parentField: String): String {
return if (parentField.isEmpty())
offsetField
else
"${parentField}_$offsetField"
}
/** hidden if false, contributes to layout only */
internal var public = true
fun private(): StructMember {
public = false
return this
}
/** private + hidden from struct layout javadoc */
internal var virtual = false
fun virtual(): StructMember {
virtual = true
return private()
}
/** mutable if true, even if the parent struct is not mutable */
internal var mutable = false
fun mutable(): StructMember {
mutable = true
return this
}
internal var links: String = ""
internal var linkMode: LinkMode = LinkMode.SINGLE
fun links(links: String, linkMode: LinkMode = LinkMode.SINGLE) {
this.links = links
this.linkMode = linkMode
}
internal open fun copy() = StructMember(nativeType, name, documentation, bits)
}
open class StructMemberArray(
val arrayType: CArrayType<*>,
name: String,
documentation: String,
/** Number of pointer elements that must not be null. */
val validSize: String
) : StructMember(arrayType.elementType, name, documentation, -1) {
val size: String get() = arrayType.size
val primitiveMapping get() = nativeType.let {
if (it is PointerType<*>) PrimitiveMapping.POINTER else it.mapping as PrimitiveMapping
}
override fun copy() = StructMemberArray(arrayType, name, documentation, validSize)
}
private class StructMemberPadding(arrayType: CArrayType<*>, val condition: String?) : StructMemberArray(arrayType, ANONYMOUS, "", arrayType.size)
{
init {
public = false
}
override fun copy(): StructMemberPadding = StructMemberPadding(arrayType, condition)
}
private enum class MultiSetterMode {
NORMAL,
ALTER
}
private enum class AccessMode(val indent: String) {
INSTANCE(t),
FLYWEIGHT("$t$t");
}
class Struct(
module: Module,
className: String,
nativeSubPath: String = "",
/** The native struct name. May be different than className. */
val nativeName: String,
internal val union: Boolean,
/** when true, a declaration is missing, we need to output one. */
private val virtual: Boolean,
/** when false, setters methods will not be generated. */
private val mutable: Boolean,
/** if specified, this struct aliases it. */
private val alias: Struct?,
/** if specified, this struct is a subtype of it. */
internal val parentStruct: Struct?,
/** when true, the struct layout will be built using native code. */
internal val nativeLayout: Boolean,
/** when true, a nested StructBuffer subclass will be generated as well. */
private val generateBuffer: Boolean
) : GeneratorTargetNative(module, className, nativeSubPath) {
companion object {
private val bufferMethodMap = mapOf(
"boolean" to "Byte",
"byte" to "Byte",
"char" to "Char",
"short" to "Short",
"int" to "Int",
"long" to "Long",
"float" to "Float",
"double" to "Double"
)
private const val BUFFER_CAPACITY_PARAM = "capacity"
private val BUFFER_CAPACITY = Parameter(int, BUFFER_CAPACITY_PARAM, "the number of elements in the returned buffer")
// Do not generate deprecated stack allocation methods for structs introduced after 3.2.3.
private val STRUCTS_323 = Files
.readAllLines(Paths.get("modules/generator/src/main/resources/structs3.2.3.txt"))
.toHashSet()
}
/* Output parameter or function result by value */
private var usageOutput = false
/* Input parameter */
private var usageInput = false
/* Function result by reference */
private var usageResultPointer = false
private var static: String? = null
private var pack: String? = null
// TODO: add alignas support to non-struct members if necessary
private var alignas: String? = null
private val customMethods = ArrayList<String>()
private val customMethodsBuffer = ArrayList<String>()
internal val members = ArrayList<StructMember>()
internal fun init(setup: (Struct.() -> Unit)? = null): StructType {
if (setup != null) {
this.setup()
}
if (setup != null || nativeLayout) {
Generator.register(this)
}
return nativeType
}
internal fun copy(className: String, nativeName: String = className, virtual: Boolean = this.virtual): Struct {
val copy = Struct(
module,
className,
nativeSubPath,
nativeName,
union,
virtual,
mutable,
alias,
parentStruct,
nativeLayout,
generateBuffer
)
copy.documentation = documentation
copy.static = static
copy.alignas = alignas
copy.pack = pack
//copy.usageInput = usageInput
//copy.usageOutput = usageOutput
//copy.usageResultPointer = usageResultPointer
copy.customMethods.addAll(customMethods)
copy.customMethodsBuffer.addAll(customMethodsBuffer)
copy.members.addAll(members)
return copy
}
val nativeType get() = StructType(this)
fun setUsageOutput() {
usageOutput = true
}
fun setUsageInput() {
usageInput = true
}
fun setUsageResultPointer() {
usageResultPointer = true
}
fun static(expression: String) {
static = expression
}
fun pack(expression: String) {
pack = expression
}
fun pack(alignment: Int) {
pack = alignment.toString()
}
fun alignas(expression: String) {
alignas = expression
}
fun alignas(alignment: Int) {
alignas = alignment.toString()
}
private val visibleMembers
get() = members.asSequence().filter { it !is StructMemberPadding }
private val publicMembers
get() = members.asSequence().filter { it.public }
private fun mutableMembers(members: Sequence<StructMember> = publicMembers): Sequence<StructMember> = members.let {
if (mutable) it else it.filter { member -> member.mutable }
}
private val settableMembers: Sequence<StructMember> by lazy(LazyThreadSafetyMode.NONE) {
val mutableMembers = mutableMembers()
mutableMembers.filter { !it.has<AutoSizeMember> { !keepSetter(mutableMembers) } }
}
private fun hasMutableMembers(members: Sequence<StructMember> = publicMembers) = this.members.isNotEmpty() && (mutable || mutableMembers(members).any())
operator fun get(name: String): StructMember = members.asSequence().first { it.name == name }
fun StructMember.replace(old: StructMember): StructMember {
members.remove(this)
members[members.indexOf(old)] = this
return this
}
infix fun StructType.copy(member: String) = add(definition[member].copy())
private fun add(member: StructMember): StructMember {
members.add(member)
return member
}
// Plain struct member
operator fun DataType.invoke(name: String, documentation: String) = add(StructMember(this, name, documentation, -1))
// Array struct member
operator fun CArrayType<*>.invoke(name: String, documentation: String, validSize: String = this.size) = add(StructMemberArray(this, name, documentation, validSize))
// Bitfield struct member
operator fun PrimitiveType.invoke(name: String, documentation: String, bits: Int) = add(StructMember(this, name, documentation, bits))
private fun Int.toHexMask() = Integer.toHexString(this)
.uppercase()
.padStart(8, '0')
.let {
"0x${it.substring(0, 2)}_${it.substring(2, 4)}_${it.substring(4, 6)}_${it.substring(6, 8)}"
}
fun StructMember.bitfield(bitfield: Int, bitmask: Int): StructMember {
if (bits != bitmask.countOneBits()) {
this.error("The number of bits set in the specified bitmask (${bitmask.countOneBits()}) does not match the struct member bits ($bits)")
}
val mask = bitmask.toHexMask()
val maskInv = bitmask.inv().toHexMask()
val shift = bitmask.countTrailingZeroBits()
if (shift == 0) {
this.getter("nbitfield$bitfield(struct) & $mask")
this.setter("nbitfield$bitfield(struct, (nbitfield$bitfield(struct) & $maskInv) | (value & $mask))")
} else if (bits + shift == Int.SIZE_BITS) {
this.getter("nbitfield$bitfield(struct) >>> $shift")
this.setter("nbitfield$bitfield(struct, (value << $shift) | (nbitfield$bitfield(struct) & $maskInv))")
} else {
this.getter("(nbitfield$bitfield(struct) & $mask) >>> $shift")
this.setter("nbitfield$bitfield(struct, ((value << $shift) & $mask) | (nbitfield$bitfield(struct) & $maskInv))")
}
return this
}
// Converts a plain member to an array member
operator fun StructMember.get(size: Int, validSize: Int = size) = this[size.toString(), validSize.toString()]
operator fun StructMember.get(size: String, validSize: String = size): StructMemberArray {
[email protected](this)
val nativeType = if (isNestedStructDefinition) {
(this.nativeType as StructType)
.definition.copy(
className = this.name,
nativeName = ANONYMOUS,
virtual = true
)
.nativeType
} else
this.nativeType
return StructMemberArray(nativeType[size], name, documentation, validSize)
.let {
add(it)
it
}
}
// Converts an N-dimensional array to an (N+1)-dimensional array.
operator fun StructMemberArray.get(size: Int, validSize: Int = size) = this[size.toString(), validSize.toString()]
operator fun StructMemberArray.get(size: String, validSize: String): StructMemberArray {
[email protected](this)
return StructMemberArray(arrayType[size], name, documentation, "${this.validSize} * $validSize")
.let {
add(it)
it
}
}
fun padding(size: Int, condition: String? = null) = padding(size.toString(), condition)
fun padding(size: String, condition: String? = null) = add(StructMemberPadding(char[size], condition))
fun PrimitiveType.padding(size: Int, condition: String? = null) = this.padding(size.toString(), condition)
fun PrimitiveType.padding(size: String, condition: String? = null) = add(StructMemberPadding(this[size], condition))
/** Anonymous nested member struct definition. */
fun struct(
mutable: Boolean = this.mutable,
alias: StructType? = null,
parentStruct: StructType? = null,
nativeLayout: Boolean = false,
skipBuffer: Boolean = false,
setup: Struct.() -> Unit
): StructMember {
val struct = Struct(module, ANONYMOUS, nativeSubPath, ANONYMOUS, false, true, mutable, alias?.definition, parentStruct?.definition, nativeLayout, !skipBuffer)
struct.setup()
return StructType(struct).invoke(ANONYMOUS, "")
}
/** Anonymous nested member union definition. */
fun union(
mutable: Boolean = this.mutable,
alias: StructType? = null,
parentStruct: StructType? = null,
nativeLayout: Boolean = false,
skipBuffer: Boolean = false,
setup: Struct.() -> Unit
): StructMember {
val struct = Struct(module, ANONYMOUS, nativeSubPath, ANONYMOUS, true, true, mutable, alias?.definition, parentStruct?.definition, nativeLayout, !skipBuffer)
struct.setup()
return StructType(struct).invoke(ANONYMOUS, "")
}
/** Named nested struct/union. */
operator fun StructMember.invoke(name: String, documentation: String): StructMember {
[email protected](this)
return this.nativeType.invoke(name, documentation)
}
fun customMethod(method: String) {
customMethods.add(method.trim())
}
fun customMethodBuffer(method: String) {
customMethodsBuffer.add(method.trim())
}
private fun PrintWriter.printCustomMethods(customMethods: ArrayList<String>, static: Boolean, indent: String = t) {
customMethods
.filter { it.startsWith("static {") == static }
.forEach {
println("\n$indent$it")
}
}
/** A pointer-to-struct member points to an array of structs, rather than a single struct. */
private val StructMember.isStructBuffer
get() = getReferenceMember<AutoSizeMember>(this.name) != null || this.has<Unsafe>()
/** The nested struct's members are embedded in the parent struct. */
private val StructMember.isNestedStruct
get() = nativeType is StructType && this !is StructMemberArray
/** The nested struct is not defined elsewhere, it's part of the parent struct's definition. */
private val StructMember.isNestedStructDefinition
get() = isNestedStruct && (nativeType as StructType).name === ANONYMOUS
private val StructMember.nestedMembers
get() = (nativeType as StructType).definition.visibleMembers
private val containsUnion: Boolean get() = union || members.any {
it.isNestedStruct && (it.nativeType as StructType).let { type -> type.name === ANONYMOUS && type.definition.containsUnion }
}
private fun StructMember.field(parentMember: String) = if (parentMember.isEmpty())
if (KEYWORDS.contains(name) || (generateBuffer && BUFFER_KEYWORDS.contains(name))) "$name\$" else name
else
"${parentMember}_$name"
private fun StructMember.fieldName(parentMember: String) = if (parentMember.isEmpty())
name
else
"$parentMember.$name"
internal val validations: Sequence<String> by lazy(LazyThreadSafetyMode.NONE) {
if (union)
return@lazy emptySequence<String>()
val validations = ArrayList<String>()
fun MutableList<String>.addPointer(m: StructMember) = this.add("$t${t}long ${m.name} = memGetAddress($STRUCT + $className.${m.offsetField});")
fun MutableList<String>.addCount(m: StructMember) = this.add("$t$t${m.nativeType.javaMethodType} ${m.name} = n${m.name}($STRUCT);")
fun validate(m: StructMember, indent: String, hasPointer: Boolean = false): String {
return if (m.nativeType.hasStructValidation) {
if (m is StructMemberArray) {
"""${
if (hasPointer) "" else "${indent}long ${m.name} = $STRUCT + $className.${m.offsetField};\n"
}${indent}for (int i = 0; i < ${getReferenceMember<AutoSizeMember>(m.name)?.name ?: m.size}; i++) {${
if (m.nativeType is PointerType<*>) {
if (m.validSize == m.size)
"\n$indent check(memGetAddress(${m.name}));"
else
"""
$indent if (i < ${m.validSize}) {
$indent check(memGetAddress(${m.name}));
$indent } else if (memGetAddress(${m.name}) == NULL) {
$indent break;
$indent }"""
} else ""}
$indent ${m.nativeType.javaMethodType}.validate(${m.name});
$indent ${m.name} += POINTER_SIZE;
$indent}"""
} else {
"${if (hasPointer) "" else
"${indent}long ${m.name} = memGetAddress($STRUCT + $className.${m.offsetField});\n" +
"${indent}check(${m.name});\n"
}$indent${getReferenceMember<AutoSizeMember>(m.name).let {
if (it == null)
"${m.nativeType.javaMethodType}.validate(${m.name});"
else
"validate(${m.name}, ${it.name}, ${m.nativeType.javaMethodType}.SIZEOF, ${m.nativeType.javaMethodType}::validate);"}
}"
}
} else
"${indent}check(memGetAddress($STRUCT + $className.${m.offsetField}));"
}
fun validationBlock(condition: String, validations: String): String = "$t${t}if ($condition) {\n$validations\n$t$t}"
mutableMembers().forEach { m ->
if (m.has<AutoSizeMember>()) {
m.get<AutoSizeMember>().let { autoSize ->
val refs = autoSize.members(mutableMembers())
if (autoSize.atLeastOne) {
// TODO: There will be redundancy here when one of the refs is a validateable struct array. But we don't have a case for it yet.
validations.addCount(m)
// if m != 0, make sure one of the auto-sized members is not null
validations.add(
"$t${t}if (${if (autoSize.optional) "\n$t$t$t${m.name} != 0 &&" else "\n$t$t$t${m.name} == 0 || ("}${
refs.map { "\n$t$t${t}memGetAddress($STRUCT + $className.${it.offsetField}) == NULL" }.joinToString(" &&")
}\n$t$t${if (autoSize.optional) "" else ")"}) {\n$t$t${t}throw new NullPointerException(\"At least one of ${refs.map { it.name }.joinToString()} must not be null\");\n$t$t}"
)
} else if (autoSize.optional) {
val refValidations = refs.filter { !it.has(nullable) }.map { ref ->
validate(ref, "$t$t$t")
}.joinToString("\n")
if (refValidations.isEmpty())
return@let
// if m != 0, make sure auto-sized members are not null
validations.add(
validationBlock("${if (refValidations.contains(", ${m.name}")) {
validations.addCount(m)
m.name
} else "n${m.name}($STRUCT)"} != 0", refValidations)
)
} else if (refs.any { it.nativeType.hasStructValidation })
validations.addCount(m)
}
} else if (m.nativeType is StructType && m.nativeType.definition.validations.any()) {
validations.add(
if (m is StructMemberArray)
validate(m, "$t$t")
else
"$t$t${m.nativeType.javaMethodType}.validate($STRUCT + $className.${m.offsetField});"
)
} else if (m.nativeType is PointerType<*> && getReferenceMember<AutoSizeMember>(m.name)?.get<AutoSizeMember>().let { it == null || !it.optional }) {
if (m.nativeType.hasStructValidation) {
validations.add(
if (m.has(nullable)) {
validations.addPointer(m)
validationBlock("${m.name} != NULL", validate(m, "$t$t$t", hasPointer = true))
} else
validate(m, "$t$t")
)
} else if (!m.has(nullable) && m.nativeType !is StructType) {
validations.add(validate(m, "$t$t"))
}
}
}
validations.asSequence()
}
/** Returns a member that has the specified ReferenceModifier with the specified reference. Returns null if no such parameter exists. */
private inline fun <reified T> getReferenceMember(reference: String) where T : StructMemberModifier, T : ReferenceModifier = members.firstOrNull {
it.has<T>(reference)
} // Assumes at most 1 parameter will be found that references the specified parameter
private fun getAutoSizeExpression(reference: String) = members
.filter { it.has<AutoSizeMember>(reference) }
.joinToString(" * ") { it.autoSize }
.run {
if (this.isEmpty())
null
else
this
}
private fun StructMember.getCheckExpression() = if (this.has<Check>())
this.get<Check>().expression.let { expression ->
// if expression is the name of another member, convert to auto-size expression
members.singleOrNull { it.name == expression }?.autoSize ?: expression
}
else
null
private fun PrintWriter.printDocumentation() {
val builder = StringBuilder()
val members = members.filter { it !is StructMemberPadding }
if (documentation != null) {
builder.append(documentation)
if (members.isNotEmpty())
builder.append("\n\n")
}
if (members.isNotEmpty()) {
builder.append("<h3>Layout</h3>\n\n")
builder.append(codeBlock(printStructLayout()))
}
if (builder.isNotEmpty())
println(processDocumentation(builder.toString()).toJavaDoc(indentation = "", see = see, since = since))
}
private val nativeNameQualified get() = (if (union) "union " else "struct ").let { type ->
when {
nativeName.startsWith(type) -> nativeName
nativeName === ANONYMOUS -> type.substring(0, type.length - 1)
else -> "$type$nativeName"
}
}
private fun printStructLayout(indentation: String = "", parent: String = "", parentGetter: String = ""): String {
val memberIndentation = "$indentation "
return """$nativeNameQualified {
${members.asSequence()
.filter { !it.virtual }
.joinToString(";\n$memberIndentation", prefix = memberIndentation, postfix = ";") { member ->
if (member.isNestedStructDefinition || (member is StructMemberArray && member.nativeType is StructType && member.nativeType.name === ANONYMOUS)) {
val struct = (member.nativeType as StructType).definition
val qualifiedClass = if (member.name === ANONYMOUS || struct.className === ANONYMOUS) {
parent
} else {
if (parent.isEmpty()) struct.className else "$parent.${struct.className}"
}
"${struct.printStructLayout(
memberIndentation,
qualifiedClass,
if (member.name === ANONYMOUS || (member is StructMemberArray && member.nativeType.name === ANONYMOUS)) parentGetter else member.field(parentGetter)
)}${if (member.name === ANONYMOUS) "" else " ${member.name.let {
if (member is StructMemberArray)
"{@link $qualifiedClass $it}${member.arrayType.def}"
else
it
}}"}"
} else {
val anonymous = member.name === ANONYMOUS || (member.nativeType is FunctionType && member.nativeType.name.contains("(*)"))
member.nativeType
.let {
when {
it is FunctionType && anonymous -> it.function.nativeType(member.name)
else -> it.name
}
}
.let {
var elementType: NativeType = member.nativeType
while (true) {
if (elementType !is PointerType<*> || elementType.elementType is OpaqueType) {
break
}
elementType = elementType.elementType
}
when {
elementType is FunctionType && anonymous -> it.replace(
"(*${member.name})",
"(*{@link ${elementType.javaMethodType} ${member.name}})"
)
elementType is StructType || elementType is FunctionType -> it.replace(
elementType.name, "{@link ${elementType.javaMethodType} ${elementType.name.let { name ->
if (name.endsWith(" const")) {
"${name.substring(0, name.length - 6)}} const"
} else {
"$name}"
}
}}")
else -> it
}
}
.let {
if (anonymous)
it
else if (!member.public || (member.documentation.isEmpty() && member.links.isEmpty()))
"$it ${member.name}"
else
"$it {@link $parent\\#${member.field(parentGetter).let { link -> if (parent.isEmpty() && link == member.name) link else "$link ${member.name}"}}}"
}
.let {
if (member.bits != -1)
"$it : ${member.bits}"
else if (member is StructMemberArray)
"$it${member.arrayType.def}"
else
it
}
}
}}
$indentation}"""
}
private val StructMember.javadoc: String?
get() = if (documentation.isNotEmpty() || links.isNotEmpty()) {
if (links.isEmpty())
documentation
else
linkMode.appendLinks(
documentation,
if (!links.contains('+')) links else linksFromRegex(links)
)
} else
null
private fun PrintWriter.printSetterJavadoc(accessMode: AccessMode, member: StructMember, indent: String, message: String, getter: String) {
println("$indent/** ${message.replace(
"#member",
if (member.documentation.isEmpty() && member.links.isEmpty())
"{@code ${member.name}}"
else
"{@link ${if (accessMode == AccessMode.INSTANCE) "" else className}#$getter}")} */")
}
private fun PrintWriter.printGetterJavadoc(accessMode: AccessMode, member: StructMember, indent: String, message: String, getter: String, memberName: String) {
val doc = member.javadoc
if (accessMode == AccessMode.INSTANCE) {
if (doc != null) {
println(processDocumentation(doc).toJavaDoc(indentation = indent))
return
}
}
println("$indent/** ${message.replace("#member", if (accessMode == AccessMode.INSTANCE || doc == null) {
"{@code $memberName}"
} else {
"{@link ${[email protected]}#$getter}"
})} */")
}
private fun PrintWriter.printGetterJavadoc(accessMode: AccessMode, member: StructMember, indent: String, message: String, getter: String, memberName: String, vararg parameters: Parameter) {
val doc = member.javadoc
if (accessMode == AccessMode.INSTANCE) {
if (doc != null) {
println(toJavaDoc("", parameters.asSequence(), member.nativeType, doc, null, "", indentation = indent))
return
}
}
println(toJavaDoc(message.replace("#member", if (accessMode == AccessMode.INSTANCE || doc == null) {
"{@code $memberName}"
} else {
"{@link ${[email protected]}#$getter}"
}), parameters.asSequence(), member.nativeType, "", null, "", indentation = indent))
}
private fun StructMember.error(msg: String) {
throw IllegalArgumentException("$msg [${[email protected]}, member: $name]")
}
private fun generateBitfields() {
var bitfieldIndex = 0
var m = 0
while (m < members.size) {
val ref = members[m]
if (ref.bits == -1) {
m++
continue
}
// skip custom bitfields (e.g. Yoga's <Bitfield.h>)
if (0 < m && members[m - 1].virtual) {
var bitsLeft = (members[m - 1].nativeType.mapping as PrimitiveMapping).bytes * 8
while (0 < bitsLeft && m < members.size && members[m].bits != -1) {
bitsLeft -= members[m++].bits
}
continue
}
val typeMapping = (ref.nativeType as PrimitiveType).mapping
val bitsTotal = typeMapping.bytes * 8
var bitsConsumed = 0
var i = m
while (bitsConsumed < bitsTotal && i < members.size) {
val member = members[i]
if (member.bits == -1 || (member.nativeType as PrimitiveType).mapping !== typeMapping || (bitsTotal - bitsConsumed) < member.bits) {
break
}
if (member.getter == null) {
member.bitfield(bitfieldIndex, (-1 ushr (bitsTotal - member.bits)) shl bitsConsumed)
} else {
val getter = member.getter
member.bitfield(bitfieldIndex, (-1 ushr (bitsTotal - member.bits)) shl bitsConsumed)
val newGetter = member.getter
check(getter == newGetter) { "$getter - $newGetter" }
}
bitsConsumed += member.bits
i++
}
members.add(m, StructMember(ref.nativeType, "bitfield${bitfieldIndex++}", "", -1).virtual())
m = i + 1
}
}
private fun validate(mallocable: Boolean) {
if (mallocable) {
members.forEach {
if (it.nativeType is PointerType<*> && it.nativeType.elementType is StructType)
it.nativeType.elementType.definition.setUsageInput()
}
}
members.filter { it.has<AutoSizeMember>() }.forEach {
val autoSize = it.get<AutoSizeMember>()
autoSize.references.forEach { reference ->
val bufferParam = members.firstOrNull { member -> member.name == reference }
if (bufferParam == null)
it.error("Reference does not exist: AutoSize($reference)")
else {
if (bufferParam !is StructMemberArray) {
if (bufferParam.nativeType !is PointerType<*>)
it.error("Reference must be a pointer type: AutoSize($reference)")
if (!bufferParam.nativeType.isPointerData)
it.error("Reference must not be a opaque pointer: AutoSize($reference)")
} else if (autoSize.optional || autoSize.atLeastOne)
it.error("Optional cannot be used with array references: AutoSize($reference)")
if (autoSize.atLeastOne && !bufferParam.has(nullable))
it.error("The \"atLeastOne\" option requires references to be nullable: AutoSize($reference)")
}
}
}
}
override fun PrintWriter.generateJava() = generateJava(false, 1)
private fun PrintWriter.generateJava(nested: Boolean, level: Int) {
if (alias != null) {
usageInput = usageInput or alias.usageInput
usageOutput = usageOutput or alias.usageOutput
usageResultPointer = usageResultPointer or alias.usageResultPointer
}
generateBitfields()
val mallocable = mutableMembers().any() || usageOutput || (usageInput && !usageResultPointer)
validate(mallocable)
val nativeLayout = !skipNative
if (nativeLayout) {
if (module !== Module.CORE && !module.key.startsWith("core.")) {
checkNotNull(module.library) {
"${t}Missing module library for native layout of struct: ${module.packageKotlin}.$className"
}
}
} else if (preamble.hasNativeDirectives) {
kotlin.io.println("${t}Unnecessary native directives in struct: ${module.packageKotlin}.$className")
}
if (!nested) {
print(HEADER)
println("package $packageName;\n")
println("import javax.annotation.*;\n")
println("import java.nio.*;\n")
if (mallocable || members.any { m ->
m.nativeType.let {
(it.mapping === PointerMapping.DATA_POINTER && it is PointerType<*> && (it.elementType !is StructType || m is StructMemberArray)) ||
(m is StructMemberArray && m.arrayType.elementType.isPointer && m.arrayType.elementType !is StructType)
}
})
println("import org.lwjgl.*;")
println("import org.lwjgl.system.*;\n")
fun Struct.hasChecks(): Boolean = visibleMembers.any {
(it is StructMemberArray && it.nativeType !is CharType) ||
(
(mutable || it.mutable) &&
(
it is StructMemberArray ||
it.nativeType is CharSequenceType ||
(it.nativeType is PointerType<*> && !it.has<Nullable>())
)
) ||
it.isNestedStructDefinition && (it.nativeType as StructType).definition.hasChecks()
}
if (Module.CHECKS && hasChecks())
println("import static org.lwjgl.system.Checks.*;")
println("import static org.lwjgl.system.MemoryUtil.*;")
if (nativeLayout || mallocable)
println("import static org.lwjgl.system.MemoryStack.*;")
}
println()
preamble.printJava(this)
printDocumentation()
if (className != nativeName) {
println("@NativeType(\"$nativeNameQualified\")")
}
print("${access.modifier}${if (nested) "static " else ""}class $className extends ")
print(alias?.className ?: "Struct${if (mallocable) " implements NativeResource" else ""}")
println(" {")
if (alias == null) {
print("""
/** The struct size in bytes. */
public static final int SIZEOF;
/** The struct alignment in bytes. */
public static final int ALIGNOF;
"""
)
val visibleMembersExceptBitfields = visibleMembers.filter { it.bits == -1 }
if (members.isNotEmpty() && (!nativeLayout || visibleMembersExceptBitfields.any())) {
val memberCount = getMemberCount(members)
// Member offset fields
if (visibleMembersExceptBitfields.any()) {
print(
"""
/** The struct member offsets. */
public static final int
"""
)
generateOffsetFields(visibleMembersExceptBitfields)
println(";")
}
print(
"""
static {"""
)
if (static != null)
print(
"""
$static
"""
)
// Member offset initialization
if (nativeLayout) {
if (module.library != null) {
print(
"""
${module.library.expression(module)}""")
}
print(
"""
try (MemoryStack stack = stackPush()) {
IntBuffer offsets = stack.mallocInt(${memberCount + 1});
SIZEOF = offsets(memAddress(offsets));
"""
)
generateOffsetInit(true, members, indentation = "$t$t$t")
println(
"""
ALIGNOF = offsets.get($memberCount);
}"""
)
} else {
print(
"""
Layout layout = """
)
generateLayout(this@Struct)
print(
""";
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
"""
)
generateOffsetInit(false, members)
}
println("$t}")
} else if (nativeLayout) {
print(
"""
static {"""
)
if (static != null)
print(
"""
$static
"""
)
println(
"""
${module.library!!.expression(module)}
try (MemoryStack stack = stackPush()) {
IntBuffer offsets = stack.mallocInt(1);
SIZEOF = offsets(memAddress(offsets));
ALIGNOF = offsets.get(0);
}
}"""
)
}
if (nativeLayout)
println(
"""
private static native int offsets(long buffer);"""
)
}
printCustomMethods(customMethods, static = true)
print("""
/**
* Creates a {@code $className} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
${access.modifier}$className(ByteBuffer container) {
super(${if (alias == null) "memAddress(container), __checkContainer(container, SIZEOF)" else "container"});
}
""")
if (alias == null) {
print("""
@Override
public int sizeof() { return SIZEOF; }
""")
}
var members = publicMembers
if (members.any()) {
if (alias == null) {
println()
generateGetters(AccessMode.INSTANCE, members)
}
if (hasMutableMembers()) {
println()
generateSetters(AccessMode.INSTANCE, settableMembers)
if (settableMembers.singleOrNull() == null && !containsUnion) {
val javadoc = "Initializes this struct with the specified values."
if (generateAlternativeMultiSetter(settableMembers))
generateMultiSetter(javadoc, settableMembers, Struct::generateAlternativeMultiSetterParameters, Struct::generateAlternativeMultiSetterSetters, MultiSetterMode.ALTER)
else
generateMultiSetter(javadoc, settableMembers, Struct::generateMultiSetterParameters, Struct::generateMultiSetterSetters)
}
print("""
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public $className set($className src) {
memCopy(src.$ADDRESS, $ADDRESS, SIZEOF);
return this;
}
""")
}
}
print("""
// -----------------------------------
""")
// Factory constructors
if (mallocable) {
print("""
/** Returns a new {@code $className} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static $className malloc() {
return wrap($className.class, nmemAllocChecked(SIZEOF));
}
/** Returns a new {@code $className} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static $className calloc() {
return wrap($className.class, nmemCallocChecked(1, SIZEOF));
}
/** Returns a new {@code $className} instance allocated with {@link BufferUtils}. */
public static $className create() {
ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
return wrap($className.class, memAddress(container), container);
}
""")
}
print("""
/** Returns a new {@code $className} instance for the specified memory address. */
public static $className create(long address) {
return wrap($className.class, address);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static $className createSafe(long address) {
return address == NULL ? null : wrap($className.class, address);
}
""")
val subtypes = Generator.structChildren[module]?.get([email protected])
subtypes?.forEach {
print("""
/** Upcasts the specified {@code ${it.className}} instance to {@code $className}. */
public static $className create(${it.className} value) {
return wrap($className.class, value);
}
""")
}
if (parentStruct != null) {
print("""
/** Downcasts the specified {@code ${parentStruct.className}} instance to {@code $className}. */
public static $className create(${parentStruct.className} value) {
return wrap($className.class, value);
}
""")
}
if (generateBuffer) {
if (mallocable) {
print("""
/**
* Returns a new {@link $className.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static $className.Buffer malloc(int $BUFFER_CAPACITY_PARAM) {
return wrap(Buffer.class, nmemAllocChecked(__checkMalloc($BUFFER_CAPACITY_PARAM, SIZEOF)), $BUFFER_CAPACITY_PARAM);
}
/**
* Returns a new {@link $className.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static $className.Buffer calloc(int $BUFFER_CAPACITY_PARAM) {
return wrap(Buffer.class, nmemCallocChecked($BUFFER_CAPACITY_PARAM, SIZEOF), $BUFFER_CAPACITY_PARAM);
}
/**
* Returns a new {@link $className.Buffer} instance allocated with {@link BufferUtils}.
*
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static $className.Buffer create(int $BUFFER_CAPACITY_PARAM) {
ByteBuffer container = __create($BUFFER_CAPACITY_PARAM, SIZEOF);
return wrap(Buffer.class, memAddress(container), $BUFFER_CAPACITY_PARAM, container);
}
""")
}
print("""
/**
* Create a {@link $className.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static $className.Buffer create(long address, int $BUFFER_CAPACITY_PARAM) {
return wrap(Buffer.class, address, $BUFFER_CAPACITY_PARAM);
}
/** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static $className.Buffer createSafe(long address, int $BUFFER_CAPACITY_PARAM) {
return address == NULL ? null : wrap(Buffer.class, address, $BUFFER_CAPACITY_PARAM);
}
""")
subtypes?.forEach {
print("""
/** Upcasts the specified {@code ${it.className}.Buffer} instance to {@code $className.Buffer}. */
public static $className.Buffer create(${it.className}.Buffer value) {
return wrap(Buffer.class, value);
}
""")
}
if (parentStruct != null) {
print("""
/** Downcasts the specified {@code ${parentStruct.className}.Buffer} instance to {@code $className.Buffer}. */
public static $className.Buffer create(${parentStruct.className}.Buffer value) {
return wrap(Buffer.class, value);
}
""")
}
}
if (mallocable) {
if (STRUCTS_323.contains("$packageName.$className")) {
print("""
// -----------------------------------
/** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
@Deprecated public static $className mallocStack() { return malloc(stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
@Deprecated public static $className callocStack() { return calloc(stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
@Deprecated public static $className mallocStack(MemoryStack stack) { return malloc(stack); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
@Deprecated public static $className callocStack(MemoryStack stack) { return calloc(stack); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */""")
if (generateBuffer) {
print("""
@Deprecated public static $className.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
@Deprecated public static $className.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */
@Deprecated public static $className.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
@Deprecated public static $className.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); }""")
}
println()
}
print("""
/**
* Returns a new {@code $className} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static $className malloc(MemoryStack stack) {
return wrap($className.class, stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@code $className} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static $className calloc(MemoryStack stack) {
return wrap($className.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
""")
if (generateBuffer) {
print("""
/**
* Returns a new {@link $className.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static $className.Buffer malloc(int $BUFFER_CAPACITY_PARAM, MemoryStack stack) {
return wrap(Buffer.class, stack.nmalloc(ALIGNOF, $BUFFER_CAPACITY_PARAM * SIZEOF), $BUFFER_CAPACITY_PARAM);
}
/**
* Returns a new {@link $className.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static $className.Buffer calloc(int $BUFFER_CAPACITY_PARAM, MemoryStack stack) {
return wrap(Buffer.class, stack.ncalloc(ALIGNOF, $BUFFER_CAPACITY_PARAM, SIZEOF), $BUFFER_CAPACITY_PARAM);
}
""")
}
}
if (alias == null) {
print("""
// -----------------------------------
""")
members = visibleMembers
if (members.any()) {
println()
generateStaticGetters(members)
if (hasMutableMembers(visibleMembers)) {
println()
generateStaticSetters(mutableMembers(visibleMembers))
if (Module.CHECKS && validations.any()) {
println(
"""
/**
* Validates pointer members that should not be {@code NULL}.
*
* @param $STRUCT the struct to validate
*/
public static void validate(long $STRUCT) {
${validations.joinToString("\n")}
}""")
}
}
}
}
printCustomMethods(customMethods, static = false)
if (generateBuffer) {
println("\n$t// -----------------------------------")
print("""
/** An array of {@link $className} structs. */
public static class Buffer extends """)
print(if (alias == null)
"StructBuffer<$className, Buffer>${if (mallocable) " implements NativeResource" else ""}"
else
"${alias.className}.Buffer"
)
print(""" {
private static final $className ELEMENT_FACTORY = $className.create(-1L);
/**
* Creates a new {@code $className.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link $className#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/""")
print(if (alias == null)
"""
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}"""
else
"""
public Buffer(ByteBuffer container) {
super(container);
}""")
print("""
public Buffer(long address, int cap) {
super(address, null, -1, 0, cap, cap);
}
Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected $className getElementFactory() {
return ELEMENT_FACTORY;
}
""")
members = publicMembers
if (members.any()) {
if (alias == null) {
println()
generateGetters(AccessMode.FLYWEIGHT, members)
}
if (hasMutableMembers()) {
println()
generateSetters(AccessMode.FLYWEIGHT, settableMembers)
}
}
printCustomMethods(customMethodsBuffer, static = false, indent = "$t$t")
print("""
}
""")
}
// Recursively output inner classes for array-of-anonymous-nested-struct members.
[email protected]
.filter { it is StructMemberArray && it.nativeType is StructType && it.nativeType.name === ANONYMOUS }
.forEach { member ->
(member.nativeType as StructType).definition.apply {
val writer = StringWriter(4 * 1024)
PrintWriter(writer).use {
it.generateJava(nested = true, level = level + 1)
}
println(writer.toString().replace("\n(?!$)".toRegex(), "\n "))
}
}
print("""
}""")
}
private fun PrintWriter.generateOffsetFields(
members: Sequence<StructMember>,
indentation: String = "$t$t",
parentField: String = "",
moreOverride: Boolean = false
) {
members.forEachWithMore(moreOverride) { member, more ->
if (member.name === ANONYMOUS && member.isNestedStruct) {
generateOffsetFields(member.nestedMembers, indentation, parentField, more) // recursion
} else {
if (more)
println(",")
val field = member.offsetField(parentField)
print("$indentation$field")
// Output nested field offsets
if (member.isNestedStructDefinition)
generateOffsetFields(member.nestedMembers, "$indentation$t", field, true) // recursion
}
}
}
private fun getMemberCount(members: List<StructMember>): Int {
var count = members.count { it.bits == -1 }
for (member in members.asSequence().filter { it.isNestedStructDefinition })
count += getMemberCount((member.nativeType as StructType).definition.members) // recursion
return count
}
private fun PrintWriter.generateOffsetInit(
nativeLayout: Boolean,
members: List<StructMember>,
indentation: String = "$t$t",
parentField: String = "",
offset: Int = 0
): Int {
var index = offset
members.forEach {
if (it.name === ANONYMOUS && it.isNestedStruct) {
index = generateOffsetInit(nativeLayout, (it.nativeType as StructType).definition.members, indentation, parentField, index + 1) // recursion
} else if (it is StructMemberPadding) {
index++
} else if (it.bits == -1) {
val field = it.offsetField(parentField)
println("$indentation$field = ${if (nativeLayout) "offsets.get" else "layout.offsetof"}(${index++});")
// Output nested fields
if (it.isNestedStructDefinition)
index = generateOffsetInit(nativeLayout, (it.nativeType as StructType).definition.members, "$indentation$t", field, index) // recursion
}
}
return index
}
private fun PrintWriter.generateLayout(
struct: Struct,
indentation: String = "$t$t",
parentField: String = ""
) {
println("__${if (struct.union) "union" else "struct"}(")
if (pack != null || alignas != null) {
println("$indentation$t${pack ?: "DEFAULT_PACK_ALIGNMENT"}, ${alignas ?: "DEFAULT_ALIGN_AS"},")
}
struct.members
.filter { it.bits == -1 }
.forEachWithMore { it, more ->
val field = it.offsetField(parentField)
if (more)
println(",")
if (it is StructMemberPadding) {
val bytesPerElement = (it.arrayType.elementType as PrimitiveType).mapping.bytesExpression
print("$indentation${t}__padding(${if (bytesPerElement == "1") it.size else "${it.size}, $bytesPerElement"}, ${it.condition ?: "true"})")
} else if (it.isNestedStructDefinition) {
print("$indentation$t")
generateLayout((it.nativeType as StructType).definition, "$indentation$t", field)
} else {
val size: String
val alignment: String
if (it.nativeType is StructType) {
size = "${it.nativeType.javaMethodType}.SIZEOF"
alignment = "${it.nativeType.javaMethodType}.ALIGNOF${if (it.nativeType.definition.alignas != null) ", true" else ""}"
} else {
size = if (it.nativeType.isPointer)
"POINTER_SIZE"
else
(it.nativeType.mapping as PrimitiveMapping).bytesExpression
alignment = size
}
if (it is StructMemberArray)
print("$indentation${t}__array($size${if (size != alignment) ", $alignment" else ""}, ${it.size})")
else
print("$indentation${t}__member($size${if (size != alignment) ", $alignment" else ""})")
}
}
print("\n$indentation)")
}
private fun PrintWriter.generateMultiSetter(
javaDoc: String,
members: Sequence<StructMember>,
generateParameters: (Struct, PrintWriter, Sequence<StructMember>, String, MultiSetterMode, Boolean) -> Unit,
generateSetters: (Struct, PrintWriter, Sequence<StructMember>, String, MultiSetterMode) -> Unit,
mode: MultiSetterMode = MultiSetterMode.NORMAL
) {
print("""
/** $javaDoc */""")
if (alias != null) {
print("""
@Override""")
}
print("""
public $className set(
""")
generateParameters(this@Struct, this, members, "", mode, false)
println("""
) {""")
generateSetters(this@Struct, this, members, "", mode)
print("""
return this;
}
""")
}
private fun generateMultiSetterParameters(writer: PrintWriter, members: Sequence<StructMember>, parentMember: String, mode: MultiSetterMode, more: Boolean) {
writer.apply {
members.forEachWithMore(more) { it, more ->
val method = it.field(parentMember)
if (it.isNestedStructDefinition) {
generateMultiSetterParameters(writer, it.nestedMembers, method, mode, more) // recursion
return@forEachWithMore
}
if (more)
println(",")
print("$t$t")
val param = it.field(parentMember)
print("${it.nativeType.javaMethodType} $param")
}
}
}
private fun generateMultiSetterSetters(writer: PrintWriter, members: Sequence<StructMember>, parentMember: String, mode: MultiSetterMode) {
writer.apply {
members.forEach {
val field = it.field(parentMember)
if (it.isNestedStructDefinition)
generateMultiSetterSetters(writer, it.nestedMembers, field, mode) // recursion
else
println("$t$t$field($field);")
}
}
}
private fun generateAlternativeMultiSetter(members: Sequence<StructMember>): Boolean =
members.any {
if (it.isNestedStructDefinition)
generateAlternativeMultiSetter(it.nestedMembers) // recursion
else
it is StructMemberArray || it.nativeType.isPointerData
}
private fun generateAlternativeMultiSetterParameters(writer: PrintWriter, members: Sequence<StructMember>, parentMember: String, mode: MultiSetterMode, more: Boolean) {
writer.apply {
members.forEachWithMore(more) { it, more ->
val method = it.field(parentMember)
if (it.isNestedStructDefinition) {
generateAlternativeMultiSetterParameters(writer, it.nestedMembers, method, mode, more) // recursion
return@forEachWithMore
}
if (more)
println(",")
print(
"$t$t${it.nullable(
if (it is StructMemberArray) {
if (it.nativeType is CharType) {
"ByteBuffer"
} else if (it.nativeType is StructType)
"${it.nativeType.javaMethodType}.Buffer"
else
it.primitiveMapping.toPointer.javaMethodName
} else if (it.nativeType is PointerType<*> && it.nativeType.elementType is StructType) {
val structType = it.nativeType.javaMethodType
if (it.isStructBuffer)
"$structType.Buffer"
else
structType
} else
it.nativeType.javaMethodType,
if (it is StructMemberArray) it.arrayType else it.nativeType
)} ${it.field(parentMember)}"
)
}
}
}
private fun generateAlternativeMultiSetterSetters(writer: PrintWriter, members: Sequence<StructMember>, parentMember: String, mode: MultiSetterMode) {
writer.apply {
members.forEach {
val field = it.field(parentMember)
if (it.isNestedStructDefinition)
generateAlternativeMultiSetterSetters(writer, it.nestedMembers, field, mode) // recursion
else
println("$t$t$field($field);")
}
}
}
private fun getFieldOffset(
m: StructMember,
parentStruct: Struct?,
parentField: String
) = if (parentStruct == null || parentField.isEmpty())
"$className.${m.offsetField}"
else if (parentStruct.className === ANONYMOUS)
"${parentField}_${m.offsetField}"
else
throw IllegalStateException()
private val StructMember.pointerValue get() = if (!Module.CHECKS || has(nullable)) "value" else "check(value)"
private val StructMember.isNullable
get() = has(nullable) ||
getReferenceMember<AutoSizeMember>(name)?.get<AutoSizeMember>()?.optional ?: false ||
(this is StructMemberArray && this.validSize < this.size)
private val StructMember.addressValue get() = if (isNullable) "memAddressSafe(value)" else "value.address()"
private val StructMember.memAddressValue get() = if (isNullable) "memAddressSafe(value)" else "memAddress(value)"
private val StructMember.autoSize get() = "n$name($STRUCT)"
.let {
val type = this.nativeType as IntegerType
if (!type.unsigned)
it
else {
val mapping = type.mapping
when (mapping.bytes) {
1 -> "Byte.toUnsignedInt($it)"
2 -> "Short.toUnsignedInt($it)"
else -> it
}
}
}
.let {
val factor = if (has<AutoSizeMember>()) get<AutoSizeMember>().factor else null
if (factor != null)
"(${factor.scale(it)})"
else
it
}
.let { if (4 < (nativeType.mapping as PrimitiveMapping).bytes && !it.startsWith('(')) "(int)$it" else it }
private fun PrintWriter.setRemaining(m: StructMember, offset: Int = 0, prefix: String = " ", suffix: String = "") {
// do not do this if the AutoSize parameter auto-sizes multiple members
val capacity = members.firstOrNull {
it.has<AutoSizeMember> { atLeastOne || (dependent.isEmpty() && reference == m.name) }
}
if (capacity != null) {
val autoSize = capacity.get<AutoSizeMember>()
val autoSizeExpression = "value.remaining()"
.let {
if (autoSize.factor != null)
"(${autoSize.factor.scaleInv(it)})"
else
it
}
.let { if ((capacity.nativeType.mapping as PrimitiveMapping).bytes < 4) "(${capacity.nativeType.javaMethodType})$it" else it }
.let { if (offset != 0) "$it - $offset" else it }
print(prefix)
print(if ((m has nullable || autoSize.optional) && m !is StructMemberArray) {
if (autoSize.atLeastOne || (m has nullable && autoSize.optional))
"if (value != null) { n${capacity.name}($STRUCT, $autoSizeExpression); }"
else
"n${capacity.name}($STRUCT, value == null ? 0 : $autoSizeExpression);"
} else
"n${capacity.name}($STRUCT, $autoSizeExpression);"
)
print(suffix)
}
}
private fun PrintWriter.generateStaticSetters(
members: Sequence<StructMember>,
parentStruct: Struct? = null,
parentMember: String = "",
parentField: String = ""
) {
members.forEach {
val setter = it.field(parentMember)
val field = getFieldOffset(it, parentStruct, parentField)
if (it.isNestedStruct) {
val nestedStruct = (it.nativeType as StructType).definition
val structType = nestedStruct.className
if (structType === ANONYMOUS)
generateStaticSetters(
it.nestedMembers, nestedStruct,
if (it.name === ANONYMOUS) parentMember else setter,
if (it.name === ANONYMOUS) parentField else field
)
else {
if (it.public)
println("$t/** Unsafe version of {@link #$setter($structType) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, $structType value) { memCopy(value.$ADDRESS, $STRUCT + $field, $structType.SIZEOF); }")
}
} else {
// Setter
if (it !is StructMemberArray && !it.nativeType.isPointerData) {
if (it.nativeType is WrappedPointerType) {
if (it.public)
println("$t/** Unsafe version of {@link #$setter(${it.nativeType.javaMethodType}) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, ${it.nullable(it.nativeType.javaMethodType)} value) { memPutAddress($STRUCT + $field, ${it.addressValue}); }")
} else {
val javaType = it.nativeType.nativeMethodType
if (it.public)
println(
if (it.has<AutoSizeMember>())
"$t/** Sets the specified value to the {@code ${it.name}} field of the specified {@code struct}. */"
else
"$t/** Unsafe version of {@link #$setter(${if (it.nativeType.mapping == PrimitiveMapping.BOOLEAN4) "boolean" else javaType}) $setter}. */"
)
if (it.setter != null) {
println("${t}public static void n$setter(long $STRUCT, $javaType value) { ${it.setter}; }")
} else if (it.bits != -1) {
println("${t}public static native void n$setter(long $STRUCT, $javaType value);")
} else {
print("${t}public static void n$setter(long $STRUCT, $javaType value) { ${getBufferMethod("put", it, javaType)}$STRUCT + $field, ")
print(
when {
javaType == "boolean"
-> "value ? (byte)1 : (byte)0"
it.nativeType.mapping === PointerMapping.OPAQUE_POINTER
-> it.pointerValue
else -> "value"
}
)
println("); }")
}
}
}
// Alternative setters
if (it is StructMemberArray) {
if (it.nativeType.dereference is StructType) {
val structType = it.nativeType.javaMethodType
if (it.nativeType is PointerType<*>) {
if (it.public)
println("$t/** Unsafe version of {@link #$setter(PointerBuffer) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, PointerBuffer value) {")
if (Module.CHECKS)
println("$t${t}if (CHECKS) { checkGT(value, ${it.size}); }")
println("$t${t}memCopy(memAddress(value), $STRUCT + $field, value.remaining() * POINTER_SIZE);")
setRemaining(it, prefix = "$t$t", suffix = "\n")
println("$t}")
val structTypeIndexed = "$structType${if (getReferenceMember<AutoSizeIndirect>(it.name) == null) "" else ".Buffer"}"
if (it.public)
println("$t/** Unsafe version of {@link #$setter(int, $structTypeIndexed) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, int index, ${it.nullable(structTypeIndexed)} value) {")
println("$t${t}memPutAddress($STRUCT + $field + check(index, ${it.size}) * POINTER_SIZE, ${it.addressValue});")
println("$t}")
} else {
if (it.public)
println("$t/** Unsafe version of {@link #$setter($structType.Buffer) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, $structType.Buffer value) {")
if (Module.CHECKS)
println("$t${t}if (CHECKS) { checkGT(value, ${it.size}); }")
println("$t${t}memCopy(value.$ADDRESS, $STRUCT + $field, value.remaining() * $structType.SIZEOF);")
setRemaining(it, prefix = "$t$t", suffix = "\n")
println("$t}")
if (it.public)
println("$t/** Unsafe version of {@link #$setter(int, $structType) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, int index, $structType value) {")
println("$t${t}memCopy(value.$ADDRESS, $STRUCT + $field + check(index, ${it.size}) * $structType.SIZEOF, $structType.SIZEOF);")
println("$t}")
}
} else if (it.nativeType is CharType) {
val mapping = it.nativeType.mapping as PrimitiveMapping
val byteSize = if (mapping.bytes == 1) it.size else "${it.size} * ${mapping.bytes}"
val nullTerminated = getReferenceMember<AutoSizeMember>(it.name) == null || it.has(NullTerminatedMember)
if (it.public)
println("$t/** Unsafe version of {@link #$setter(ByteBuffer) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, ByteBuffer value) {")
if (Module.CHECKS) {
println("$t${t}if (CHECKS) {")
if (nullTerminated) {
println("$t$t${t}checkNT${mapping.bytes}(value);")
}
println("$t$t${t}checkGT(value, $byteSize);")
println("$t$t}")
}
println("$t${t}memCopy(memAddress(value), $STRUCT + $field, value.remaining());")
setRemaining(it, if (nullTerminated) mapping.bytes else 0, prefix = "$t$t", suffix = "\n")
println("$t}")
} else {
val mapping = it.primitiveMapping
val bufferType = mapping.toPointer.javaMethodName
if (it.public)
println("$t/** Unsafe version of {@link #$setter($bufferType) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, $bufferType value) {")
if (Module.CHECKS)
println("$t${t}if (CHECKS) { checkGT(value, ${it.size}); }")
println("$t${t}memCopy(memAddress(value), $STRUCT + $field, value.remaining() * ${mapping.bytesExpression});")
setRemaining(it, prefix = "$t$t", suffix = "\n")
println("$t}")
val javaType = it.nativeType.nativeMethodType
if (it.public)
println("$t/** Unsafe version of {@link #$setter(int, $javaType) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, int index, $javaType value) {")
println("$t$t${getBufferMethod("put", it, javaType)}$STRUCT + $field + check(index, ${it.size}) * ${mapping.bytesExpression}, value);")
println("$t}")
}
} else if (it.nativeType is CharSequenceType) {
val mapping = it.nativeType.charMapping
val nullTerminated = getReferenceMember<AutoSizeMember>(it.name) == null || it.has(NullTerminatedMember)
if (it.public)
println("$t/** Unsafe version of {@link #$setter(ByteBuffer) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, ${it.nullable("ByteBuffer")} value) {")
if (Module.CHECKS && nullTerminated)
println("$t${t}if (CHECKS) { checkNT${mapping.bytes}${if (it.isNullable) "Safe" else ""}(value); }")
println("$t${t}memPutAddress($STRUCT + $field, ${it.memAddressValue});")
setRemaining(it, prefix = "$t$t", suffix = "\n")
println("$t}")
} else if (it.nativeType.isPointerData) {
val paramType = it.nativeType.javaMethodType
if (it.nativeType.dereference is StructType) {
if (it.isStructBuffer) {
if (it.public)
println("$t/** Unsafe version of {@link #$setter($paramType.Buffer) $setter}. */")
print("${t}public static void n$setter(long $STRUCT, ${it.nullable("$paramType.Buffer")} value) { memPutAddress($STRUCT + $field, ${it.addressValue});")
setRemaining(it)
println(" }")
} else {
if (it.public)
println("$t/** Unsafe version of {@link #$setter($paramType) $setter}. */")
println("${t}public static void n$setter(long $STRUCT, ${it.nullable(paramType)} value) { memPutAddress($STRUCT + $field, ${it.addressValue}); }")
}
} else {
if (it.public)
println("$t/** Unsafe version of {@link #$setter($paramType) $setter}. */")
print("${t}public static void n$setter(long $STRUCT, ${it.nullable(paramType)} value) { memPutAddress($STRUCT + $field, ${it.memAddressValue});")
setRemaining(it)
println(" }")
}
}
}
}
}
private fun StructMember.annotate(
type: String,
nativeType: DataType = if (this is StructMemberArray) this.arrayType else this.nativeType
) = nullable(nativeType.annotate(type), nativeType)
private fun StructMember.nullable(type: String, nativeType: DataType = this.nativeType) =
if (nativeType.isReference && isNullable && nativeType !is CArrayType<*>) {
"@Nullable $type"
} else {
type
}
private fun StructMember.construct(type: String) = if (nativeType.isReference && isNullable) {
"$type.createSafe"
} else {
"$type.create"
}
private fun StructMember.mem(type: String) = if (nativeType.isReference && isNullable && this !is StructMemberArray) {
"mem${type}Safe"
} else {
"mem$type"
}
private fun PrintWriter.generateSetters(
accessMode: AccessMode,
members: Sequence<StructMember>,
parentSetter: String = "",
parentMember: String = ""
) {
val n = if (accessMode === AccessMode.INSTANCE) "n" else "$className.n"
members.forEach {
val setter = it.field(parentSetter)
val member = it.fieldName(parentMember)
val indent = accessMode.indent
val overrides = alias != null /*
TODO: forward declarations have no members (see VkPhysicalDeviceBufferDeviceAddressFeaturesEXT)
&& alias.members.any { parentMember -> parentMember.name == it.name }
*/
val returnType = if (accessMode === AccessMode.INSTANCE)
className
else
"$className.Buffer"
if (it.isNestedStruct) {
val nestedStruct = (it.nativeType as StructType).definition
val structType = nestedStruct.className
if (structType === ANONYMOUS)
generateSetters(
accessMode,
it.nestedMembers,
if (it.name === ANONYMOUS) parentSetter else setter,
if (it.name === ANONYMOUS) parentMember else member
)
else {
printSetterJavadoc(accessMode, it, indent, "Copies the specified {@link $structType} to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate(structType)} value) { $n$setter($ADDRESS, value); return this; }")
if (nestedStruct.mutable) {
printSetterJavadoc(accessMode, it, indent, "Passes the #member field to the specified {@link java.util.function.Consumer Consumer}.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $className${if (accessMode === AccessMode.INSTANCE) "" else ".Buffer"} $setter(java.util.function.Consumer<$structType> consumer) { consumer.accept($setter()); return this; }")
}
}
} else {
// Setter
if (it !is StructMemberArray && !it.nativeType.isPointerData) {
printSetterJavadoc(accessMode, it, indent, "Sets the specified value to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate(it.nativeType.javaMethodType)} value) { $n$setter($ADDRESS, value${if (it.nativeType.mapping === PrimitiveMapping.BOOLEAN4) " ? 1 : 0" else ""}); return this; }")
}
// Alternative setters
if (it is StructMemberArray) {
if (it.nativeType.dereference is StructType) {
val nestedStruct: Struct
val structType = it.nativeType.javaMethodType
val retType = "$structType${if (getReferenceMember<AutoSizeIndirect>(it.name) == null) "" else ".Buffer"}"
if (it.nativeType is PointerType<*>) {
nestedStruct = (it.nativeType.dereference as StructType).definition
printSetterJavadoc(accessMode, it, indent, "Copies the specified {@link PointerBuffer} to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate("PointerBuffer")} value) { $n$setter($ADDRESS, value); return this; }")
printSetterJavadoc(accessMode, it, indent, "Copies the address of the specified {@link $retType} at the specified index of the #member field.", setter)
} else {
nestedStruct = (it.nativeType as StructType).definition
printSetterJavadoc(accessMode, it, indent, "Copies the specified {@link $structType.Buffer} to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate("$structType.Buffer")} value) { $n$setter($ADDRESS, value); return this; }")
printSetterJavadoc(accessMode, it, indent, "Copies the specified {@link $structType} at the specified index of the #member field.", setter)
}
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(int index, ${it.annotate(retType, it.nativeType)} value) { $n$setter($ADDRESS, index, value); return this; }")
if (nestedStruct.mutable) {
if (it.nativeType !is PointerType<*>) {
printSetterJavadoc(accessMode, it, indent, "Passes the #member field to the specified {@link java.util.function.Consumer Consumer}.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $className${if (accessMode === AccessMode.INSTANCE) "" else ".Buffer"} $setter(java.util.function.Consumer<$structType.Buffer> consumer) { consumer.accept($setter()); return this; }")
}
printSetterJavadoc(accessMode, it, indent, "Passes the element at {@code index} of the #member field to the specified {@link java.util.function.Consumer Consumer}.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $className${if (accessMode === AccessMode.INSTANCE) "" else ".Buffer"} $setter(int index, java.util.function.Consumer<$retType> consumer) { consumer.accept($setter(index)); return this; }")
}
} else if (it.nativeType is CharType) {
printSetterJavadoc(accessMode, it, indent, "Copies the specified encoded string to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate("ByteBuffer")} value) { $n$setter($ADDRESS, value); return this; }")
} else {
val bufferType = it.primitiveMapping.toPointer.javaMethodName
printSetterJavadoc(accessMode, it, indent, "Copies the specified {@link $bufferType} to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate(bufferType)} value) { $n$setter($ADDRESS, value); return this; }")
printSetterJavadoc(accessMode, it, indent, "Sets the specified value at the specified index of the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(int index, ${it.annotate(it.nativeType.javaMethodType, it.nativeType)} value) { $n$setter($ADDRESS, index, value); return this; }")
}
} else if (it.nativeType is CharSequenceType) {
printSetterJavadoc(accessMode, it, indent, "Sets the address of the specified encoded string to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate("ByteBuffer")} value) { $n$setter($ADDRESS, value); return this; }")
} else if (it.nativeType.isPointerData) {
val pointerType = it.nativeType.javaMethodType
if ((it.nativeType as PointerType<*>).elementType is StructType && it.isStructBuffer) {
printSetterJavadoc(accessMode, it, indent, "Sets the address of the specified {@link $pointerType.Buffer} to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate("$pointerType.Buffer")} value) { $n$setter($ADDRESS, value); return this; }")
} else {
printSetterJavadoc(accessMode, it, indent, "Sets the address of the specified {@link $pointerType} to the #member field.", setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.annotate(pointerType)} value) { $n$setter($ADDRESS, value); return this; }")
}
}
if (it.has<Expression>()) {
val javadoc: String
val expression = it.get<Expression>().value.let { expression ->
if (expression.startsWith("#")) {
if (expression.endsWith(')')) {
throw NotImplementedError()
}
val token = Generator.tokens[module]!![expression.substring(1)]!!
javadoc = processDocumentation("Sets the $expression value to the \\#member field.")
token
} else {
javadoc = "Sets the default value to the #member field."
expression
}
}
printSetterJavadoc(accessMode, it, indent, javadoc, setter)
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter\$Default() { return $setter(${expression.replace('#', '.')}); }")
}
if (it.has<PointerSetter>()) {
val pointerSetter = it.get<PointerSetter>()
pointerSetter.types.forEach { type ->
val hasOverrideAnnotation = overrides && alias != null && alias[member].let { member ->
member.has<PointerSetter>() && member.get<PointerSetter>().types.contains(type)
}
if (pointerSetter.prepend) {
printSetterJavadoc(accessMode, it, indent, "Prepends the specified {@link $type} value to the {@code $setter} chain.", setter)
if (hasOverrideAnnotation) println("$indent@Override")
println("${indent}public $returnType $setter($type value) { return this.$setter(value.${pointerSetter.targetSetter ?: setter}(this.$setter()).address()); }")
} else {
printSetterJavadoc(accessMode, it, indent, "Sets the address of the specified {@link $type} value to the #member field.", setter)
if (hasOverrideAnnotation) println("$indent@Override")
println("${indent}public $returnType $setter($type value) { return $setter(value.address()); }")
}
}
}
}
}
}
private fun PrintWriter.generateStaticGetters(
members: Sequence<StructMember>,
parentStruct: Struct? = null,
parentGetter: String = "",
parentField: String = ""
) {
members.forEach {
val getter = it.field(parentGetter)
val field = getFieldOffset(it, parentStruct, parentField)
if (it.isNestedStruct) {
val nestedStruct = (it.nativeType as StructType).definition
val structType = nestedStruct.className
if (structType === ANONYMOUS)
generateStaticGetters(
it.nestedMembers, nestedStruct,
if (it.name === ANONYMOUS) parentGetter else getter,
if (it.name === ANONYMOUS) parentField else field
)
else {
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
println("${t}public static $structType n$getter(long $STRUCT) { return $structType.create($STRUCT + $field); }")
}
} else {
// Getter
if (it !is StructMemberArray && !it.nativeType.isPointerData) {
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
if (it.nativeType is FunctionType) {
println("$t${it.nullable("public")} static ${it.nativeType.className} n$getter(long $STRUCT) { return ${it.construct(it.nativeType.className)}(memGetAddress($STRUCT + $field)); }")
} else if (it.getter != null) {
println("${t}public static ${it.nativeType.nativeMethodType} n$getter(long $STRUCT) { return ${it.getter}; }")
} else if (it.bits != -1) {
println("${t}public static native ${it.nativeType.nativeMethodType} n$getter(long $STRUCT);")
} else {
val javaType = it.nativeType.nativeMethodType
print("${t}public static $javaType n$getter(long $STRUCT) { return ${getBufferMethod("get", it, javaType)}$STRUCT + $field)")
if (it.nativeType.mapping === PrimitiveMapping.BOOLEAN)
print(" != 0")
println("; }")
}
}
// Alternative getters
if (it is StructMemberArray) {
if (it.nativeType.dereference is StructType) {
val nestedStruct = it.nativeType.javaMethodType
val capacity = getAutoSizeExpression(it.name) ?: it.size
if (it.nativeType is PointerType<*>) {
val autoSizeIndirect = getReferenceMember<AutoSizeIndirect>(it.name)
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
println("${t}public static PointerBuffer n$getter(long $STRUCT) { return ${it.mem("PointerBuffer")}($STRUCT + $field, $capacity); }")
if (it.public)
println("$t/** Unsafe version of {@link #$getter(int) $getter}. */")
println("$t${it.nullable("public")} static $nestedStruct${if (autoSizeIndirect == null) "" else ".Buffer"} n$getter(long $STRUCT, int index) {")
println("$t${t}return ${it.construct(nestedStruct)}(memGetAddress($STRUCT + $field + check(index, $capacity) * POINTER_SIZE)${
if (autoSizeIndirect == null) "" else ", n${autoSizeIndirect.name}($STRUCT)"
});")
println("$t}")
} else {
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
println("${t}public static $nestedStruct.Buffer n$getter(long $STRUCT) { return ${it.construct(nestedStruct)}($STRUCT + $field, $capacity); }")
if (it.public)
println("$t/** Unsafe version of {@link #$getter(int) $getter}. */")
println("$t${it.nullable("public")} static $nestedStruct n$getter(long $STRUCT, int index) {")
println("$t${t}return ${it.construct(nestedStruct)}($STRUCT + $field + check(index, $capacity) * $nestedStruct.SIZEOF);")
println("$t}")
}
} else if (it.nativeType is CharType) {
val mapping = it.nativeType.mapping
val capacity = getAutoSizeExpression(it.name) ?: it.getCheckExpression()
val byteSize = capacity ?: if (mapping.bytes == 1) it.size else "${it.size} * ${mapping.bytes}"
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
println("${t}public static ByteBuffer n$getter(long $STRUCT) { return memByteBuffer($STRUCT + $field, $byteSize); }")
if (it.public)
println("$t/** Unsafe version of {@link #${getter}String}. */")
println("${t}public static String n${getter}String(long $STRUCT) { return mem${mapping.charset}(${if (capacity != null) "n$getter($STRUCT)" else "$STRUCT + $field"}); }")
} else {
val mapping = it.primitiveMapping
val bufferType = mapping.toPointer.javaMethodName
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
println("${t}public static $bufferType n$getter(long $STRUCT) { return ${it.mem(bufferType)}($STRUCT + $field, ${getAutoSizeExpression(it.name) ?: it.size}); }")
val javaType = it.nativeType.nativeMethodType
if (it.public)
println("$t/** Unsafe version of {@link #$getter(int) $getter}. */")
println("${t}public static $javaType n$getter(long $STRUCT, int index) {")
print("$t${t}return ${getBufferMethod("get", it, javaType)}$STRUCT + $field + check(index, ${it.size}) * ${mapping.bytesExpression})")
if (it.nativeType.mapping === PrimitiveMapping.BOOLEAN)
print(" != 0")
println(";\n$t}")
}
} else if (it.nativeType is CharSequenceType) {
val mapping = it.nativeType.charMapping
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
println("$t${it.nullable("public")} static ByteBuffer n$getter(long $STRUCT) { return ${it.mem("ByteBufferNT${mapping.bytes}")}(memGetAddress($STRUCT + $field)); }")
if (it.public)
println("$t/** Unsafe version of {@link #${getter}String}. */")
println("$t${it.nullable("public")} static String n${getter}String(long $STRUCT) { return ${it.mem(mapping.charset)}(memGetAddress($STRUCT + $field)); }")
} else if (it.nativeType.isPointerData) {
val returnType = it.nativeType.javaMethodType
if (it.nativeType.dereference is StructType) {
if (it.public)
println("$t/** Unsafe version of {@link #$getter}. */")
println(if (it.isStructBuffer) {
val capacity = getAutoSizeExpression(it.name) ?: it.getCheckExpression()
if (capacity == null)
"$t${it.nullable("public")} static $returnType.Buffer n$getter(long $STRUCT, int $BUFFER_CAPACITY_PARAM) { return ${it.construct(returnType)}(memGetAddress($STRUCT + $field), $BUFFER_CAPACITY_PARAM); }"
else
"$t${it.nullable("public")} static $returnType.Buffer n$getter(long $STRUCT) { return ${it.construct(returnType)}(memGetAddress($STRUCT + $field), $capacity); }"
} else
"$t${it.nullable("public")} static $returnType n$getter(long $STRUCT) { return ${it.construct(returnType)}(memGetAddress($STRUCT + $field)); }"
)
} else {
val capacity = getAutoSizeExpression(it.name) ?: it.getCheckExpression()
if (capacity == null) {
if (it.public)
println("$t/** Unsafe version of {@link #$getter(int) $getter}. */")
println("$t${it.nullable("public")} static $returnType n$getter(long $STRUCT, int $BUFFER_CAPACITY_PARAM) { return ${it.mem(returnType)}(memGetAddress($STRUCT + $field), $BUFFER_CAPACITY_PARAM); }")
} else {
if (it.public)
println("$t/** Unsafe version of {@link #$getter() $getter}. */")
println("$t${it.nullable("public")} static $returnType n$getter(long $STRUCT) { return ${it.mem(returnType)}(memGetAddress($STRUCT + $field), $capacity); }")
}
}
}
}
}
}
private fun PrintWriter.generateGetterAnnotations(indent: String, member: StructMember, type: String, nativeType: NativeType = member.nativeType) {
if (nativeType.isReference && member.isNullable) {
println("$indent@Nullable")
}
nativeType.annotation(type).let {
if (it != null)
println("$indent$it")
}
}
private fun PrintWriter.generateGetters(
accessMode: AccessMode,
members: Sequence<StructMember>,
parentGetter: String = "",
parentMember: String = ""
) {
val n = if (accessMode === AccessMode.INSTANCE) "n" else "$className.n"
members.forEach {
val getter = it.field(parentGetter)
val member = it.fieldName(parentMember)
val indent = accessMode.indent
if (it.isNestedStruct) {
val structType = it.nativeType.javaMethodType
if (structType === ANONYMOUS)
generateGetters(
accessMode,
it.nestedMembers,
if (it.name === ANONYMOUS) parentGetter else getter,
if (it.name === ANONYMOUS) parentMember else member
)
else {
printGetterJavadoc(accessMode, it, indent, "@return a {@link $structType} view of the #member field.", getter, member)
generateGetterAnnotations(indent, it, structType)
println("${indent}public $structType $getter() { return $n$getter($ADDRESS); }")
}
} else {
// Getter
if (it !is StructMemberArray && !it.nativeType.isPointerData) {
val returnType = when (it.nativeType) {
is FunctionType -> it.nativeType.className
is WrappedPointerType -> "long"
else -> it.nativeType.javaMethodType
}
printGetterJavadoc(accessMode, it, indent, "@return the value of the #member field.", getter, member)
generateGetterAnnotations(indent, it, returnType)
println("${indent}public $returnType $getter() { return $n$getter($ADDRESS)${if (it.nativeType.mapping === PrimitiveMapping.BOOLEAN4) " != 0" else ""}; }")
}
// Alternative getters
if (it is StructMemberArray) {
if (it.nativeType.dereference is StructType) {
val structType = it.nativeType.javaMethodType
if (it.nativeType is PointerType<*>) {
printGetterJavadoc(accessMode, it, indent, "@return a {@link PointerBuffer} view of the #member field.", getter, member)
generateGetterAnnotations(indent, it, "PointerBuffer", it.arrayType)
println("${indent}public PointerBuffer $getter() { return $n$getter($ADDRESS); }")
val retType = "$structType${if (getReferenceMember<AutoSizeIndirect>(it.name) == null) "" else ".Buffer"}"
printGetterJavadoc(accessMode, it, indent, "@return a {@link $structType} view of the pointer at the specified index of the #member field.", getter, member)
generateGetterAnnotations(indent, it, retType)
println("${indent}public $retType $getter(int index) { return $n$getter($ADDRESS, index); }")
} else {
printGetterJavadoc(accessMode, it, indent, "@return a {@link $structType}.Buffer view of the #member field.", getter, member)
generateGetterAnnotations(indent, it, "$structType.Buffer", it.arrayType)
println("${indent}public $structType.Buffer $getter() { return $n$getter($ADDRESS); }")
printGetterJavadoc(accessMode, it, indent, "@return a {@link $structType} view of the struct at the specified index of the #member field.", getter, member)
generateGetterAnnotations(indent, it, structType)
println("${indent}public $structType $getter(int index) { return $n$getter($ADDRESS, index); }")
}
} else if (it.nativeType is CharType) {
printGetterJavadoc(accessMode, it, indent, "@return a {@link ByteBuffer} view of the #member field.", getter, member)
generateGetterAnnotations(indent, it, "ByteBuffer", it.arrayType)
println("${indent}public ByteBuffer $getter() { return $n$getter($ADDRESS); }")
printGetterJavadoc(accessMode, it, indent, "@return the null-terminated string stored in the #member field.", getter, member)
generateGetterAnnotations(indent, it, "String", it.arrayType)
println("${indent}public String ${getter}String() { return $n${getter}String($ADDRESS); }")
} else {
val bufferType = it.primitiveMapping.toPointer.javaMethodName
printGetterJavadoc(accessMode, it, indent, "@return a {@link $bufferType} view of the #member field.", getter, member)
generateGetterAnnotations(indent, it, bufferType, it.arrayType)
println("${indent}public $bufferType $getter() { return $n$getter($ADDRESS); }")
printGetterJavadoc(accessMode, it, indent, "@return the value at the specified index of the #member field.", getter, member)
generateGetterAnnotations(indent, it, it.nativeType.nativeMethodType)
println("${indent}public ${it.nativeType.nativeMethodType} $getter(int index) { return $n$getter($ADDRESS, index); }")
}
} else if (it.nativeType is CharSequenceType) {
printGetterJavadoc(accessMode, it, indent, "@return a {@link ByteBuffer} view of the null-terminated string pointed to by the #member field.", getter, member)
generateGetterAnnotations(indent, it, "ByteBuffer")
println("${indent}public ByteBuffer $getter() { return $n$getter($ADDRESS); }")
printGetterJavadoc(accessMode, it, indent, "@return the null-terminated string pointed to by the #member field.", getter, member)
generateGetterAnnotations(indent, it, "String")
println("${indent}public String ${getter}String() { return $n${getter}String($ADDRESS); }")
} else if (it.nativeType.isPointerData) {
val returnType = it.nativeType.javaMethodType
if (it.nativeType.dereference is StructType) {
if (it.isStructBuffer) {
if (getReferenceMember<AutoSizeMember>(it.name) == null && !it.has<Check>()) {
printGetterJavadoc(accessMode, it, indent, "@return a {@link $returnType.Buffer} view of the struct array pointed to by the #member field.", getter, member, BUFFER_CAPACITY)
generateGetterAnnotations(indent, it, "$returnType.Buffer")
println("${indent}public $returnType.Buffer $getter(int $BUFFER_CAPACITY_PARAM) { return $n$getter($ADDRESS, $BUFFER_CAPACITY_PARAM); }")
} else {
printGetterJavadoc(accessMode, it, indent, "@return a {@link $returnType.Buffer} view of the struct array pointed to by the #member field.", getter, member)
generateGetterAnnotations(indent, it, "$returnType.Buffer")
println("${indent}public $returnType.Buffer $getter() { return $n$getter($ADDRESS); }")
}
} else {
printGetterJavadoc(accessMode, it, indent, "@return a {@link $returnType} view of the struct pointed to by the #member field.", getter, member)
generateGetterAnnotations(indent, it, returnType)
println("${indent}public $returnType $getter() { return $n$getter($ADDRESS); }")
}
} else {
if (getReferenceMember<AutoSizeMember>(it.name) == null && !it.has<Check>()) {
printGetterJavadoc(accessMode, it, indent, "@return a {@link $returnType} view of the data pointed to by the #member field.", getter, member, BUFFER_CAPACITY)
generateGetterAnnotations(indent, it, returnType)
println("${indent}public $returnType $getter(int $BUFFER_CAPACITY_PARAM) { return $n$getter($ADDRESS, $BUFFER_CAPACITY_PARAM); }")
} else {
printGetterJavadoc(accessMode, it, indent, "@return a {@link $returnType} view of the data pointed to by the #member field.", getter, member)
generateGetterAnnotations(indent, it, returnType)
println("${indent}public $returnType $getter() { return $n$getter($ADDRESS); }")
}
}
}
}
}
}
private fun getBufferMethod(type: String, member: StructMember, javaType: String) = if (member.nativeType.isPointer)
"mem${type.upperCaseFirst}Address("
else if (member.nativeType.mapping === PrimitiveMapping.CLONG)
"mem${type.upperCaseFirst}CLong("
else
"UNSAFE.$type${
bufferMethodMap[javaType] ?: throw UnsupportedOperationException("Unsupported struct member java type: $className.${member.name} ($javaType)")
}(null, "
override val skipNative get() = !nativeLayout && members.isNotEmpty() && members.none { it.bits != -1 && it.getter == null }
override fun PrintWriter.generateNative() {
print(HEADER)
nativeImport("<stddef.h>")
nativeDirective(
"""#ifdef LWJGL_WINDOWS
#define alignof __alignof
#else
#include <stdalign.h>
#endif""")
preamble.printNative(this)
println("""
EXTERN_C_ENTER
JNIEXPORT jint JNICALL Java_${nativeFileNameJNI}_offsets(JNIEnv *$JNIENV, jclass clazz, jlong bufferAddress) {
jint *buffer = (jint *)(uintptr_t)bufferAddress;
UNUSED_PARAMS($JNIENV, clazz)
""")
if (virtual) {
// NOTE: Assumes a plain struct definition (no nested structs, no unions)
println("${t}typedef struct $nativeName {")
for (m in members) {
print("$t$t${m.nativeType.name}")
println(" ${m.name};")
}
println("$t} $nativeName;\n")
}
var index = 0
if (members.isNotEmpty()) {
index = generateNativeMembers(members)
if (index != 0) {
println()
}
}
print(
""" buffer[$index] = alignof($nativeName);
return sizeof($nativeName);
}""")
generateNativeGetters(members)
generateNativeSetters(mutableMembers())
println("""
EXTERN_C_EXIT""")
}
private fun PrintWriter.generateNativeMembers(members: List<StructMember>, offset: Int = 0, prefix: String = ""): Int {
var index = offset
members.forEach {
if (it.name === ANONYMOUS && it.isNestedStruct) {
index = generateNativeMembers((it.nativeType as StructType).definition.members, index + 1, prefix) // recursion
} else if (it is StructMemberPadding) {
index++
} else if (it.bits == -1) {
println("${t}buffer[$index] = (jint)offsetof($nativeName, $prefix${if (it.has<NativeName>()) it.get<NativeName>().nativeName else it.name});")
index++
if (it.isNestedStruct) {
// Output nested structs
val structType = it.nativeType as StructType
if (structType.name === ANONYMOUS)
index = generateNativeMembers(structType.definition.members, index, prefix = "$prefix${it.name}.") // recursion
}
}
}
return index
}
private fun PrintWriter.generateNativeGetters(members: List<StructMember>, prefix: String = "") {
members.forEach {
if (it.name === ANONYMOUS && it.isNestedStruct) {
generateNativeGetters((it.nativeType as StructType).definition.members, prefix) // recursion
} else if (it.isNestedStruct) {
// Output nested structs
val structType = it.nativeType as StructType
if (structType.name === ANONYMOUS)
generateNativeGetters(structType.definition.members, "$prefix${it.name}.") // recursion
} else if (it.bits != -1 && it.getter == null) {
val signature = "${nativeFileNameJNI}_n${"${prefix.replace('.', '_')}${it.name}".asJNIName}__J"
print("""
JNIEXPORT ${it.nativeType.jniFunctionType} JNICALL Java_$signature(JNIEnv *$JNIENV, jclass clazz, jlong bufferAddress) {
UNUSED_PARAMS($JNIENV, clazz)
$nativeName *buffer = ($nativeName *)(uintptr_t)bufferAddress;
return (${it.nativeType.jniFunctionType})buffer->$prefix${it.name};
}""")
}
}
}
private fun PrintWriter.generateNativeSetters(members: Sequence<StructMember>, prefix: String = "") {
members.forEach {
if (it.name === ANONYMOUS && it.isNestedStruct) {
generateNativeSetters((it.nativeType as StructType).definition.mutableMembers(), prefix) // recursion
} else if (it.isNestedStruct) {
// Output nested structs
val structType = it.nativeType as StructType
if (structType.name === ANONYMOUS)
generateNativeSetters(structType.definition.mutableMembers(), "$prefix${it.name}.") // recursion
} else if (it.bits != -1 && it.setter == null) {
val signature = "${nativeFileNameJNI}_n${"${prefix.replace('.', '_')}${it.name}".asJNIName}__J${it.nativeType.jniSignatureStrict}"
print("""
JNIEXPORT void JNICALL Java_$signature(JNIEnv *$JNIENV, jclass clazz, jlong bufferAddress, ${it.nativeType.jniFunctionType} value) {
UNUSED_PARAMS($JNIENV, clazz)
$nativeName *buffer = ($nativeName *)(uintptr_t)bufferAddress;
buffer->$prefix${it.name} = (${it.nativeType.name})value;
}""")
}
}
}
fun AutoSize(reference: String, vararg dependent: String, optional: Boolean = false, atLeastOne: Boolean = false) =
AutoSizeMember(reference, *dependent, optional = optional, atLeastOne = atLeastOne)
fun AutoSize(div: Int, reference: String, vararg dependent: String, optional: Boolean = false, atLeastOne: Boolean = false) =
when {
div < 1 -> throw IllegalArgumentException()
div == 1 -> AutoSizeMember(reference, *dependent, optional = optional, atLeastOne = atLeastOne)
Integer.bitCount(div) == 1 -> AutoSizeShr(Integer.numberOfTrailingZeros(div).toString(), reference, *dependent, optional = optional, atLeastOne = atLeastOne)
else -> AutoSizeDiv(div.toString(), reference, *dependent, optional = optional, atLeastOne = atLeastOne)
}
fun AutoSizeDiv(expression: String, reference: String, vararg dependent: String, optional: Boolean = false, atLeastOne: Boolean = false) =
AutoSizeMember(reference, *dependent, factor = AutoSizeFactor.div(expression), optional = optional, atLeastOne = atLeastOne)
fun AutoSizeMul(expression: String, reference: String, vararg dependent: String, optional: Boolean = false, atLeastOne: Boolean = false) =
AutoSizeMember(reference, *dependent, factor = AutoSizeFactor.mul(expression), optional = optional, atLeastOne = atLeastOne)
fun AutoSizeShr(expression: String, reference: String, vararg dependent: String, optional: Boolean = false, atLeastOne: Boolean = false) =
AutoSizeMember(reference, *dependent, factor = AutoSizeFactor.shr(expression), optional = optional, atLeastOne = atLeastOne)
fun AutoSizeShl(expression: String, reference: String, vararg dependent: String, optional: Boolean = false, atLeastOne: Boolean = false) =
AutoSizeMember(reference, *dependent, factor = AutoSizeFactor.shl(expression), optional = optional, atLeastOne = atLeastOne)
}
fun struct(
module: Module,
className: String,
nativeSubPath: String = "",
nativeName: String = className,
virtual: Boolean = false,
mutable: Boolean = true,
alias: StructType? = null,
parentStruct: StructType? = null,
nativeLayout: Boolean = false,
skipBuffer: Boolean = false,
setup: (Struct.() -> Unit)? = null
): StructType =
Struct(
module, className, nativeSubPath, nativeName, false,
virtual, mutable, alias?.definition, parentStruct?.definition, nativeLayout, !skipBuffer
).init(setup)
fun union(
module: Module,
className: String,
nativeSubPath: String = "",
nativeName: String = className,
virtual: Boolean = false,
mutable: Boolean = true,
alias: StructType? = null,
parentStruct: StructType? = null,
nativeLayout: Boolean = false,
skipBuffer: Boolean = false,
setup: (Struct.() -> Unit)? = null
): StructType =
Struct(
module, className, nativeSubPath, nativeName, true,
virtual, mutable, alias?.definition, parentStruct?.definition, nativeLayout, !skipBuffer
).init(setup) | bsd-3-clause | 5f640f9539dc7d69dea5f524ca315db4 | 45.91867 | 242 | 0.541099 | 4.946484 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/analytics/FindInPageFunnel.kt | 1 | 979 | package org.wikipedia.analytics
import org.json.JSONObject
import org.wikipedia.WikipediaApp
import org.wikipedia.dataclient.WikiSite
class FindInPageFunnel(app: WikipediaApp, wiki: WikiSite?, private val pageId: Int) :
TimedFunnel(app, SCHEMA_NAME, REV_ID, SAMPLE_LOG_ALL, wiki) {
private var numFindNext = 0
private var numFindPrev = 0
var pageHeight = 0
var findText: String? = null
override fun preprocessSessionToken(eventData: JSONObject) {}
fun addFindNext() {
numFindNext++
}
fun addFindPrev() {
numFindPrev++
}
fun logDone() {
log(
"pageID", pageId,
"numFindNext", numFindNext,
"numFindPrev", numFindPrev,
"findText", findText,
"pageHeight", pageHeight
)
}
companion object {
private const val SCHEMA_NAME = "MobileWikiAppFindInPage"
private const val REV_ID = 19690671
}
}
| apache-2.0 | d17eccac623c61de23e9c4af6e617deb | 24.102564 | 85 | 0.618999 | 4.219828 | false | false | false | false |
dahlstrom-g/intellij-community | java/java-impl-refactorings/src/com/intellij/refactoring/extractMethod/newImpl/ExtractMethodHelper.kt | 5 | 12765 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.refactoring.extractMethod.newImpl
import com.intellij.codeInsight.Nullability
import com.intellij.codeInsight.NullableNotNullManager
import com.intellij.codeInsight.PsiEquivalenceUtil
import com.intellij.codeInsight.generation.GenerateMembersUtil
import com.intellij.codeInsight.intention.AddAnnotationPsiFix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.codeStyle.VariableKind
import com.intellij.psi.formatter.java.MultipleFieldDeclarationHelper
import com.intellij.psi.impl.source.DummyHolder
import com.intellij.psi.impl.source.codeStyle.JavaCodeStyleManagerImpl
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.refactoring.IntroduceVariableUtil
import com.intellij.refactoring.extractMethod.newImpl.structures.DataOutput
import com.intellij.refactoring.extractMethod.newImpl.structures.DataOutput.*
import com.intellij.refactoring.extractMethod.newImpl.structures.ExtractOptions
import com.intellij.refactoring.extractMethod.newImpl.structures.InputParameter
import com.intellij.util.CommonJavaRefactoringUtil
object ExtractMethodHelper {
fun hasReferencesToScope(scope: List<PsiElement>, elements: List<PsiElement>): Boolean {
val localVariables = scope.asSequence().flatMap { element -> PsiTreeUtil.findChildrenOfType(element, PsiVariable::class.java) }.toSet()
return elements.asSequence()
.flatMap { element -> PsiTreeUtil.findChildrenOfType(element, PsiReferenceExpression::class.java) }
.mapNotNull { reference -> reference.resolve() as? PsiVariable }
.any { variable -> variable in localVariables }
}
@JvmStatic
fun findEditorSelection(editor: Editor): TextRange? {
val selectionModel = editor.selectionModel
return if (selectionModel.hasSelection()) TextRange(selectionModel.selectionStart, selectionModel.selectionEnd) else null
}
fun isNullabilityAvailable(extractOptions: ExtractOptions): Boolean {
val project = extractOptions.project
val scope = extractOptions.elements.first().resolveScope
val defaultNullable = NullableNotNullManager.getInstance(project).defaultNullable
val annotationClass = JavaPsiFacade.getInstance(project).findClass(defaultNullable, scope)
return annotationClass != null
}
fun wrapWithCodeBlock(elements: List<PsiElement>): List<PsiCodeBlock> {
require(elements.isNotEmpty())
val codeBlock = PsiElementFactory.getInstance(elements.first().project).createCodeBlock()
elements.forEach { codeBlock.add(it) }
return listOf(codeBlock)
}
fun getReturnedExpression(returnOrYieldStatement: PsiStatement): PsiExpression? {
return when (returnOrYieldStatement) {
is PsiReturnStatement -> returnOrYieldStatement.returnValue
is PsiYieldStatement -> returnOrYieldStatement.expression
else -> null
}
}
fun findUsedTypeParameters(source: PsiTypeParameterList?, searchScope: List<PsiElement>): List<PsiTypeParameter> {
val typeParameterList = CommonJavaRefactoringUtil.createTypeParameterListWithUsedTypeParameters(
source, *searchScope.toTypedArray())
return typeParameterList?.typeParameters.orEmpty().toList()
}
fun inputParameterOf(externalReference: ExternalReference): InputParameter {
return InputParameter(externalReference.references, requireNotNull(externalReference.variable.name), externalReference.variable.type)
}
fun inputParameterOf(expressionGroup: List<PsiExpression>): InputParameter {
require(expressionGroup.isNotEmpty())
val expression = expressionGroup.first()
val objectType = PsiType.getJavaLangObject(expression.manager, GlobalSearchScope.projectScope(expression.project))
return InputParameter(expressionGroup, guessName(expression), expressionGroup.first().type ?: objectType)
}
fun PsiElement.addSiblingAfter(element: PsiElement): PsiElement {
return this.parent.addAfter(element, this)
}
fun getValidParentOf(element: PsiElement): PsiElement {
val physicalParent = when (val parent = element.parent) {
is DummyHolder -> parent.context
null -> element.context
else -> parent
}
return physicalParent ?: throw IllegalArgumentException()
}
fun normalizedAnchor(anchor: PsiMember): PsiMember {
return if (anchor is PsiField) {
MultipleFieldDeclarationHelper.findLastFieldInGroup(anchor.node).psi as? PsiField ?: anchor
} else {
anchor
}
}
fun addNullabilityAnnotation(owner: PsiModifierListOwner, nullability: Nullability) {
val nullabilityManager = NullableNotNullManager.getInstance(owner.project)
val annotation = when (nullability) {
Nullability.NOT_NULL -> nullabilityManager.defaultNotNull
Nullability.NULLABLE -> nullabilityManager.defaultNullable
else -> return
}
val target: PsiAnnotationOwner? = if (owner is PsiParameter) owner.typeElement else owner.modifierList
if (target == null) return
val annotationElement = AddAnnotationPsiFix.addPhysicalAnnotationIfAbsent(annotation, PsiNameValuePair.EMPTY_ARRAY, target)
if (annotationElement != null) {
JavaCodeStyleManager.getInstance(owner.project).shortenClassReferences(annotationElement)
}
}
private fun findVariableReferences(element: PsiElement): Sequence<PsiVariable> {
val references = PsiTreeUtil.findChildrenOfAnyType(element, PsiReferenceExpression::class.java)
return references.asSequence().mapNotNull { reference -> (reference.resolve() as? PsiVariable) }
}
fun hasConflictResolve(name: String?, scopeToIgnore: List<PsiElement>): Boolean {
require(scopeToIgnore.isNotEmpty())
if (name == null) return false
val lastElement = scopeToIgnore.last()
val helper = JavaPsiFacade.getInstance(lastElement.project).resolveHelper
val resolvedRange = helper.resolveAccessibleReferencedVariable(name, lastElement.context)?.textRange ?: return false
return resolvedRange !in TextRange(scopeToIgnore.first().textRange.startOffset, scopeToIgnore.last().textRange.endOffset)
}
fun uniqueNameOf(name: String?, scopeToIgnore: List<PsiElement>, reservedNames: List<String>): String? {
require(scopeToIgnore.isNotEmpty())
if (name == null) return null
val lastElement = scopeToIgnore.last()
if (hasConflictResolve(name, scopeToIgnore) || name in reservedNames){
val styleManager = JavaCodeStyleManager.getInstance(lastElement.project) as JavaCodeStyleManagerImpl
return styleManager.suggestUniqueVariableName(name, lastElement, true)
} else {
return name
}
}
fun guessName(expression: PsiExpression): String {
val codeStyleManager = JavaCodeStyleManager.getInstance(expression.project) as JavaCodeStyleManagerImpl
return findVariableReferences(expression).mapNotNull { variable -> variable.name }.firstOrNull()
?: codeStyleManager.suggestSemanticNames(expression).firstOrNull()
?: "x"
}
fun createDeclaration(variable: PsiVariable): PsiDeclarationStatement {
val factory = PsiElementFactory.getInstance(variable.project)
val declaration = factory.createVariableDeclarationStatement(requireNotNull(variable.name), variable.type, null)
val declaredVariable = declaration.declaredElements.first() as PsiVariable
PsiUtil.setModifierProperty(declaredVariable, PsiModifier.FINAL, variable.hasModifierProperty(PsiModifier.FINAL))
variable.annotations.forEach { annotation -> declaredVariable.modifierList?.add(annotation) }
return declaration
}
fun getExpressionType(expression: PsiExpression): PsiType {
val type = CommonJavaRefactoringUtil.getTypeByExpressionWithExpectedType(expression)
return when {
type != null -> type
expression.parent is PsiExpressionStatement -> PsiType.VOID
else -> PsiType.getJavaLangObject(expression.manager, GlobalSearchScope.allScope(expression.project))
}
}
fun areSame(elements: List<PsiElement?>): Boolean {
val first = elements.firstOrNull()
return elements.all { element -> areSame(first, element) }
}
fun areSame(first: PsiElement?, second: PsiElement?): Boolean {
return when {
first != null && second != null -> PsiEquivalenceUtil.areElementsEquivalent(first, second)
first == null && second == null -> true
else -> false
}
}
private fun boxedTypeOf(type: PsiType, context: PsiElement): PsiType {
return (type as? PsiPrimitiveType)?.getBoxedType(context) ?: type
}
fun PsiModifierListOwner?.hasExplicitModifier(modifier: String): Boolean {
return this?.modifierList?.hasExplicitModifier(modifier) == true
}
fun DataOutput.withBoxedType(): DataOutput {
return when (this) {
is VariableOutput -> copy(type = boxedTypeOf(type, variable))
is ExpressionOutput -> copy(type = boxedTypeOf(type, returnExpressions.first()))
ArtificialBooleanOutput, is EmptyOutput -> this
}
}
fun areSemanticallySame(statements: List<PsiStatement>): Boolean {
if (statements.isEmpty()) return true
if (! areSame(statements)) return false
val returnExpressions = statements.mapNotNull { statement -> (statement as? PsiReturnStatement)?.returnValue }
return returnExpressions.all { expression -> PsiUtil.isConstantExpression(expression) || expression.type == PsiType.NULL }
}
fun haveReferenceToScope(elements: List<PsiElement>, scope: List<PsiElement>): Boolean {
val scopeRange = TextRange(scope.first().textRange.startOffset, scope.last().textRange.endOffset)
return elements.asSequence()
.flatMap { PsiTreeUtil.findChildrenOfAnyType(it, false, PsiJavaCodeReferenceElement::class.java).asSequence() }
.mapNotNull { reference -> reference.resolve() }
.any{ referencedElement -> referencedElement.textRange in scopeRange }
}
fun guessMethodName(options: ExtractOptions): List<String> {
val project = options.project
val initialMethodNames: MutableSet<String> = LinkedHashSet()
val codeStyleManager = JavaCodeStyleManager.getInstance(project) as JavaCodeStyleManagerImpl
val returnType = options.dataOutput.type
val expression = options.elements.singleOrNull() as? PsiExpression
if (expression != null || returnType !is PsiPrimitiveType) {
codeStyleManager.suggestVariableName(VariableKind.FIELD, null, expression, returnType).names
.forEach { name ->
initialMethodNames += codeStyleManager.variableNameToPropertyName(name, VariableKind.FIELD)
}
}
val outVariable = (options.dataOutput as? VariableOutput)?.variable
if (outVariable != null) {
val outKind = codeStyleManager.getVariableKind(outVariable)
val propertyName = codeStyleManager.variableNameToPropertyName(outVariable.name!!, outKind)
val names = codeStyleManager.suggestVariableName(VariableKind.FIELD, propertyName, null, outVariable.type).names
names.forEach { name ->
initialMethodNames += codeStyleManager.variableNameToPropertyName(name, VariableKind.FIELD)
}
}
val normalizedType = (returnType as? PsiEllipsisType)?.toArrayType() ?: returnType
val field = JavaPsiFacade.getElementFactory(project).createField("fieldNameToReplace", normalizedType)
fun suggestGetterName(name: String): String {
field.name = name
return GenerateMembersUtil.suggestGetterName(field)
}
return initialMethodNames.filter { PsiNameHelper.getInstance(project).isIdentifier(it) }
.map { propertyName -> suggestGetterName(propertyName) }
}
fun replacePsiRange(source: List<PsiElement>, target: List<PsiElement>): List<PsiElement> {
val sourceAsExpression = source.singleOrNull() as? PsiExpression
val targetAsExpression = target.singleOrNull() as? PsiExpression
if (sourceAsExpression != null && targetAsExpression != null) {
val replacedExpression = IntroduceVariableUtil.replace(sourceAsExpression,
targetAsExpression,
sourceAsExpression.project)
return listOf(replacedExpression)
}
val normalizedTarget = if (target.size > 1 && source.first().parent !is PsiCodeBlock) {
wrapWithCodeBlock(target)
}
else {
target
}
val replacedElements = normalizedTarget.reversed().map { statement -> source.last().addSiblingAfter(statement) }.reversed()
source.first().parent.deleteChildRange(source.first(), source.last())
return replacedElements
}
} | apache-2.0 | d325672fcbbe02fd681342163197cbd5 | 46.281481 | 139 | 0.75707 | 5.051444 | false | false | false | false |
spotify/heroic | aggregation/simple/src/main/java/com/spotify/heroic/aggregation/simple/TdigestMergingBucket.kt | 1 | 2483 | /*
* Copyright (c) 2015 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.aggregation.simple
import com.spotify.heroic.aggregation.AbstractBucket
import com.spotify.heroic.aggregation.TDigestBucket
import com.spotify.heroic.metric.DistributionPoint
import com.spotify.heroic.metric.HeroicDistribution
import com.spotify.heroic.metric.TdigestPoint
import com.tdunning.math.stats.MergingDigest
import com.tdunning.math.stats.TDigest;
/**
*
* This bucket merges data sketch in every distribution data point visited.
* As the name indicates, this implementation only supports Tdigest.
*
*/
data class TdigestMergingBucket(override val timestamp: Long) : AbstractBucket(), TDigestBucket {
private val datasketch : TDigest = TdigestInstanceUtils.inital()
override fun updateDistributionPoint(key: Map<String, String>, sample : DistributionPoint) {
val heroicDistribution : HeroicDistribution = HeroicDistribution.create(sample.value().value)
val serializedDatasketch = heroicDistribution.toByteBuffer()
val input: TDigest = MergingDigest.fromBytes(serializedDatasketch)
if ( input.size() > 0) {
update(input)
}
}
@Synchronized fun update(input : TDigest) {
//This is a temp fix to handle corrupted datapoint.
try {
datasketch.add(input)
}catch(ignore: Exception) {
}
}
override fun updateTDigestPoint(key: Map<String, String>, sample : TdigestPoint) {
val input: TDigest = sample.value()
if ( input.size() > 0) {
update(input)
}
}
@Synchronized override fun value(): TDigest {
return datasketch
}
}
| apache-2.0 | 1a62c593c56f4538aaa64089f9f3f8bc | 33.486111 | 101 | 0.717277 | 4.173109 | false | false | false | false |
bitterblue/livingdoc2 | livingdoc-engine/src/main/kotlin/org/livingdoc/engine/fixtures/FixtureMethodInvoker.kt | 2 | 5915 | package org.livingdoc.engine.fixtures
import org.livingdoc.api.conversion.TypeConverter
import org.livingdoc.converters.TypeConverters
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.lang.reflect.Parameter
class FixtureMethodInvoker(
private val document: Any?
) {
/**
* Invoke the given static `method` with the given [String] `arguments`.
*
* Before invoking the method, the [String] arguments will be converted into objects of the appropriate types.
* This is done by looking up a matching [TypeConverter] as follows:
*
* 1. `parameter`
* 2. `method`
* 3. `class`
* 4. `document`
* 5. `default`
*
* This method is capable of invoking any static method. If the invoked method is not public, it will be made so.
*
* @param method the [Method] to invoke
* @param arguments the arguments for the invoked method as strings
* @return the result of the invocation or `null` in case the invoked method has not return type (`void` / `Unit`)
* @throws StaticFixtureMethodInvocationException in case anything went wrong with the invocation
*/
fun invokeStatic(method: Method, arguments: Array<String> = emptyArray()): Any? {
try {
return doInvokeStatic(method, arguments)
} catch (e: Exception) {
throw StaticFixtureMethodInvocationException(method, method.declaringClass, e)
}
}
private fun doInvokeStatic(method: Method, arguments: Array<String>): Any? {
val methodParameters = method.parameters
assertThatAllArgumentsForMethodAreProvided(arguments, methodParameters)
val convertedArguments = convert(arguments, methodParameters)
return forceInvocation(method, convertedArguments)
}
/**
* Invoke the given `method` on the given `fixture` instance with the given [String] `arguments`.
*
* Before invoking the method, the [String] arguments will be converted into objects of the appropriate types.
* This is done by looking up a matching [TypeConverter] as follows:
*
* 1. `parameter`
* 2. `method`
* 3. `class`
* 4. `document`
* 5. `default`
*
* This method is capable of invoking any method on the given fixture instance. If the invoked method is not
* public, it will be made so.
*
* @param method the [Method] to invoke
* @param fixture the fixture instance to invoke the method on
* @param arguments the arguments for the invoked method as strings
* @return the result of the invocation or `null` in case the invoked method has not return type (`void` / `Unit`)
* @throws FixtureMethodInvocationException in case anything went wrong with the invocation
*/
fun invoke(method: Method, fixture: Any, arguments: Array<String> = emptyArray()): Any? {
try {
return doInvoke(method, fixture, arguments)
} catch (e: Exception) {
throw FixtureMethodInvocationException(method, fixture, e)
}
}
private fun doInvoke(method: Method, fixture: Any, arguments: Array<String>): Any? {
val methodParameters = method.parameters
assertThatAllArgumentsForMethodAreProvided(arguments, methodParameters)
val convertedArguments = convert(arguments, methodParameters)
return forceInvocation(method, convertedArguments, fixture)
}
private fun assertThatAllArgumentsForMethodAreProvided(
arguments: Array<String>,
methodParameters: Array<Parameter>
) {
val numberOfArguments = arguments.size
val numberOfMethodParameters = methodParameters.size
if (numberOfArguments != numberOfMethodParameters) {
throw MismatchedNumberOfArgumentsException(numberOfArguments, numberOfMethodParameters)
}
}
private fun convert(
arguments: Array<String>,
methodParameters: Array<Parameter>
): Array<Any> { // TODO: Zip function?
val convertedArguments = mutableListOf<Any>()
for (i in arguments.indices) {
val argument = arguments[i]
val methodParameter = methodParameters[i]
val convertedArgument = convert(argument, methodParameter)
convertedArguments.add(convertedArgument)
}
return convertedArguments.toTypedArray()
}
private fun convert(argument: String, methodParameter: Parameter): Any {
val documentClass = document?.javaClass
val typeConverter = TypeConverters.findTypeConverter(methodParameter, documentClass)
?: throw NoTypeConverterFoundException(methodParameter)
return typeConverter.convert(argument, methodParameter, documentClass)
}
private fun forceInvocation(method: Method, arguments: Array<Any>, instance: Any? = null): Any? {
method.isAccessible = true
try {
return method.invoke(instance, arguments)
} catch (e: InvocationTargetException) {
throw e.cause ?: e
}
}
class FixtureMethodInvocationException(method: Method, fixture: Any, e: Exception) :
RuntimeException("Could not invoke method '$method' on fixture '$fixture' because of an exception:", e)
class StaticFixtureMethodInvocationException(method: Method, fixtureClass: Class<*>, e: Exception) :
RuntimeException(
"Could not invoke method '$method' on fixture class '$fixtureClass' because of an exception:",
e
)
internal class MismatchedNumberOfArgumentsException(args: Int, params: Int) :
RuntimeException("Method argument number mismatch: arguments = $args, method parameters = $params")
internal class NoTypeConverterFoundException(parameter: Parameter) :
RuntimeException("No type converter could be found to convert method parameter: $parameter")
}
| apache-2.0 | 0bce85b9f2ff650a532f7038aea3919e | 41.862319 | 118 | 0.685207 | 4.904643 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/fir-low-level-api-ide-impl/src/org/jetbrains/kotlin/idea/fir/low/level/api/ide/SealedClassInheritorsProviderIdeImpl.kt | 3 | 3405 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.fir.low.level.api.ide
import com.intellij.openapi.module.Module
import com.intellij.psi.JavaDirectoryService
import com.intellij.psi.PsiPackage
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PackageScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.ClassInheritorsSearch
import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.utils.classId
import org.jetbrains.kotlin.fir.declarations.utils.isSealed
import org.jetbrains.kotlin.fir.psi
import org.jetbrains.kotlin.idea.base.psi.classIdIfNonLocal
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade
import java.util.concurrent.ConcurrentHashMap
internal class SealedClassInheritorsProviderIdeImpl : SealedClassInheritorsProvider() {
val cache = ConcurrentHashMap<ClassId, List<ClassId>>()
@OptIn(SealedClassInheritorsProviderInternals::class)
override fun getSealedClassInheritors(firClass: FirRegularClass): List<ClassId> {
require(firClass.isSealed)
firClass.sealedInheritorsAttr?.let { return it }
return cache.computeIfAbsent(firClass.classId) { getInheritors(firClass) }
}
private fun getInheritors(firClass: FirRegularClass): List<ClassId> {
// TODO fix for non-source classes
val sealedKtClass = firClass.psi as? KtClass ?: return emptyList()
val module = sealedKtClass.module ?: return emptyList()
val containingPackage = firClass.classId.packageFqName
val psiPackage = KotlinJavaPsiFacade.getInstance(sealedKtClass.project)
.findPackage(containingPackage.asString(), GlobalSearchScope.moduleScope(module))
?: getPackageViaDirectoryService(sealedKtClass)
?: return emptyList()
val kotlinAsJavaSupport = KotlinAsJavaSupport.getInstance(sealedKtClass.project)
val lightClass = sealedKtClass.toLightClass() ?: kotlinAsJavaSupport.getFakeLightClass(sealedKtClass)
val searchScope: SearchScope = getSearchScope(module, psiPackage)
val searchParameters = ClassInheritorsSearch.SearchParameters(lightClass, searchScope, false, true, false)
val subclasses = ClassInheritorsSearch.search(searchParameters)
.mapNotNull { it.classIdIfNonLocal }
.toMutableList()
// Enforce a deterministic order on the result.
subclasses.sortBy { it.toString() }
return subclasses
}
private fun getSearchScope(module: Module, psiPackage: PsiPackage): GlobalSearchScope {
val packageScope = PackageScope(psiPackage, false, false)
// MPP multiple common modules are not supported!!
return module.moduleScope.intersectWith(packageScope)
}
private fun getPackageViaDirectoryService(ktClass: KtClass): PsiPackage? {
val directory = ktClass.containingFile.containingDirectory ?: return null
return JavaDirectoryService.getInstance().getPackage(directory)
}
}
| apache-2.0 | 3e5cd60b532a473d27a68022e0614abd | 46.957746 | 158 | 0.767988 | 4.927641 | false | false | false | false |
DreierF/MyTargets | shared/src/main/java/de/dreier/mytargets/shared/models/Target.kt | 1 | 3265 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.shared.models
import androidx.room.ColumnInfo
import androidx.room.Ignore
import android.os.Parcelable
import de.dreier.mytargets.shared.models.db.Shot
import de.dreier.mytargets.shared.targets.TargetFactory
import de.dreier.mytargets.shared.targets.drawable.TargetDrawable
import de.dreier.mytargets.shared.targets.models.TargetModelBase
import de.dreier.mytargets.shared.targets.scoringstyle.ScoringStyle
import kotlinx.android.parcel.IgnoredOnParcel
import kotlinx.android.parcel.Parcelize
/**
* Represents a target face, which is in contrast to a [TargetModelBase] bound to a specific
* scoring style and diameter.
*/
@Parcelize
data class Target(
@ColumnInfo(name = "targetId")
override var id: Long = 0,
@ColumnInfo(name = "targetScoringStyleIndex")
var scoringStyleIndex: Int = 0,
@ColumnInfo(name = "targetDiameter")
var diameter: Dimension = Dimension.UNKNOWN
) : IIdProvider, Comparable<Target>, Parcelable {
@IgnoredOnParcel
@delegate:Ignore
val model: TargetModelBase by lazy { TargetFactory.getTarget(id) }
@IgnoredOnParcel
@delegate:Ignore
val drawable: TargetDrawable by lazy { TargetDrawable(this) }
@Ignore
constructor(target: Long, scoringStyle: Int) : this(target, scoringStyle, Dimension.UNKNOWN) {
this.diameter = model.diameters[0]
}
val name: String
get() = String.format("%s (%s)", toString(), diameter.toString())
fun zoneToString(zone: Int, arrow: Int): String {
return getScoringStyle().zoneToString(zone, arrow)
}
fun getScoreByZone(zone: Int, arrow: Int): Int {
return getScoringStyle().getPointsByScoringRing(zone, arrow)
}
fun getDetails(): String {
return model.scoringStyles[scoringStyleIndex].toString()
}
fun getSelectableZoneList(arrow: Int): List<SelectableZone> {
return model.getSelectableZoneList(scoringStyleIndex, arrow)
}
fun getScoringStyle(): ScoringStyle {
return model.getScoringStyle(scoringStyleIndex)
}
fun getReachedScore(shots: List<Shot>): Score {
return getScoringStyle().getReachedScore(shots)
}
override fun toString(): String {
return model.toString()
}
override fun compareTo(other: Target) = compareBy(Target::id).compare(this, other)
companion object {
fun singleSpotTargetFrom(spotTarget: Target): Target {
if (spotTarget.model.faceCount == 1) {
return spotTarget
}
val singleSpotTargetId = spotTarget.model.singleSpotTargetId.toInt()
return Target(singleSpotTargetId.toLong(), spotTarget.scoringStyleIndex, spotTarget.diameter)
}
}
}
| gpl-2.0 | 0fd67c6529819c50fef98a703fbe9299 | 32.659794 | 105 | 0.709954 | 4.313078 | false | false | false | false |
spoptchev/kotlin-preconditions | src/main/kotlin/com/github/spoptchev/kotlin/preconditions/matcher/MapMatcher.kt | 1 | 961 | package com.github.spoptchev.kotlin.preconditions.matcher
import com.github.spoptchev.kotlin.preconditions.Condition
import com.github.spoptchev.kotlin.preconditions.Matcher
import com.github.spoptchev.kotlin.preconditions.PreconditionBlock
fun <K, M : Map<K, *>> PreconditionBlock<M>.hasKey(key: K) = object : Matcher<M>() {
override fun test(condition: Condition<M>) = condition.test {
withResult(value.containsKey(key)) { "$expectedTo contain key $key" }
}
}
fun <V, M : Map<*, V>> PreconditionBlock<M>.hasValue(v: V) = object : Matcher<M>() {
override fun test(condition: Condition<M>) = condition.test {
withResult(value.containsValue(v)) { "$expectedTo contain value $v" }
}
}
fun <K, V, M : Map<K, V>> PreconditionBlock<M>.contains(key: K, v: V) = object : Matcher<M>() {
override fun test(condition: Condition<M>) = condition.test {
withResult(value[key] == v) { "$expectedTo contain $key=$v" }
}
}
| mit | 14510867692718d82e5f52d62b8e673e | 37.44 | 95 | 0.683663 | 3.279863 | false | true | false | false |
cbeust/klaxon | klaxon/src/test/kotlin/com/beust/klaxon/ParseFromEmptyNameTest.kt | 1 | 809 | package com.beust.klaxon
import org.testng.Assert
import org.testng.annotations.Test
@Test
class ParseFromEmptyNameTest {
fun nameSetToEmptyString() {
data class EmptyName (
@Json(name = "")
val empty: String)
val sampleJson = """{"":"value"}"""
val result = Klaxon().parse<EmptyName>(sampleJson)
Assert.assertNotNull(result)
Assert.assertEquals(result!!.empty, "value")
}
fun nameSetToDefaultValue() {
data class SpecificName (
@Json(name = NAME_NOT_INITIALIZED)
val oddName: String)
val sampleJson = """{"$NAME_NOT_INITIALIZED":"value"}"""
Assert.assertThrows(KlaxonException::class.java) {
Klaxon().parse<SpecificName>(sampleJson)
}
}
}
| apache-2.0 | 806f65e1eedb5f816784226b6088676c | 26.896552 | 64 | 0.593325 | 4.396739 | false | true | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mcp/actions/CopyAtAction.kt | 1 | 2097 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.actions
import com.demonwav.mcdev.platform.mcp.srg.McpSrgMap
import com.demonwav.mcdev.util.ActionData
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiField
import com.intellij.psi.PsiMethod
import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
class CopyAtAction : SrgActionBase() {
override fun withSrgTarget(parent: PsiElement, srgMap: McpSrgMap, e: AnActionEvent, data: ActionData) {
when (parent) {
is PsiField -> {
val srg = srgMap.getSrgField(parent) ?: return showBalloon("No SRG name found", e)
copyToClipboard(
data.editor,
data.element,
parent.containingClass?.qualifiedName + " " + srg.name + " #" + parent.name
)
}
is PsiMethod -> {
val srg = srgMap.getSrgMethod(parent) ?: return showBalloon("No SRG name found", e)
copyToClipboard(
data.editor,
data.element,
parent.containingClass?.qualifiedName + " " + srg.name + srg.descriptor + " #" + parent.name
)
}
is PsiClass -> {
val classMcpToSrg = srgMap.getSrgClass(parent) ?: return showBalloon("No SRG name found", e)
copyToClipboard(data.editor, data.element, classMcpToSrg)
}
else -> showBalloon("Not a valid element", e)
}
}
private fun copyToClipboard(editor: Editor, element: PsiElement, text: String) {
val stringSelection = StringSelection(text)
val clpbrd = Toolkit.getDefaultToolkit().systemClipboard
clpbrd.setContents(stringSelection, null)
showSuccessBalloon(editor, element, "Copied " + text)
}
}
| mit | a3f6500164c383e5a4c379b49290d6fa | 35.789474 | 112 | 0.621364 | 4.433404 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/actions/BookmarkTypeChooser.kt | 1 | 9865 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.bookmark.actions
import com.intellij.ide.bookmark.BookmarkBundle.message
import com.intellij.ide.bookmark.BookmarkType
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.JBColor.namedColor
import com.intellij.ui.components.JBTextField
import com.intellij.ui.components.panels.RowGridLayout
import com.intellij.ui.dsl.builder.BottomGap
import com.intellij.ui.dsl.builder.IntelliJSpacingConfiguration
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.RegionPaintIcon
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import org.jetbrains.annotations.Nls
import java.awt.*
import java.awt.RenderingHints.KEY_ANTIALIASING
import java.awt.RenderingHints.VALUE_ANTIALIAS_ON
import java.awt.event.KeyEvent
import java.awt.event.KeyListener
import javax.swing.*
private val ASSIGNED_FOREGROUND = namedColor("Bookmark.MnemonicAssigned.foreground", 0x000000, 0xBBBBBB)
private val ASSIGNED_BACKGROUND = namedColor("Bookmark.MnemonicAssigned.background", 0xF7C777, 0x665632)
private val CURRENT_FOREGROUND = namedColor("Bookmark.MnemonicCurrent.foreground", 0xFFFFFF, 0xFEFEFE)
private val CURRENT_BACKGROUND = namedColor("Bookmark.MnemonicCurrent.background", 0x389FD6, 0x345F85)
private val SHARED_CURSOR by lazy { Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) }
private val SHARED_LAYOUT by lazy {
object : RowGridLayout(0, 4, 2, SwingConstants.CENTER) {
override fun getCellSize(sizes: List<Dimension>) = when {
ExperimentalUI.isNewUI() -> Dimension(JBUI.scale(30), JBUI.scale(34))
else -> Dimension(JBUI.scale(24), JBUI.scale(28))
}
}
}
private object MySpacingConfiguration: IntelliJSpacingConfiguration() {
override val verticalComponentGap: Int
get() = 0
override val verticalSmallGap: Int
get() = JBUI.scale(8)
override val verticalMediumGap: Int
get() = JBUI.scale(if (ExperimentalUI.isNewUI()) 16 else 8)
}
internal class BookmarkTypeChooser(
private var current: BookmarkType?,
assigned: Set<BookmarkType>,
private var description: String?,
private val onChosen: (BookmarkType, String) -> Unit
): JPanel(FlowLayout(FlowLayout.CENTER, 0, 0)) {
private val bookmarkLayoutGrid = BookmarkLayoutGrid(
current,
assigned,
{ if (current == it) save() else current = it },
{ save() }
)
private lateinit var descriptionField: JBTextField
val firstButton = bookmarkLayoutGrid.buttons().first()
init {
add(panel {
customizeSpacingConfiguration(MySpacingConfiguration) {
row {
val lineLength = if (ExperimentalUI.isNewUI()) 63 else 55
comment(message("mnemonic.chooser.comment"), lineLength).apply {
if (ExperimentalUI.isNewUI()) border = JBUI.Borders.empty(2, 4, 0, 4)
}
}.bottomGap(BottomGap.MEDIUM)
row {
cell(bookmarkLayoutGrid)
.horizontalAlign(HorizontalAlign.CENTER)
}.bottomGap(BottomGap.MEDIUM)
row {
descriptionField = textField()
.horizontalAlign(HorizontalAlign.FILL)
.applyToComponent {
text = description ?: ""
emptyText.text = message("mnemonic.chooser.description")
isOpaque = false
addKeyListener(object : KeyListener {
override fun keyTyped(e: KeyEvent?) = Unit
override fun keyReleased(e: KeyEvent?) = Unit
override fun keyPressed(e: KeyEvent?) {
if (e != null && e.modifiersEx == 0 && e.keyCode == KeyEvent.VK_ENTER) {
save()
}
}
})
}
.component
}.bottomGap(BottomGap.SMALL)
row {
cell(createLegend(ASSIGNED_BACKGROUND, message("mnemonic.chooser.legend.assigned.bookmark")))
cell(createLegend(CURRENT_BACKGROUND, message("mnemonic.chooser.legend.current.bookmark")))
}
}
}.apply {
border = when {
ExperimentalUI.isNewUI() -> JBUI.Borders.empty(0, 20, 14, 20)
else -> JBUI.Borders.empty(12, 11)
}
isOpaque = false
isFocusCycleRoot = true
focusTraversalPolicy = object: LayoutFocusTraversalPolicy() {
override fun accept(aComponent: Component?): Boolean {
return super.accept(aComponent) && (aComponent !is JButton || aComponent == firstButton)
}
}
})
border = JBUI.Borders.empty()
background = namedColor("Popup.background")
}
private fun createLegend(color: Color, @Nls text: String) = JLabel(text).apply {
icon = RegionPaintIcon(8) { g, x, y, width, height, _ ->
g.color = color
g.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON)
g.fillOval(x, y, width, height)
}.withIconPreScaled(false)
}
private fun save() {
current?.let {
onChosen(it, descriptionField.text)
}
}
}
private class BookmarkLayoutGrid(
current: BookmarkType?,
private val assigned: Set<BookmarkType>,
private val onChosen: (BookmarkType) -> Unit,
private val save: () -> Unit
) : BorderLayoutPanel(), KeyListener {
companion object {
const val TYPE_KEY: String = "BookmarkLayoutGrid.Type"
}
init {
addToLeft(JPanel(SHARED_LAYOUT).apply {
border = when {
ExperimentalUI.isNewUI() -> JBUI.Borders.emptyRight(14)
else -> JBUI.Borders.empty(5)
}
isOpaque = false
BookmarkType.values()
.filter { it.mnemonic.isDigit() }
.forEach { add(createButton(it)) }
})
addToRight(JPanel(SHARED_LAYOUT).apply {
border = when {
ExperimentalUI.isNewUI() -> JBUI.Borders.empty()
else -> JBUI.Borders.empty(5)
}
isOpaque = false
BookmarkType.values()
.filter { it.mnemonic.isLetter() }
.forEach { add(createButton(it)) }
})
isOpaque = false
updateButtons(current)
}
fun buttons() = UIUtil.uiTraverser(this).traverse().filter(JButton::class.java)
fun createButton(type: BookmarkType) = JButton(type.mnemonic.toString()).apply {
setMnemonic(type.mnemonic)
isOpaque = false
putClientProperty("ActionToolbar.smallVariant", true)
putClientProperty(TYPE_KEY, type)
addPropertyChangeListener { repaint() }
addActionListener {
onChosen(type)
updateButtons(type)
}
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "released")
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "pressed")
cursor = SHARED_CURSOR
addKeyListener(this@BookmarkLayoutGrid)
}
fun updateButtons(current: BookmarkType?) {
buttons().forEach {
val type = it.getClientProperty(TYPE_KEY) as? BookmarkType
when {
type == current -> {
it.putClientProperty("JButton.textColor", CURRENT_FOREGROUND)
it.putClientProperty("JButton.backgroundColor", CURRENT_BACKGROUND)
it.putClientProperty("JButton.borderColor", CURRENT_BACKGROUND)
}
assigned.contains(type) -> {
it.putClientProperty("JButton.textColor", ASSIGNED_FOREGROUND)
it.putClientProperty("JButton.backgroundColor", ASSIGNED_BACKGROUND)
it.putClientProperty("JButton.borderColor", ASSIGNED_BACKGROUND)
}
else -> {
it.putClientProperty("JButton.textColor", UIManager.getColor("Bookmark.MnemonicAvailable.foreground"))
it.putClientProperty("JButton.backgroundColor", UIManager.getColor("Popup.background"))
it.putClientProperty("JButton.borderColor", UIManager.getColor("Bookmark.MnemonicAvailable.borderColor"))
}
}
}
}
private fun offset(delta: Int, size: Int) = when {
delta < 0 -> delta
delta > 0 -> delta + size
else -> size / 2
}
private fun next(source: Component, dx: Int, dy: Int): Component? {
val point = SwingUtilities.convertPoint(source, offset(dx, source.width), offset(dy, source.height), this)
val component = next(source, dx, dy, point)
if (component != null || !Registry.`is`("ide.bookmark.mnemonic.chooser.cyclic.scrolling.allowed")) return component
if (dx > 0) point.x = 0
if (dx < 0) point.x = dx + width
if (dy > 0) point.y = 0
if (dy < 0) point.y = dy + height
return next(source, dx, dy, point)
}
private fun next(source: Component, dx: Int, dy: Int, point: Point): Component? {
while (contains(point)) {
val component = SwingUtilities.getDeepestComponentAt(this, point.x, point.y)
if (component is JButton) return component
point.translate(dx * source.width / 2, dy * source.height / 2)
}
return null
}
override fun keyTyped(event: KeyEvent) = Unit
override fun keyReleased(event: KeyEvent) = Unit
override fun keyPressed(event: KeyEvent) {
if (event.modifiersEx == 0) {
when (event.keyCode) {
KeyEvent.VK_UP, KeyEvent.VK_KP_UP -> next(event.component, 0, -1)?.requestFocus()
KeyEvent.VK_DOWN, KeyEvent.VK_KP_DOWN -> next(event.component, 0, 1)?.requestFocus()
KeyEvent.VK_LEFT, KeyEvent.VK_KP_LEFT -> next(event.component, -1, 0)?.requestFocus()
KeyEvent.VK_RIGHT, KeyEvent.VK_KP_RIGHT -> next(event.component, 1, 0)?.requestFocus()
KeyEvent.VK_ENTER -> {
val button = next(event.component, 0, 0) as? JButton
button?.doClick()
save()
}
else -> {
val type = BookmarkType.get(event.keyCode.toChar())
if (type != BookmarkType.DEFAULT) {
onChosen(type)
save()
}
}
}
}
}
}
| apache-2.0 | 12343ad302a7989875f8595b9e351d2c | 35.268382 | 120 | 0.665484 | 4.239364 | false | false | false | false |
google/intellij-community | platform/testFramework/src/com/intellij/testFramework/utils/inlays/InlayParameterHintsTest.kt | 4 | 8514 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.testFramework.utils.inlays
import com.intellij.codeInsight.daemon.impl.HintRenderer
import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager
import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.VisualPosition
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.util.TextRange
import com.intellij.rt.execution.junit.FileComparisonFailure
import com.intellij.testFramework.VfsTestUtil
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
import junit.framework.ComparisonFailure
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import java.util.regex.Pattern
class InlayHintsChecker(private val myFixture: CodeInsightTestFixture) {
private var isParamHintsEnabledBefore = false
companion object {
val pattern: Pattern = Pattern.compile("(<caret>)|(<selection>)|(</selection>)|<(hint|HINT|Hint|hINT)\\s+text=\"([^\n\r]+?(?=\"\\s*/>))\"\\s*/>")
private val default = ParameterNameHintsSettings()
}
fun setUp() {
val settings = EditorSettingsExternalizable.getInstance()
isParamHintsEnabledBefore = settings.isShowParameterNameHints
settings.isShowParameterNameHints = true
}
fun tearDown() {
EditorSettingsExternalizable.getInstance().isShowParameterNameHints = isParamHintsEnabledBefore
val hintSettings = ParameterNameHintsSettings.getInstance()
hintSettings.loadState(default.state)
}
val manager = ParameterHintsPresentationManager.getInstance()
val inlayPresenter: (Inlay<*>) -> String = { (it.renderer as HintRenderer).text ?: throw IllegalArgumentException("No text set to hint") }
val inlayFilter: (Inlay<*>) -> Boolean = { manager.isParameterHint(it) }
fun checkParameterHints() = checkInlays(inlayPresenter, inlayFilter)
fun checkInlays(inlayPresenter: (Inlay<*>) -> String, inlayFilter: (Inlay<*>) -> Boolean) {
val file = myFixture.file!!
val document = myFixture.getDocument(file)
val originalText = document.text
val expectedInlaysAndCaret = extractInlaysAndCaretInfo(document)
myFixture.doHighlighting()
verifyInlaysAndCaretInfo(expectedInlaysAndCaret, originalText, inlayPresenter, inlayFilter)
}
fun verifyInlaysAndCaretInfo(expectedInlaysAndCaret: CaretAndInlaysInfo,
originalText: String) =
verifyInlaysAndCaretInfo(expectedInlaysAndCaret, originalText, inlayPresenter, inlayFilter)
private fun verifyInlaysAndCaretInfo(expectedInlaysAndCaret: CaretAndInlaysInfo,
originalText: String,
inlayPresenter: (Inlay<*>) -> String,
inlayFilter: (Inlay<*>) -> Boolean) {
val file = myFixture.file!!
val document = myFixture.getDocument(file)
val actual: List<InlayInfo> = getActualInlays(inlayPresenter, inlayFilter)
val expected = expectedInlaysAndCaret.inlays
if (expectedInlaysAndCaret.inlays.size != actual.size || actual.zip(expected).any { it.first != it.second }) {
val entries: MutableList<Pair<Int, String>> = mutableListOf()
actual.forEach { entries.add(Pair(it.offset, buildString {
append("<")
append((if (it.highlighted) "H" else "h"))
append((if (it.current) "INT" else "int"))
append(" text=\"")
append(it.text)
append("\"/>")
}))}
if (expectedInlaysAndCaret.caretOffset != null) {
val actualCaretOffset = myFixture.editor.caretModel.offset
val actualInlaysBeforeCaret = myFixture.editor.caretModel.visualPosition.column -
myFixture.editor.offsetToVisualPosition(actualCaretOffset).column
val first = entries.indexOfFirst { it.first == actualCaretOffset }
val insertIndex = if (first == -1) -entries.binarySearch { it.first - actualCaretOffset } - 1
else first + actualInlaysBeforeCaret
entries.add(insertIndex, Pair(actualCaretOffset, "<caret>"))
}
val proposedText = StringBuilder(document.text)
entries.asReversed().forEach { proposedText.insert(it.first, it.second) }
VfsTestUtil.TEST_DATA_FILE_PATH.get(file.virtualFile)?.let { originalPath ->
throw FileComparisonFailure("Hints differ", originalText, proposedText.toString(), originalPath)
} ?: throw ComparisonFailure("Hints differ", originalText, proposedText.toString())
}
if (expectedInlaysAndCaret.caretOffset != null) {
assertEquals("Unexpected caret offset", expectedInlaysAndCaret.caretOffset, myFixture.editor.caretModel.offset)
val position = myFixture.editor.offsetToVisualPosition(expectedInlaysAndCaret.caretOffset)
assertEquals("Unexpected caret visual position",
VisualPosition(position.line, position.column + expectedInlaysAndCaret.inlaysBeforeCaret),
myFixture.editor.caretModel.visualPosition)
val selectionModel = myFixture.editor.selectionModel
if (expectedInlaysAndCaret.selection == null) assertFalse(selectionModel.hasSelection())
else assertEquals("Unexpected selection",
expectedInlaysAndCaret.selection,
TextRange(selectionModel.selectionStart, selectionModel.selectionEnd))
}
}
private fun getActualInlays(inlayPresenter: (Inlay<*>) -> String,
inlayFilter: (Inlay<*>) -> Boolean): List<InlayInfo> {
val editor = myFixture.editor
val allInlays = editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength) +
editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength)
val hintManager = ParameterHintsPresentationManager.getInstance()
return allInlays
.filterNotNull()
.filter { inlayFilter(it) }
.map {
val isHighlighted: Boolean
val isCurrent: Boolean
if (hintManager.isParameterHint(it)) {
isHighlighted = hintManager.isHighlighted(it)
isCurrent = hintManager.isCurrent(it)
} else {
isHighlighted = false
isCurrent = false
}
InlayInfo(it.offset, inlayPresenter(it), isHighlighted, isCurrent)
}
.sortedBy { it.offset }
}
fun extractInlaysAndCaretInfo(document: Document): CaretAndInlaysInfo {
val text = document.text
val matcher = pattern.matcher(text)
val inlays = mutableListOf<InlayInfo>()
var extractedLength = 0
var caretOffset : Int? = null
var inlaysBeforeCaret = 0
var selectionStart : Int? = null
var selectionEnd : Int? = null
while (matcher.find()) {
val start = matcher.start()
val matchedLength = matcher.end() - start
val realStartOffset = start - extractedLength
when {
matcher.group(1) != null -> {
caretOffset = realStartOffset
inlays.asReversed()
.takeWhile { it.offset == caretOffset }
.forEach { inlaysBeforeCaret++ }
}
matcher.group(2) != null -> selectionStart = realStartOffset
matcher.group(3) != null -> selectionEnd = realStartOffset
else -> inlays += InlayInfo(realStartOffset, matcher.group(5), matcher.group(4).startsWith("H"), matcher.group(4).endsWith("INT"))
}
removeText(document, realStartOffset, matchedLength)
extractedLength += (matcher.end() - start)
}
return CaretAndInlaysInfo(caretOffset, inlaysBeforeCaret,
if (selectionStart == null || selectionEnd == null) null else TextRange(selectionStart, selectionEnd),
inlays)
}
private fun removeText(document: Document, realStartOffset: Int, matchedLength: Int) {
WriteCommandAction.runWriteCommandAction(myFixture.project, {
document.replaceString(realStartOffset, realStartOffset + matchedLength, "")
})
}
}
class CaretAndInlaysInfo (val caretOffset: Int?, val inlaysBeforeCaret: Int, val selection: TextRange?,
val inlays: List<InlayInfo>)
data class InlayInfo (val offset: Int, val text: String, val highlighted: Boolean, val current: Boolean) | apache-2.0 | d17d28bec9359f01ec0ffdd0be3c7c8b | 44.05291 | 149 | 0.6965 | 5.110444 | false | false | false | false |
RuneSuite/client | updater-deob/src/main/java/org/runestar/client/updater/deob/rs/OpaquePredicateCheckRemover.kt | 1 | 4790 | package org.runestar.client.updater.deob.rs
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.kxtra.slf4j.getLogger
import org.kxtra.slf4j.info
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type
import org.objectweb.asm.tree.AbstractInsnNode
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.JumpInsnNode
import org.objectweb.asm.tree.LabelNode
import org.objectweb.asm.tree.MethodInsnNode
import org.objectweb.asm.tree.MethodNode
import org.objectweb.asm.tree.VarInsnNode
import org.runestar.client.updater.deob.Transformer
import org.runestar.client.updater.deob.util.intValue
import org.runestar.client.updater.deob.util.isIntValue
import java.lang.reflect.Modifier
import java.nio.file.Path
import java.util.TreeMap
object OpaquePredicateCheckRemover : Transformer.Tree() {
private val ISE_INTERNAL_NAME = Type.getInternalName(IllegalStateException::class.java)
private val mapper = jacksonObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
private val logger = getLogger()
override fun transform(dir: Path, klasses: List<ClassNode>) {
val passingArgs = TreeMap<String, Int>()
var returns = 0
var exceptions = 0
klasses.forEach { c ->
c.methods.forEach { m ->
val instructions = m.instructions.iterator()
val lastParamIndex = m.lastParamIndex
while (instructions.hasNext()) {
val insn = instructions.next()
val toDelete = if (insn.matchesReturn(lastParamIndex)) {
returns++
4
} else if (insn.matchesException(lastParamIndex)) {
exceptions++
7
} else {
continue
}
val constantPushed = insn.next.intValue
val ifOpcode = insn.next.next.opcode
val label = (insn.next.next as JumpInsnNode).label.label
instructions.remove()
repeat(toDelete - 1) {
instructions.next()
instructions.remove()
}
instructions.add(JumpInsnNode(GOTO, LabelNode(label)))
passingArgs["${c.name}.${m.name}${m.desc}"] = passingVal(constantPushed, ifOpcode)
}
}
}
logger.info { "Opaque predicates checks removed: returns: $returns, exceptions: $exceptions" }
mapper.writeValue(dir.resolve("op.json").toFile(), passingArgs)
}
private fun AbstractInsnNode.matchesReturn(lastParamIndex: Int): Boolean {
val i0 = this
if (i0.opcode != ILOAD) return false
i0 as VarInsnNode
if (i0.`var` != lastParamIndex) return false
val i1 = i0.next
if (!i1.isIntValue) return false
val i2 = i1.next
if (!i2.isIf) return false
val i3 = i2.next
if (!i3.isReturn) return false
return true
}
private fun AbstractInsnNode.matchesException(lastParamIndex: Int): Boolean {
val i0 = this
if (i0.opcode != ILOAD) return false
i0 as VarInsnNode
if (i0.`var` != lastParamIndex) return false
val i1 = i0.next
if (!i1.isIntValue) return false
val i2 = i1.next
if (!i2.isIf) return false
val i3 = i2.next
if (i3.opcode != NEW) return false
val i4 = i3.next
if (i4.opcode != DUP) return false
val i5 = i4.next
if (i5.opcode != INVOKESPECIAL) return false
i5 as MethodInsnNode
if (i5.owner != ISE_INTERNAL_NAME) return false
val i6 = i5.next
if (i6.opcode != ATHROW) return false
return true
}
private val MethodNode.lastParamIndex: Int get() {
val offset = if (Modifier.isStatic(access)) 1 else 0
return (Type.getArgumentsAndReturnSizes(desc) shr 2) - offset - 1
}
private fun passingVal(pushed: Int, ifOpcode: Int): Int {
return when(ifOpcode) {
IF_ICMPEQ -> pushed
IF_ICMPGE,
IF_ICMPGT -> pushed + 1
IF_ICMPLE,
IF_ICMPLT,
IF_ICMPNE -> pushed - 1
else -> error(ifOpcode)
}
}
private val AbstractInsnNode.isIf: Boolean get() {
return this is JumpInsnNode && opcode != Opcodes.GOTO
}
private val AbstractInsnNode.isReturn: Boolean get() {
return when (opcode) {
RETURN, ARETURN, DRETURN, FRETURN, IRETURN, LRETURN -> true
else -> false
}
}
} | mit | 8964dffdff822291daa40c7c1244eaf3 | 35.572519 | 102 | 0.601461 | 4.246454 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/OptInFixesFactory.kt | 3 | 14095 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.module.Module
import com.intellij.psi.SmartPsiElementPointer
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.resolveClassByFqName
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors.*
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.toDescriptor
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypesAndPredicate
import org.jetbrains.kotlin.resolve.AnnotationChecker
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.checkers.OptInNames
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
object OptInFixesFactory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val element = diagnostic.psiElement
val containingDeclaration: KtDeclaration = element.getParentOfTypesAndPredicate(
true,
KtDeclarationWithBody::class.java,
KtClassOrObject::class.java,
KtProperty::class.java,
KtTypeAlias::class.java
) {
!KtPsiUtil.isLocal(it)
} ?: return emptyList()
val annotationFqName = when (diagnostic.factory) {
OPT_IN_USAGE -> OPT_IN_USAGE.cast(diagnostic).a
OPT_IN_USAGE_ERROR -> OPT_IN_USAGE_ERROR.cast(diagnostic).a
OPT_IN_OVERRIDE -> OPT_IN_OVERRIDE.cast(diagnostic).a
OPT_IN_OVERRIDE_ERROR -> OPT_IN_OVERRIDE_ERROR.cast(diagnostic).a
else -> null
} ?: return emptyList()
val moduleDescriptor = containingDeclaration.resolveToDescriptorIfAny()?.module ?: return emptyList()
val annotationClassDescriptor = moduleDescriptor.resolveClassByFqName(
annotationFqName, NoLookupLocation.FROM_IDE
) ?: return emptyList()
val applicableTargets = AnnotationChecker.applicableTargetSet(annotationClassDescriptor)
val context = when (element) {
is KtElement -> element.analyze()
else -> containingDeclaration.analyze()
}
fun isApplicableTo(declaration: KtDeclaration): Boolean {
val actualTargetList = AnnotationChecker.getDeclarationSiteActualTargetList(
declaration, declaration.toDescriptor() as? ClassDescriptor, context
)
return actualTargetList.any { it in applicableTargets }
}
val isOverrideError = diagnostic.factory == OPT_IN_OVERRIDE_ERROR || diagnostic.factory == OPT_IN_OVERRIDE
val optInFqName = OptInNames.OPT_IN_FQ_NAME.takeIf { moduleDescriptor.annotationExists(it) }
?: OptInNames.OLD_USE_EXPERIMENTAL_FQ_NAME
val result = mutableListOf<IntentionAction>()
// just to avoid local variable name shadowing
run {
val kind = if (containingDeclaration is KtConstructor<*>)
AddAnnotationFix.Kind.Constructor
else
AddAnnotationFix.Kind.Declaration(containingDeclaration.name)
if (isApplicableTo(containingDeclaration)) {
// When we are fixing a missing annotation on an overridden function, we should
// propose to add a propagating annotation first, and in all other cases
// the non-propagating opt-in annotation should be default.
// The same logic applies to the similar conditional expressions onward.
result.add(
if (isOverrideError)
HighPriorityPropagateOptInAnnotationFix(containingDeclaration, annotationFqName, kind)
else
PropagateOptInAnnotationFix(containingDeclaration, annotationFqName, kind)
)
}
val existingAnnotationEntry = containingDeclaration.findAnnotation(optInFqName)?.createSmartPointer()
result.add(
if (isOverrideError)
UseOptInAnnotationFix(containingDeclaration, optInFqName, kind, annotationFqName, existingAnnotationEntry)
else
HighPriorityUseOptInAnnotationFix(containingDeclaration, optInFqName, kind, annotationFqName, existingAnnotationEntry)
)
}
if (containingDeclaration is KtCallableDeclaration) {
val containingClassOrObject = containingDeclaration.containingClassOrObject
if (containingClassOrObject != null) {
val kind = AddAnnotationFix.Kind.ContainingClass(containingClassOrObject.name)
val isApplicableToContainingClassOrObject = isApplicableTo(containingClassOrObject)
if (isApplicableToContainingClassOrObject) {
result.add(
if (isOverrideError)
HighPriorityPropagateOptInAnnotationFix(containingClassOrObject, annotationFqName, kind)
else
PropagateOptInAnnotationFix(containingClassOrObject, annotationFqName, kind)
)
}
val existingAnnotationEntry = containingClassOrObject.findAnnotation(optInFqName)?.createSmartPointer()
result.add(
if (isOverrideError)
UseOptInAnnotationFix(containingClassOrObject, optInFqName, kind, annotationFqName, existingAnnotationEntry)
else
HighPriorityUseOptInAnnotationFix(
containingClassOrObject, optInFqName, kind, annotationFqName, existingAnnotationEntry
)
)
}
}
val containingFile = containingDeclaration.containingKtFile
val module = containingFile.module
if (module != null) {
result.add(LowPriorityMakeModuleOptInFix(containingFile, module, annotationFqName))
}
// Add the file-level annotation `@file:OptIn(...)`
result.add(
UseOptInFileAnnotationFix(
containingFile, optInFqName, annotationFqName,
findFileAnnotation(containingFile, optInFqName)?.createSmartPointer()
)
)
return result
}
// Find the existing file-level annotation of the specified class if it exists
private fun findFileAnnotation(file: KtFile, annotationFqName: FqName): KtAnnotationEntry? {
val context = file.analyze(BodyResolveMode.PARTIAL)
return file.fileAnnotationList?.annotationEntries?.firstOrNull { entry ->
context.get(BindingContext.ANNOTATION, entry)?.fqName == annotationFqName
}
}
fun ModuleDescriptor.annotationExists(fqName: FqName): Boolean =
resolveClassByFqName(fqName, NoLookupLocation.FROM_IDE) != null
/**
* A specialized subclass of [AddAnnotationFix] that adds @OptIn(...) annotations to declarations,
* containing classes, or constructors.
*
* This class reuses the parent's [invoke] method but overrides the [getText] method to provide
* more descriptive opt-in-specific messages.
*
* @param element a declaration to annotate
* @param optInFqName name of OptIn annotation
* @param kind the annotation kind (desired scope)
* @param argumentClassFqName the fully qualified name of the annotation to opt-in
* @param existingAnnotationEntry the already existing annotation entry (if any)
*
*/
private open class UseOptInAnnotationFix(
element: KtDeclaration,
optInFqName: FqName,
private val kind: Kind,
private val argumentClassFqName: FqName,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : AddAnnotationFix(element, optInFqName, kind, argumentClassFqName, existingAnnotationEntry) {
private val elementName = element.name ?: "?"
override fun getText(): String {
val argumentText = argumentClassFqName.shortName().asString()
return when (kind) {
Kind.Self -> KotlinBundle.message("fix.opt_in.text.use.declaration", argumentText, elementName)
Kind.Constructor -> KotlinBundle.message("fix.opt_in.text.use.constructor", argumentText)
is Kind.Declaration -> KotlinBundle.message("fix.opt_in.text.use.declaration", argumentText, kind.name ?: "?")
is Kind.ContainingClass -> KotlinBundle.message("fix.opt_in.text.use.containing.class", argumentText, kind.name ?: "?")
}
}
override fun getFamilyName(): String = KotlinBundle.message("fix.opt_in.annotation.family")
}
private class HighPriorityUseOptInAnnotationFix(
element: KtDeclaration,
optInFqName: FqName,
kind: Kind,
argumentClassFqName: FqName,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : UseOptInAnnotationFix(element, optInFqName, kind, argumentClassFqName, existingAnnotationEntry),
HighPriorityAction
/**
* A specialized version of [AddFileAnnotationFix] that adds @OptIn(...) annotations to the containing file.
*
* This class reuses the parent's [invoke] method, but overrides the [getText] method to provide
* more descriptive opt-in related messages.
*
* @param file the file there the annotation should be added
* @param optInFqName name of OptIn annotation
* @param argumentClassFqName the fully qualified name of the annotation to opt-in
* @param existingAnnotationEntry the already existing annotation entry (if any)
*/
private open class UseOptInFileAnnotationFix(
file: KtFile,
optInFqName: FqName,
private val argumentClassFqName: FqName,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>?
) : AddFileAnnotationFix(file, optInFqName, argumentClassFqName, existingAnnotationEntry) {
private val fileName = file.name
override fun getText(): String {
val argumentText = argumentClassFqName.shortName().asString()
return KotlinBundle.message("fix.opt_in.text.use.containing.file", argumentText, fileName)
}
override fun getFamilyName(): String = KotlinBundle.message("fix.opt_in.annotation.family")
}
/**
* A specialized subclass of [AddAnnotationFix] that adds propagating opted-in annotations
* to declarations, containing classes, or constructors.
*
* This class reuses the parent's [invoke] method but overrides the [getText] method to provide
* more descriptive opt-in-specific messages.
*
* @param element a declaration to annotate
* @param annotationFqName the fully qualified name of the annotation
* @param kind the annotation kind (desired scope)
* @param existingAnnotationEntry the already existing annotation entry (if any)
*
*/
private open class PropagateOptInAnnotationFix(
element: KtDeclaration,
private val annotationFqName: FqName,
private val kind: Kind,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : AddAnnotationFix(element, annotationFqName, Kind.Self, null, existingAnnotationEntry) {
override fun getText(): String {
val argumentText = annotationFqName.shortName().asString()
return when (kind) {
Kind.Self -> KotlinBundle.message("fix.opt_in.text.propagate.declaration", argumentText, "?")
Kind.Constructor -> KotlinBundle.message("fix.opt_in.text.propagate.constructor", argumentText)
is Kind.Declaration -> KotlinBundle.message("fix.opt_in.text.propagate.declaration", argumentText, kind.name ?: "?")
is Kind.ContainingClass -> KotlinBundle.message(
"fix.opt_in.text.propagate.containing.class",
argumentText,
kind.name ?: "?"
)
}
}
override fun getFamilyName(): String = KotlinBundle.message("fix.opt_in.annotation.family")
}
/**
* A high-priority version of [PropagateOptInAnnotationFix] (for overridden constructor case)
*
* @param element a declaration to annotate
* @param annotationFqName the fully qualified name of the annotation
* @param kind the annotation kind (desired scope)
* @param existingAnnotationEntry the already existing annotation entry (if any)
*/
private class HighPriorityPropagateOptInAnnotationFix(
element: KtDeclaration,
annotationFqName: FqName,
kind: Kind,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : PropagateOptInAnnotationFix(element, annotationFqName, kind, existingAnnotationEntry),
HighPriorityAction
private class LowPriorityMakeModuleOptInFix(
file: KtFile,
module: Module,
annotationFqName: FqName
) : MakeModuleOptInFix(file, module, annotationFqName), LowPriorityAction
}
| apache-2.0 | 1af975cccc86078b5c70ae4bbf7c137b | 47.940972 | 138 | 0.685917 | 5.53831 | false | false | false | false |
google/intellij-community | plugins/devkit/devkit-core/src/inspections/NonDefaultConstructorInspection.kt | 5 | 12680 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.devkit.inspections
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.lang.jvm.JvmClassKind
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiParameterList
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.psi.xml.XmlTag
import com.intellij.util.SmartList
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.idea.devkit.dom.Extension
import org.jetbrains.idea.devkit.dom.ExtensionPoint
import org.jetbrains.idea.devkit.dom.ExtensionPoint.Area
import org.jetbrains.idea.devkit.util.locateExtensionsByPsiClass
import org.jetbrains.idea.devkit.util.processExtensionDeclarations
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UMethod
import org.jetbrains.uast.UastFacade
import org.jetbrains.uast.convertOpt
import java.util.*
private const val serviceBeanFqn = "com.intellij.openapi.components.ServiceDescriptor"
class NonDefaultConstructorInspection : DevKitUastInspectionBase(UClass::class.java) {
override fun checkClass(aClass: UClass, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
val javaPsi = aClass.javaPsi
// Groovy from test data - ignore it
if (javaPsi.language.id == "Groovy" || javaPsi.classKind != JvmClassKind.CLASS ||
PsiUtil.isInnerClass(javaPsi) || PsiUtil.isLocalOrAnonymousClass(javaPsi) || PsiUtil.isAbstractClass(javaPsi) ||
javaPsi.hasModifierProperty(PsiModifier.PRIVATE) /* ignore private classes */) {
return null
}
val constructors = javaPsi.constructors
// very fast path - do nothing if no constructors
if (constructors.isEmpty()) {
return null
}
val area: Area?
val isService: Boolean
var serviceClientKind: ServiceDescriptor.ClientKind? = null
// hack, allow Project-level @Service
var isServiceAnnotation = false
var extensionPoint: ExtensionPoint? = null
if (javaPsi.hasAnnotation("com.intellij.openapi.components.Service")) {
area = null
isService = true
isServiceAnnotation = true
}
else {
// fast path - check by qualified name
if (!isExtensionBean(aClass)) {
// slow path - check using index
extensionPoint = findExtensionPoint(aClass, manager.project) ?: return null
}
else if (javaPsi.name == "VcsConfigurableEP") {
// VcsConfigurableEP extends ConfigurableEP but used directly, for now just ignore it as hardcoded exclusion
return null
}
area = getArea(extensionPoint)
isService = extensionPoint?.beanClass?.stringValue == serviceBeanFqn
if (isService) {
for (candidate in locateExtensionsByPsiClass(javaPsi)) {
val extensionTag = candidate.pointer.element ?: continue
val clientName = extensionTag.getAttribute("client")?.value ?: continue
val kind = when (clientName.lowercase(Locale.US)) {
"all" -> ServiceDescriptor.ClientKind.ALL
"guest" -> ServiceDescriptor.ClientKind.GUEST
"local" -> ServiceDescriptor.ClientKind.LOCAL
else -> null
}
if (serviceClientKind == null) {
serviceClientKind = kind
}
else if (serviceClientKind != kind) {
serviceClientKind = ServiceDescriptor.ClientKind.ALL
}
}
}
}
val isAppLevelExtensionPoint = area == null || area == Area.IDEA_APPLICATION
var errors: MutableList<ProblemDescriptor>? = null
loop@ for (method in constructors) {
if (isAllowedParameters(method.parameterList, extensionPoint, isAppLevelExtensionPoint, serviceClientKind, isServiceAnnotation)) {
// allow to have empty constructor and extra (e.g. DartQuickAssistIntention)
return null
}
if (errors == null) {
errors = SmartList()
}
// kotlin is not physical, but here only physical is expected, so, convert to uast element and use sourcePsi
val anchorElement = when {
method.isPhysical -> method.identifyingElement!!
else -> aClass.sourcePsi?.let { UastFacade.findPlugin(it)?.convertOpt<UMethod>(method, aClass)?.sourcePsi } ?: continue@loop
}
@NlsSafe val kind = if (isService) DevKitBundle.message("inspections.non.default.warning.type.service") else DevKitBundle.message("inspections.non.default.warning.type.extension")
@Nls val suffix =
if (area == null) DevKitBundle.message("inspections.non.default.warning.suffix.project.or.module")
else {
when {
isAppLevelExtensionPoint -> ""
area == Area.IDEA_PROJECT -> DevKitBundle.message("inspections.non.default.warning.suffix.project")
else -> DevKitBundle.message("inspections.non.default.warning.suffix.module")
}
}
errors.add(manager.createProblemDescriptor(anchorElement,
DevKitBundle.message("inspections.non.default.warning.and.suffix.message", kind, suffix),
true,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly))
}
return errors?.toTypedArray()
}
private fun getArea(extensionPoint: ExtensionPoint?): Area {
val areaName = (extensionPoint ?: return Area.IDEA_APPLICATION).area.stringValue
when (areaName) {
"IDEA_PROJECT" -> return Area.IDEA_PROJECT
"IDEA_MODULE" -> return Area.IDEA_MODULE
else -> {
when (extensionPoint.name.value) {
"projectService" -> return Area.IDEA_PROJECT
"moduleService" -> return Area.IDEA_MODULE
}
}
}
return Area.IDEA_APPLICATION
}
}
private fun findExtensionPoint(clazz: UClass, project: Project): ExtensionPoint? {
val parentClass = clazz.uastParent as? UClass
if (parentClass == null) {
val qualifiedName = clazz.qualifiedName ?: return null
return findExtensionPointByImplementationClass(qualifiedName, qualifiedName, project)
}
else {
val parentQualifiedName = parentClass.qualifiedName ?: return null
// parent$inner string cannot be found, so, search by parent FQN
return findExtensionPointByImplementationClass(parentQualifiedName, "$parentQualifiedName$${clazz.javaPsi.name}", project)
}
}
private fun findExtensionPointByImplementationClass(searchString: String, qualifiedName: String, project: Project): ExtensionPoint? {
var result: ExtensionPoint? = null
val strictMatch = searchString === qualifiedName
processExtensionDeclarations(searchString, project, strictMatch = strictMatch) { extension, tag ->
val point = extension.extensionPoint ?: return@processExtensionDeclarations true
if (point.name.value == "psi.symbolReferenceProvider") {
return@processExtensionDeclarations true
}
when (point.beanClass.stringValue) {
null -> {
if (tag.attributes.any { it.name == Extension.IMPLEMENTATION_ATTRIBUTE && it.value == qualifiedName }) {
result = point
return@processExtensionDeclarations false
}
}
serviceBeanFqn -> {
if (tag.attributes.any { it.name == "serviceImplementation" && it.value == qualifiedName }) {
result = point
return@processExtensionDeclarations false
}
}
else -> {
// bean EP
if (tag.name == "className" || tag.subTags.any {
it.name == "className" && (strictMatch || it.textMatches(qualifiedName))
} || checkAttributes(tag, qualifiedName)) {
result = point
return@processExtensionDeclarations false
}
}
}
true
}
return result
}
// todo can we use attribute `with`?
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
@NonNls
private val ignoredTagNames = java.util.Set.of("semContributor", "modelFacade", "scriptGenerator",
"editorActionHandler", "editorTypedHandler",
"dataImporter", "java.error.fix", "explainPlanProvider", "typeIcon")
// problem - tag
//<lang.elementManipulator forClass="com.intellij.psi.css.impl.CssTokenImpl"
// implementationClass="com.intellij.psi.css.impl.CssTokenImpl$Manipulator"/>
// will be found for `com.intellij.psi.css.impl.CssTokenImpl`, but we need to ignore `forClass` and check that we have exact match for implementation attribute
private fun checkAttributes(tag: XmlTag, qualifiedName: String): Boolean {
if (ignoredTagNames.contains(tag.name)) {
// DbmsExtension passes Dbms instance directly, doesn't need to check
return false
}
return tag.attributes.any {
val name = it.name
(name.startsWith(Extension.IMPLEMENTATION_ATTRIBUTE) || name == "instance") && it.value == qualifiedName
}
}
@NonNls
private val allowedClientSessionsQualifiedNames = setOf(
"com.intellij.openapi.client.ClientSession",
"com.jetbrains.rdserver.core.GuestSession",
)
@NonNls
private val allowedClientAppSessionsQualifiedNames = setOf(
"com.intellij.openapi.client.ClientAppSession",
"com.jetbrains.rdserver.core.GuestAppSession",
) + allowedClientSessionsQualifiedNames
@NonNls
private val allowedClientProjectSessionsQualifiedNames = setOf(
"com.intellij.openapi.client.ClientProjectSession",
"com.jetbrains.rdserver.core.GuestProjectSession",
) + allowedClientSessionsQualifiedNames
@NonNls
private val allowedServiceQualifiedNames = setOf(
"com.intellij.openapi.project.Project",
"com.intellij.openapi.module.Module",
"com.intellij.util.messages.MessageBus",
"com.intellij.openapi.options.SchemeManagerFactory",
"com.intellij.openapi.editor.actionSystem.TypedActionHandler",
"com.intellij.database.Dbms"
) + allowedClientAppSessionsQualifiedNames + allowedClientProjectSessionsQualifiedNames
private val allowedServiceNames = allowedServiceQualifiedNames.mapTo(HashSet(allowedServiceQualifiedNames.size)) { it.substringAfterLast('.') }
private fun isAllowedParameters(list: PsiParameterList,
extensionPoint: ExtensionPoint?,
isAppLevelExtensionPoint: Boolean,
clientKind: ServiceDescriptor.ClientKind?,
isServiceAnnotation: Boolean): Boolean {
if (list.isEmpty) {
return true
}
// hardcoded for now, later will be generalized
if (!isServiceAnnotation && extensionPoint?.effectiveQualifiedName == "com.intellij.semContributor") {
// disallow any parameters
return false
}
for (parameter in list.parameters) {
if (parameter.isVarArgs) {
return false
}
val type = parameter.type as? PsiClassType ?: return false
// before resolve, check unqualified name
val name = type.className
if (!allowedServiceNames.contains(name)) {
return false
}
val qualifiedName = (type.resolve() ?: return false).qualifiedName
if (!allowedServiceQualifiedNames.contains(qualifiedName)) {
return false
}
if (clientKind != ServiceDescriptor.ClientKind.GUEST &&
qualifiedName?.startsWith("com.jetbrains.rdserver.core") == true) {
return false
}
if (clientKind == null && allowedClientProjectSessionsQualifiedNames.contains(qualifiedName)) {
return false
}
if (isAppLevelExtensionPoint && !isServiceAnnotation && name == "Project") {
return false
}
}
return true
}
private val interfacesToCheck = HashSet(listOf(
"com.intellij.codeInsight.daemon.LineMarkerProvider",
"com.intellij.openapi.fileTypes.SyntaxHighlighterFactory"
))
private val classesToCheck = HashSet(listOf(
"com.intellij.codeInsight.completion.CompletionContributor",
"com.intellij.codeInsight.completion.CompletionConfidence",
"com.intellij.psi.PsiReferenceContributor"
))
private fun isExtensionBean(aClass: UClass): Boolean {
var found = false
InheritanceUtil.processSupers(aClass.javaPsi, true) {
val qualifiedName = it.qualifiedName
found = (if (it.isInterface) interfacesToCheck else classesToCheck).contains(qualifiedName)
!found
}
return found
} | apache-2.0 | 3a3ac4083b7bbc5b47066105759acd07 | 38.628125 | 185 | 0.702208 | 4.966706 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/ClanChat.kt | 1 | 3695 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.common.startsWith
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type.BYTE_TYPE
import org.objectweb.asm.Type.INT_TYPE
import org.objectweb.asm.Type.VOID_TYPE
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
import org.runestar.client.updater.mapper.Instruction2
import org.runestar.client.updater.mapper.Method2
import java.lang.reflect.Modifier
@DependsOn(UserList::class, ClanMate::class)
class ClanChat : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == type<UserList>() }
.and { it.instanceMethods.flatMap { it.instructions.toList() }.any { it.opcode == NEW && it.typeType == type<ClanMate>() } }
@DependsOn(UserList.newInstance::class)
class newInstance : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<UserList.newInstance>().mark }
}
@DependsOn(UserList.newTypedArray::class)
class newTypedArray : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<UserList.newTypedArray>().mark }
}
@DependsOn(LoginType::class)
class loginType : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<LoginType>() }
}
class minKick : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == BYTE_TYPE }
}
class name : OrderMapper.InConstructor.Field(ClanChat::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == String::class.type }
}
class owner : OrderMapper.InConstructor.Field(ClanChat::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == String::class.type }
}
@MethodParameters("packet")
@DependsOn(Packet::class)
class readUpdate : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.arguments.startsWith(type<Packet>()) }
.and { it.instructions.any { it.opcode == IINC } }
}
@DependsOn(Usernamed::class)
class localUser : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<Usernamed>() }
}
class rank : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == INT_TYPE && Modifier.isPublic(it.access) }
}
@MethodParameters()
@DependsOn(ClanMate.clearIsFriend::class)
class clearFriends : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE && it.arguments.isEmpty() }
.and { it.instructions.any { it.isMethod && it.methodId == method<ClanMate.clearIsFriend>().id } }
}
@MethodParameters()
@DependsOn(ClanMate.clearIsIgnored::class)
class clearIgnoreds : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE && it.arguments.isEmpty() }
.and { it.instructions.any { it.isMethod && it.methodId == method<ClanMate.clearIsIgnored>().id } }
}
} | mit | b89f33a501db469f4fa8d5751522b58b | 43.53012 | 136 | 0.713938 | 4.096452 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/pullUpConflictsUtils.kt | 2 | 13612 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.pullUp
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.RefactoringBundle
import com.intellij.util.containers.MultiMap
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.getChildrenToAnalyze
import org.jetbrains.kotlin.idea.refactoring.memberInfo.resolveToDescriptorWrapperAware
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.languageVersionSettings
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.base.util.useScope
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.ParameterNameRenderingPolicy
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.util.findCallableMemberBySignature
fun checkConflicts(
project: Project,
sourceClass: KtClassOrObject,
targetClass: PsiNamedElement,
memberInfos: List<KotlinMemberInfo>,
onShowConflicts: () -> Unit = {},
onAccept: () -> Unit
) {
val conflicts = MultiMap<PsiElement, String>()
val conflictsCollected = runProcessWithProgressSynchronously(RefactoringBundle.message("detecting.possible.conflicts"), project) {
runReadAction { collectConflicts(sourceClass, targetClass, memberInfos, conflicts) }
}
if (conflictsCollected) {
project.checkConflictsInteractively(conflicts, onShowConflicts, onAccept)
} else {
onShowConflicts()
}
}
private fun runProcessWithProgressSynchronously(
progressTitle: @NlsContexts.ProgressTitle String,
project: Project?,
process: Runnable,
): Boolean = ProgressManager.getInstance().runProcessWithProgressSynchronously(process, progressTitle, true, project)
private fun collectConflicts(
sourceClass: KtClassOrObject,
targetClass: PsiNamedElement,
memberInfos: List<KotlinMemberInfo>,
conflicts: MultiMap<PsiElement, String>
) {
val pullUpData = KotlinPullUpData(sourceClass,
targetClass,
memberInfos.mapNotNull { it.member })
with(pullUpData) {
for (memberInfo in memberInfos) {
val member = memberInfo.member
val memberDescriptor = member.resolveToDescriptorWrapperAware(resolutionFacade)
checkClashWithSuperDeclaration(member, memberDescriptor, conflicts)
checkAccidentalOverrides(member, memberDescriptor, conflicts)
checkInnerClassToInterface(member, memberDescriptor, conflicts)
checkVisibility(memberInfo, memberDescriptor, conflicts, resolutionFacade.languageVersionSettings)
}
}
checkVisibilityInAbstractedMembers(memberInfos, pullUpData.resolutionFacade, conflicts)
}
internal fun checkVisibilityInAbstractedMembers(
memberInfos: List<KotlinMemberInfo>,
resolutionFacade: ResolutionFacade,
conflicts: MultiMap<PsiElement, String>
) {
val membersToMove = ArrayList<KtNamedDeclaration>()
val membersToAbstract = ArrayList<KtNamedDeclaration>()
for (memberInfo in memberInfos) {
val member = memberInfo.member ?: continue
(if (memberInfo.isToAbstract) membersToAbstract else membersToMove).add(member)
}
for (member in membersToAbstract) {
val memberDescriptor = member.resolveToDescriptorWrapperAware(resolutionFacade)
member.forEachDescendantOfType<KtSimpleNameExpression> {
val target = it.mainReference.resolve() as? KtNamedDeclaration ?: return@forEachDescendantOfType
if (!willBeMoved(target, membersToMove)) return@forEachDescendantOfType
if (target.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
val targetDescriptor = target.resolveToDescriptorWrapperAware(resolutionFacade)
val memberText = memberDescriptor.renderForConflicts()
val targetText = targetDescriptor.renderForConflicts()
val message = KotlinBundle.message("text.0.uses.1.which.will.not.be.accessible.from.subclass", memberText, targetText)
conflicts.putValue(target, message.capitalize())
}
}
}
}
internal fun willBeMoved(element: PsiElement, membersToMove: Collection<KtNamedDeclaration>) =
element.parentsWithSelf.any { it in membersToMove }
internal fun willBeUsedInSourceClass(
member: PsiElement,
sourceClass: KtClassOrObject,
membersToMove: Collection<KtNamedDeclaration>
): Boolean {
return !ReferencesSearch
.search(member, LocalSearchScope(sourceClass), false)
.all { willBeMoved(it.element, membersToMove) }
}
private val CALLABLE_RENDERER = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions {
parameterNameRenderingPolicy = ParameterNameRenderingPolicy.NONE
modifiers = emptySet()
startFromName = false
}
@Nls
fun DeclarationDescriptor.renderForConflicts(): String {
return when (this) {
is ClassDescriptor -> {
@NlsSafe val text = "${DescriptorRenderer.getClassifierKindPrefix(this)} " +
IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(this)
text
}
is FunctionDescriptor -> {
KotlinBundle.message("text.function.in.ticks.0", CALLABLE_RENDERER.render(this))
}
is PropertyDescriptor -> {
KotlinBundle.message("text.property.in.ticks.0", CALLABLE_RENDERER.render(this))
}
is PackageFragmentDescriptor -> {
@NlsSafe val text = fqName.asString()
text
}
is PackageViewDescriptor -> {
@NlsSafe val text = fqName.asString()
text
}
else -> {
""
}
}
}
internal fun KotlinPullUpData.getClashingMemberInTargetClass(memberDescriptor: CallableMemberDescriptor): CallableMemberDescriptor? {
val memberInSuper = memberDescriptor.substitute(sourceToTargetClassSubstitutor) ?: return null
return targetClassDescriptor.findCallableMemberBySignature(memberInSuper as CallableMemberDescriptor)
}
private fun KotlinPullUpData.checkClashWithSuperDeclaration(
member: KtNamedDeclaration,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>
) {
val message = KotlinBundle.message(
"text.class.0.already.contains.member.1",
targetClassDescriptor.renderForConflicts(),
memberDescriptor.renderForConflicts()
)
if (member is KtParameter) {
if (((targetClass as? KtClass)?.primaryConstructorParameters ?: emptyList()).any { it.name == member.name }) {
conflicts.putValue(member, message.capitalize())
}
return
}
if (memberDescriptor !is CallableMemberDescriptor) return
val clashingSuper = getClashingMemberInTargetClass(memberDescriptor) ?: return
if (clashingSuper.modality == Modality.ABSTRACT) return
if (clashingSuper.kind != CallableMemberDescriptor.Kind.DECLARATION) return
conflicts.putValue(member, message.capitalize())
}
private fun PsiClass.isSourceOrTarget(data: KotlinPullUpData): Boolean {
var element = unwrapped
if (element is KtObjectDeclaration && element.isCompanion()) element = element.containingClassOrObject
return element == data.sourceClass || element == data.targetClass
}
private fun KotlinPullUpData.checkAccidentalOverrides(
member: KtNamedDeclaration,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>
) {
if (memberDescriptor is CallableDescriptor && !member.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
val memberDescriptorInTargetClass = memberDescriptor.substitute(sourceToTargetClassSubstitutor)
if (memberDescriptorInTargetClass != null) {
val sequence = HierarchySearchRequest<PsiElement>(targetClass, targetClass.useScope())
.searchInheritors()
.asSequence()
.filterNot { it.isSourceOrTarget(this) }
.mapNotNull { it.unwrapped as? KtClassOrObject }
for (it in sequence) {
val subClassDescriptor = it.resolveToDescriptorWrapperAware(resolutionFacade) as ClassDescriptor
val substitution = getTypeSubstitution(targetClassDescriptor.defaultType, subClassDescriptor.defaultType).orEmpty()
val memberDescriptorInSubClass = memberDescriptorInTargetClass.substitute(substitution) as? CallableMemberDescriptor
val clashingMemberDescriptor = memberDescriptorInSubClass?.let {
subClassDescriptor.findCallableMemberBySignature(it)
} ?: continue
val clashingMember = clashingMemberDescriptor.source.getPsi() ?: continue
val message = KotlinBundle.message(
"text.member.0.in.super.class.will.clash.with.existing.member.of.1",
memberDescriptor.renderForConflicts(),
it.resolveToDescriptorWrapperAware(resolutionFacade).renderForConflicts()
)
conflicts.putValue(clashingMember, message.capitalize())
}
}
}
}
private fun KotlinPullUpData.checkInnerClassToInterface(
member: KtNamedDeclaration,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>
) {
if (isInterfaceTarget && memberDescriptor is ClassDescriptor && memberDescriptor.isInner) {
val message = KotlinBundle.message("text.inner.class.0.cannot.be.moved.to.intefrace", memberDescriptor.renderForConflicts())
conflicts.putValue(member, message.capitalize())
}
}
private fun KotlinPullUpData.checkVisibility(
memberInfo: KotlinMemberInfo,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>,
languageVersionSettings: LanguageVersionSettings
) {
fun reportConflictIfAny(targetDescriptor: DeclarationDescriptor, languageVersionSettings: LanguageVersionSettings) {
if (targetDescriptor in memberDescriptors.values) return
val target = (targetDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() ?: return
if (targetDescriptor is DeclarationDescriptorWithVisibility
&& !DescriptorVisibilityUtils.isVisibleIgnoringReceiver(targetDescriptor, targetClassDescriptor, languageVersionSettings)
) {
val message = RefactoringBundle.message(
"0.uses.1.which.is.not.accessible.from.the.superclass",
memberDescriptor.renderForConflicts(),
targetDescriptor.renderForConflicts()
)
conflicts.putValue(target, message.capitalize())
}
}
val member = memberInfo.member
val childrenToCheck = memberInfo.getChildrenToAnalyze()
if (memberInfo.isToAbstract && member is KtCallableDeclaration) {
if (member.typeReference == null) {
(memberDescriptor as CallableDescriptor).returnType?.let { returnType ->
val typeInTargetClass = sourceToTargetClassSubstitutor.substitute(returnType, Variance.INVARIANT)
val descriptorToCheck = typeInTargetClass?.constructor?.declarationDescriptor as? ClassDescriptor
if (descriptorToCheck != null) {
reportConflictIfAny(descriptorToCheck, languageVersionSettings)
}
}
}
}
childrenToCheck.forEach { children ->
children.accept(
object : KtTreeVisitorVoid() {
override fun visitReferenceExpression(expression: KtReferenceExpression) {
super.visitReferenceExpression(expression)
val context = resolutionFacade.analyze(expression)
expression.references
.flatMap { (it as? KtReference)?.resolveToDescriptors(context) ?: emptyList() }
.forEach { reportConflictIfAny(it, languageVersionSettings) }
}
}
)
}
}
| apache-2.0 | f4d514e0ce9d45247391e9ce4e293655 | 43.338762 | 158 | 0.725022 | 5.497577 | false | false | false | false |
square/okhttp | okhttp-testing-support/src/main/kotlin/okhttp3/DelegatingSSLSocketFactory.kt | 4 | 2789 | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import java.io.IOException
import java.net.InetAddress
import java.net.Socket
import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory
/**
* A [SSLSocketFactory] that delegates calls. Sockets can be configured after creation by
* overriding [.configureSocket].
*/
open class DelegatingSSLSocketFactory(private val delegate: SSLSocketFactory) : SSLSocketFactory() {
@Throws(IOException::class)
override fun createSocket(): SSLSocket {
val sslSocket = delegate.createSocket() as SSLSocket
return configureSocket(sslSocket)
}
@Throws(IOException::class)
override fun createSocket(host: String, port: Int): SSLSocket {
val sslSocket = delegate.createSocket(host, port) as SSLSocket
return configureSocket(sslSocket)
}
@Throws(IOException::class)
override fun createSocket(
host: String, port: Int, localAddress: InetAddress, localPort: Int
): SSLSocket {
val sslSocket = delegate.createSocket(host, port, localAddress, localPort) as SSLSocket
return configureSocket(sslSocket)
}
@Throws(IOException::class)
override fun createSocket(host: InetAddress, port: Int): SSLSocket {
val sslSocket = delegate.createSocket(host, port) as SSLSocket
return configureSocket(sslSocket)
}
@Throws(IOException::class)
override fun createSocket(
host: InetAddress, port: Int, localAddress: InetAddress, localPort: Int
): SSLSocket {
val sslSocket = delegate.createSocket(host, port, localAddress, localPort) as SSLSocket
return configureSocket(sslSocket)
}
override fun getDefaultCipherSuites(): Array<String> {
return delegate.defaultCipherSuites
}
override fun getSupportedCipherSuites(): Array<String> {
return delegate.supportedCipherSuites
}
@Throws(IOException::class)
override fun createSocket(
socket: Socket, host: String, port: Int, autoClose: Boolean
): SSLSocket {
val sslSocket = delegate.createSocket(socket, host, port, autoClose) as SSLSocket
return configureSocket(sslSocket)
}
@Throws(IOException::class)
protected open fun configureSocket(sslSocket: SSLSocket): SSLSocket {
// No-op by default.
return sslSocket
}
}
| apache-2.0 | 262ae25e4b9c01216bfd967c42a818ca | 32.202381 | 100 | 0.74507 | 4.527597 | false | true | false | false |
JetBrains/intellij-community | java/java-impl/src/com/intellij/lang/java/actions/CreateMethodAction.kt | 1 | 7283 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.lang.java.actions
import com.intellij.codeInsight.CodeInsightUtil.positionCursor
import com.intellij.codeInsight.CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement
import com.intellij.codeInsight.daemon.QuickFixBundle.message
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.setupEditor
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.setupMethodBody
import com.intellij.codeInsight.daemon.impl.quickfix.GuessTypeParameters
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo
import com.intellij.codeInsight.intention.preview.IntentionPreviewUtils
import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.TemplateBuilder
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInsight.template.TemplateEditingAdapter
import com.intellij.lang.java.request.CreateMethodFromJavaUsageRequest
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.*
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.presentation.java.ClassPresentationUtil.getNameForClass
import com.intellij.psi.util.JavaElementKind
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil.setModifierProperty
/**
* @param abstract whether this action creates a method with explicit abstract modifier
*/
internal class CreateMethodAction(
targetClass: PsiClass,
override val request: CreateMethodRequest,
private val abstract: Boolean
) : CreateMemberAction(targetClass, request), JvmGroupIntentionAction {
override fun getActionGroup(): JvmActionGroup = if (abstract) CreateAbstractMethodActionGroup else CreateMethodActionGroup
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
return super.isAvailable(project, editor, file) && PsiNameHelper.getInstance(project).isIdentifier(request.methodName)
}
override fun getRenderData() = JvmActionGroup.RenderData { request.methodName }
override fun getFamilyName(): String = message("create.method.from.usage.family")
override fun getText(): String {
val what = request.methodName
val where = getNameForClass(target, false)
val kind = if (abstract) JavaElementKind.ABSTRACT_METHOD else JavaElementKind.METHOD
return message("create.element.in.class", kind.`object`(), what, where)
}
override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo {
val copyClass = PsiTreeUtil.findSameElementInCopy(target, file)
val previewRequest = if (request is CreateMethodFromJavaUsageRequest) {
val physicalRequest = request as? CreateMethodFromJavaUsageRequest ?: return IntentionPreviewInfo.EMPTY
val copyCall = PsiTreeUtil.findSameElementInCopy(physicalRequest.call, file)
CreateMethodFromJavaUsageRequest(copyCall, physicalRequest.modifiers)
} else request
JavaMethodRenderer(project, abstract, copyClass, previewRequest).doMagic()
return IntentionPreviewInfo.DIFF
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
JavaMethodRenderer(project, abstract, target, request).doMagic()
}
}
private class JavaMethodRenderer(
val project: Project,
val abstract: Boolean,
val targetClass: PsiClass,
val request: CreateMethodRequest
) {
val factory = JavaPsiFacade.getElementFactory(project)!!
val requestedModifiers = request.modifiers
val javaUsage = request as? CreateMethodFromJavaUsageRequest
val withoutBody = abstract || targetClass.isInterface && JvmModifier.STATIC !in requestedModifiers
fun doMagic() {
var method = renderMethod()
method = insertMethod(method)
method = forcePsiPostprocessAndRestoreElement(method) ?: return
val builder = setupTemplate(method)
method = forcePsiPostprocessAndRestoreElement(method) ?: return
val template = builder.buildInlineTemplate()
startTemplate(method, template)
}
fun renderMethod(): PsiMethod {
val method = factory.createMethod(request.methodName, PsiType.VOID)
val modifiersToRender = requestedModifiers.toMutableList()
if (targetClass.isInterface) {
modifiersToRender -= (visibilityModifiers + JvmModifier.ABSTRACT)
}
else if (abstract) {
if (modifiersToRender.remove(JvmModifier.PRIVATE)) {
modifiersToRender += JvmModifier.PROTECTED
}
modifiersToRender += JvmModifier.ABSTRACT
}
for (modifier in modifiersToRender) {
setModifierProperty(method, modifier.toPsiModifier(), true)
}
for (annotation in request.annotations) {
method.modifierList.addAnnotation(annotation.qualifiedName)
}
if (withoutBody) method.body?.delete()
return method
}
private fun insertMethod(method: PsiMethod): PsiMethod {
val anchor = javaUsage?.getAnchor(targetClass)
val inserted = if (anchor == null) {
targetClass.add(method)
}
else {
targetClass.addAfter(method, anchor)
}
return inserted as PsiMethod
}
private fun setupTemplate(method: PsiMethod): TemplateBuilderImpl {
val builder = TemplateBuilderImpl(method)
createTemplateContext(builder).run {
setupTypeElement(method.returnTypeElement, request.returnType)
setupParameters(method, request.expectedParameters)
}
builder.setEndVariableAfter(method.body ?: method)
return builder
}
private fun createTemplateContext(builder: TemplateBuilder): TemplateContext {
val substitutor = request.targetSubstitutor.toPsiSubstitutor(project)
val guesser = GuessTypeParameters(project, factory, builder, substitutor)
return TemplateContext(project, factory, targetClass, builder, guesser, javaUsage?.context)
}
private fun startTemplate(method: PsiMethod, template: Template) {
val targetFile = targetClass.containingFile
val newEditor = positionCursor(project, targetFile, method) ?: return
val templateListener = if (withoutBody) null else MyMethodBodyListener(project, newEditor, targetFile)
CreateFromUsageBaseFix.startTemplate(newEditor, template, project, templateListener, null)
}
}
private class MyMethodBodyListener(val project: Project, val editor: Editor, val file: PsiFile) : TemplateEditingAdapter() {
override fun templateFinished(template: Template, brokenOff: Boolean) {
if (brokenOff) return
PsiDocumentManager.getInstance(project).commitDocument(editor.document)
val offset = editor.caretModel.offset
val method = PsiTreeUtil.findElementOfClassAtOffset(file, offset - 1, PsiMethod::class.java, false) ?: return
if (IntentionPreviewUtils.isIntentionPreviewActive()) {
finishTemplate(method)
} else {
WriteCommandAction.runWriteCommandAction(project, message("create.method.body"), null, { finishTemplate(method) }, file)
}
}
private fun finishTemplate(method: PsiMethod) {
setupMethodBody(method)
setupEditor(method, editor)
}
}
| apache-2.0 | d59e327c726dee1a17086685a8ddc2e7 | 41.098266 | 126 | 0.780722 | 4.881367 | false | false | false | false |
exercism/xkotlin | exercises/practice/clock/src/test/kotlin/ClockCreationTest.kt | 1 | 2396 | import org.junit.Ignore
import org.junit.Test
import kotlin.test.assertEquals
class ClockCreationTest {
@Test
fun `on the hour`() = assertEquals("08:00", Clock(8, 0).toString())
@Ignore
@Test
fun `past the hour`() = assertEquals("11:09", Clock(11, 9).toString())
@Ignore
@Test
fun `midnight is zero hours`() = assertEquals("00:00", Clock(24, 0).toString())
@Ignore
@Test
fun `hour rolls over`() = assertEquals("01:00", Clock(25, 0).toString())
@Ignore
@Test
fun `hour rolls over continuously`() = assertEquals("04:00", Clock(100, 0).toString())
@Ignore
@Test
fun `sixty minutes is next hour`() = assertEquals("02:00", Clock(1, 60).toString())
@Ignore
@Test
fun `minutes roll over`() = assertEquals("02:40", Clock(0, 160).toString())
@Ignore
@Test
fun `minutes roll over continuously`() = assertEquals("04:43", Clock(0, 1723).toString())
@Ignore
@Test
fun `hour and minutes roll over`() = assertEquals("03:40", Clock(25, 160).toString())
@Ignore
@Test
fun `hour and minutes roll over continuously`() = assertEquals("11:01", Clock(201, 3001).toString())
@Ignore
@Test
fun `hour and minutes roll over to exactly midnight`() = assertEquals("00:00", Clock(72, 8640).toString())
@Ignore
@Test
fun `negative hour`() = assertEquals("23:15", Clock(-1, 15).toString())
@Ignore
@Test
fun `negative hour rolls over`() = assertEquals("23:00", Clock(-25, 0).toString())
@Ignore
@Test
fun `negative hour rolls over continuously`() = assertEquals("05:00", Clock(-91, 0).toString())
@Ignore
@Test
fun `negative minutes`() = assertEquals("00:20", Clock(1, -40).toString())
@Ignore
@Test
fun `negative minutes roll over`() = assertEquals("22:20", Clock(1, -160).toString())
@Ignore
@Test
fun `negative minutes roll over continuously`() = assertEquals("16:40", Clock(1, -4820).toString())
@Ignore
@Test
fun `negative sixty minutes is previous hour`() = assertEquals("01:00", Clock(2, -60).toString())
@Ignore
@Test
fun `negative hour and minutes both roll over`() = assertEquals("20:20", Clock(-25, -160).toString())
@Ignore
@Test
fun `negative hour and minutes both roll over continuously`() =
assertEquals("22:10", Clock(-121, -5810).toString())
}
| mit | 4315fefd8204510ee538548f2768d4ec | 26.54023 | 110 | 0.622705 | 3.761381 | false | true | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/toolboks/font/FreeTypeFont.kt | 2 | 1837 | package io.github.chrislo27.toolboks.font
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator
import com.badlogic.gdx.utils.Disposable
import io.github.chrislo27.toolboks.util.gdxutils.copy
import kotlin.math.min
import kotlin.math.roundToInt
/**
* Handles a FreeType font. Used for dynamic resizing.
*/
class FreeTypeFont(val file: FileHandle, val defaultWindowSize: Pair<Int, Int>,
val fontSize: Int, val borderSize: Float,
val parameter: FreeTypeFontGenerator.FreeTypeFontParameter) : Disposable {
constructor(file: FileHandle, defaultWindowSize: Pair<Int, Int>,
parameter: FreeTypeFontGenerator.FreeTypeFontParameter):
this(file, defaultWindowSize, parameter.size, parameter.borderWidth, parameter)
private var generator: FreeTypeFontGenerator? = null
var font: BitmapFont? = null
private set
private var afterLoad: FreeTypeFont.() -> Unit = {}
fun setAfterLoad(func: FreeTypeFont.() -> Unit): FreeTypeFont {
afterLoad = func
return this
}
fun isLoaded(): Boolean = font != null
fun load(width: Float, height: Float) {
dispose()
val scale: Float = min(width / defaultWindowSize.first, height / defaultWindowSize.second)
val newParam = parameter.copy()
newParam.size = (fontSize * scale).roundToInt()
newParam.borderWidth = borderSize * scale
generator = FreeTypeFontGenerator(file)
font = generator!!.generateFont(newParam)
this.afterLoad()
}
override fun dispose() {
font?.dispose()
(font?.data as? Disposable)?.dispose()
generator?.dispose()
font = null
generator = null
}
} | gpl-3.0 | 8711e2d85ccbc849fd844c04d85f03d3 | 31.821429 | 98 | 0.680457 | 4.662437 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/completion/htl/provider/option/HtlOptionCompletionProvider.kt | 1 | 1255 | package com.aemtools.completion.htl.provider.option
import com.aemtools.common.util.findParentByType
import com.aemtools.completion.model.htl.HtlOption
import com.aemtools.service.repository.inmemory.HtlAttributesRepository
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.util.ProcessingContext
/**
* @author Dmytro Troynikov
*/
object HtlOptionCompletionProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters,
context: ProcessingContext,
result: CompletionResultSet) {
val currentPosition = parameters.position
val hel = currentPosition.findParentByType(com.aemtools.lang.htl.psi.mixin.HtlElExpressionMixin::class.java)
?: return
val names = hel.getOptions().map { it.name() }
.filterNot { it == "" }
val completionVariants = HtlAttributesRepository.getHtlOptions()
.filterNot { names.contains(it.name) }
.map(HtlOption::toLookupElement)
result.addAllElements(completionVariants)
result.stopHere()
}
}
| gpl-3.0 | b2abf43398aec904d29dbd04a9ad81c5 | 35.911765 | 112 | 0.749801 | 4.921569 | false | false | false | false |
zdary/intellij-community | platform/workspaceModel/ide/src/com/intellij/workspaceModel/ide/impl/StartupMeasurerHelper.kt | 1 | 584 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl
import com.intellij.diagnostic.Activity
import com.intellij.diagnostic.StartUpMeasurer.startActivity
internal var moduleLoadingActivity: Activity? = null
fun finishModuleLoadingActivity() {
moduleLoadingActivity?.end()
moduleLoadingActivity = null
}
fun recordModuleLoadingActivity() {
if (moduleLoadingActivity == null) {
moduleLoadingActivity = startActivity("moduleLoading")
}
}
| apache-2.0 | 6e01c0873da454e78521fe38010a0c02 | 31.444444 | 140 | 0.794521 | 4.262774 | false | false | false | false |
leafclick/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesGroupingSupport.kt | 1 | 3936 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.KeyedExtensionFactory
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.DIRECTORY_GROUPING
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.MODULE_GROUPING
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.REPOSITORY_GROUPING
import gnu.trove.THashMap
import java.beans.PropertyChangeListener
import java.beans.PropertyChangeSupport
import javax.swing.tree.DefaultTreeModel
private val PREDEFINED_PRIORITIES = mapOf(DIRECTORY_GROUPING to 10, MODULE_GROUPING to 20, REPOSITORY_GROUPING to 30)
class ChangesGroupingSupport(val project: Project, source: Any, val showConflictsNode: Boolean) {
private val changeSupport = PropertyChangeSupport(source)
private val groupingConfig: MutableMap<String, Boolean>
val groupingKeys: Set<String>
get() = groupingConfig.filterValues { it }.keys
init {
groupingConfig = THashMap()
for (epBean in ChangesGroupingPolicyFactory.EP_NAME.extensionList) {
if (epBean.key != null) {
groupingConfig.put(epBean.key, false)
}
}
}
operator fun get(groupingKey: String): Boolean {
if (!isAvailable(groupingKey)) throw IllegalArgumentException("Unknown grouping $groupingKey")
return groupingConfig[groupingKey]!!
}
operator fun set(groupingKey: String, state: Boolean) {
if (!isAvailable(groupingKey)) throw IllegalArgumentException("Unknown grouping $groupingKey")
if (groupingConfig[groupingKey] != state) {
val oldGroupingKeys = groupingKeys
groupingConfig[groupingKey] = state
changeSupport.firePropertyChange(PROP_GROUPING_KEYS, oldGroupingKeys, groupingKeys)
}
}
val grouping: ChangesGroupingPolicyFactory
get() = object : ChangesGroupingPolicyFactory() {
override fun createGroupingPolicy(project: Project, model: DefaultTreeModel): ChangesGroupingPolicy {
var result = DefaultChangesGroupingPolicy.Factory(showConflictsNode).createGroupingPolicy(project, model)
groupingConfig.filterValues { it }.keys.sortedByDescending { PREDEFINED_PRIORITIES[it] }.forEach {
result = findFactory(it)!!.createGroupingPolicy(project, model).apply { setNextGroupingPolicy(result) }
}
return result
}
}
val isNone: Boolean get() = groupingKeys.isEmpty()
val isDirectory: Boolean get() = this[DIRECTORY_GROUPING]
fun setGroupingKeysOrSkip(groupingKeys: Set<String>) {
groupingConfig.entries.forEach { it.setValue(it.key in groupingKeys) }
}
fun isAvailable(groupingKey: String) = findFactory(groupingKey) != null
fun addPropertyChangeListener(listener: PropertyChangeListener): Unit = changeSupport.addPropertyChangeListener(listener)
fun removePropertyChangeListener(listener: PropertyChangeListener): Unit = changeSupport.removePropertyChangeListener(listener)
companion object {
@JvmField
val KEY = DataKey.create<ChangesGroupingSupport>("ChangesTree.GroupingSupport")
const val PROP_GROUPING_KEYS = "ChangesGroupingKeys"
const val DIRECTORY_GROUPING = "directory"
const val MODULE_GROUPING = "module"
const val REPOSITORY_GROUPING = "repository"
const val NONE_GROUPING = "none"
@JvmStatic
fun getFactory(key: String): ChangesGroupingPolicyFactory {
return findFactory(key) ?: NoneChangesGroupingFactory
}
private fun findFactory(key: String): ChangesGroupingPolicyFactory? {
return KeyedExtensionFactory.findByKey(key, ChangesGroupingPolicyFactory.EP_NAME, ApplicationManager.getApplication().picoContainer)
}
}
} | apache-2.0 | 004b89caa423f0f7f1768318652617ec | 41.793478 | 140 | 0.771596 | 4.944724 | false | true | false | false |
tinsukE/retrofit-coroutines | lib/src/main/java/com/tinsuke/retrofit/coroutines/experimental/CoroutinesCallAdapterFactory.kt | 1 | 2403 | package com.tinsuke.retrofit.coroutines.experimental
import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.newFixedThreadPoolContext
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Response
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import kotlin.coroutines.experimental.CoroutineContext
class CoroutinesCallAdapterFactory private constructor(private val context: CoroutineContext,
interceptor: CoroutinesInterceptor?) : CallAdapter.Factory() {
private val executor = object : CoroutinesExecutor {
override fun execute(call: Call<Any>): Response<Any> {
return if (interceptor == null) {
call.execute()
} else {
interceptor.intercept(call)
}
}
}
override fun get(returnType: Type?, annotations: Array<out Annotation>?, retrofit: Retrofit?): CallAdapter<*, *>? {
val rawType = getRawType(returnType)
if (rawType != Deferred::class.java) {
return null
}
if (returnType !is ParameterizedType) {
throw createInvalidReturnTypeException()
}
val deferredType = getParameterUpperBound(0, returnType)
val rawDeferredType = getRawType(deferredType)
if (rawDeferredType == Response::class.java) {
if (deferredType !is ParameterizedType) {
throw throw createInvalidReturnTypeException()
}
val responseType = getParameterUpperBound(0, deferredType)
return CoroutinesResponseCallAdapter(context, responseType, executor)
} else {
return CoroutinesCallAdapter(context, deferredType, executor)
}
}
private fun createInvalidReturnTypeException(): RuntimeException {
return IllegalStateException("Return type must be parameterized as Deferred<Foo>, Deferred<out Foo>, " +
"Deferred<Response<Foo>> or Deferred<Response<out Foo>>")
}
companion object {
fun create(context: CoroutineContext = newFixedThreadPoolContext(5, "Network-Coroutines"),
interceptor: CoroutinesInterceptor? = null): CoroutinesCallAdapterFactory {
return CoroutinesCallAdapterFactory(context, interceptor)
}
}
} | apache-2.0 | 943e05b4631d519b49dc4b8c0f3a0120 | 37.15873 | 119 | 0.668747 | 5.486301 | false | false | false | false |
AndroidX/androidx | camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/impl/ZoomControl.kt | 3 | 2846 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.pipe.integration.impl
import androidx.annotation.RequiresApi
import androidx.camera.camera2.pipe.integration.compat.ZoomCompat
import androidx.camera.camera2.pipe.integration.config.CameraScope
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoSet
import javax.inject.Inject
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
@CameraScope
class ZoomControl @Inject constructor(private val zoomCompat: ZoomCompat) : UseCaseCameraControl {
private var _zoomRatio = 1.0f
var zoomRatio: Float
get() = _zoomRatio
set(value) {
// TODO: Make this a suspend function?
_zoomRatio = value
update()
}
// NOTE: minZoom may be lower than 1.0
// NOTE: Default zoom ratio is 1.0
// NOTE: Linear zoom is
val minZoom: Float = zoomCompat.minZoom
val maxZoom: Float = zoomCompat.maxZoom
/** Linear zoom is between 0.0f and 1.0f */
fun toLinearZoom(zoomRatio: Float): Float {
val range = zoomCompat.maxZoom - zoomCompat.minZoom
if (range > 0) {
return (zoomRatio - zoomCompat.minZoom) / range
}
return 0.0f
}
/** Zoom ratio is commonly used as the "1x, 2x, 5x" zoom ratio. Zoom ratio may be less than 1 */
fun toZoomRatio(linearZoom: Float): Float {
val range = zoomCompat.maxZoom - zoomCompat.minZoom
if (range > 0) {
return linearZoom * range + zoomCompat.minZoom
}
return 1.0f
}
private var _useCaseCamera: UseCaseCamera? = null
override var useCaseCamera: UseCaseCamera?
get() = _useCaseCamera
set(value) {
_useCaseCamera = value
update()
}
override fun reset() {
// TODO: 1.0 may not be a reasonable value to reset the zoom state too.
zoomRatio = 1.0f
update()
}
private fun update() {
_useCaseCamera?.let {
zoomCompat.apply(_zoomRatio, it)
}
}
@Module
abstract class Bindings {
@Binds
@IntoSet
abstract fun provideControls(zoomControl: ZoomControl): UseCaseCameraControl
}
}
| apache-2.0 | 5d8d0ce37d78f917ae4cce84ffcb20b5 | 30.977528 | 100 | 0.661279 | 4.124638 | false | false | false | false |
nextras/orm-intellij | src/main/kotlin/org/nextras/orm/intellij/utils/OrmUtils.kt | 1 | 5501 | package org.nextras.orm.intellij.utils
import com.intellij.openapi.project.Project
import com.jetbrains.php.PhpIndex
import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocProperty
import com.jetbrains.php.lang.psi.elements.*
import com.jetbrains.php.lang.psi.resolve.types.PhpType
import java.util.*
object OrmUtils {
enum class OrmClass constructor(private val className: String) {
COLLECTION("\\Nextras\\Orm\\Collection\\ICollection"),
MAPPER("\\Nextras\\Orm\\Mapper\\IMapper"),
REPOSITORY("\\Nextras\\Orm\\Repository\\IRepository"),
ENTITY("\\Nextras\\Orm\\Entity\\IEntity"),
HAS_MANY("\\Nextras\\Orm\\Relationships\\HasMany"),
EMBEDDABLE("\\Nextras\\Orm\\Entity\\Embeddable\\IEmbeddable");
fun `is`(cls: PhpClass, index: PhpIndex): Boolean {
val classes = index.getAnyByFQN(className)
val instanceOf = when {
classes.isEmpty() -> null
else -> classes.iterator().next()
} ?: return false
return instanceOf.type.isConvertibleFrom(cls.type, index)
}
}
private var isV3: Boolean? = null
fun isV3(project: Project): Boolean {
val index = PhpIndex.getInstance(project)
if (isV3 != null) {
return isV3!!
}
val collectionFunction = index.getInterfacesByFQN("\\Nextras\\Orm\\Collection\\Functions\\IArrayFunction")
isV3 = collectionFunction.isEmpty()
return isV3!!
}
fun findRepositoryEntities(repositories: Collection<PhpClass>): Collection<PhpClass> {
val entities = HashSet<PhpClass>(1)
for (repositoryClass in repositories) {
val entityNamesMethod = repositoryClass.findMethodByName("getEntityClassNames") ?: return emptyList()
if (entityNamesMethod.lastChild !is GroupStatement) {
continue
}
if ((entityNamesMethod.lastChild as GroupStatement).firstPsiChild !is PhpReturn) {
continue
}
if ((entityNamesMethod.lastChild as GroupStatement).firstPsiChild!!.firstPsiChild !is ArrayCreationExpression) {
continue
}
val arr = (entityNamesMethod.lastChild as GroupStatement).firstPsiChild!!.firstPsiChild as ArrayCreationExpression?
val phpIndex = PhpIndex.getInstance(repositoryClass.project)
for (el in arr!!.children) {
if (el.firstChild !is ClassConstantReference) {
continue
}
val ref = el.firstChild as ClassConstantReference
if (ref.name != "class") {
continue
}
entities.addAll(PhpIndexUtils.getByType(ref.classReference!!.type, phpIndex))
}
}
return entities
}
fun findQueriedEntities(ref: MemberReference): Collection<PhpClass> {
val classReference = ref.classReference ?: return emptyList()
val entities = HashSet<PhpClass>()
val phpIndex = PhpIndex.getInstance(ref.project)
val classes = PhpIndexUtils.getByType(classReference.type, phpIndex)
val repositories = classes.filter { cls -> OrmClass.REPOSITORY.`is`(cls, phpIndex) }
if (repositories.isNotEmpty()) {
entities.addAll(findRepositoryEntities(repositories))
}
for (type in classReference.type.types) {
if (!type.endsWith("[]")) {
continue
}
val typeWithoutArray = PhpType().add(type.substring(0, type.length - 2))
val maybeEntities = PhpIndexUtils.getByType(typeWithoutArray, phpIndex)
entities.addAll(
maybeEntities.filter { cls ->
OrmClass.ENTITY.`is`(cls, phpIndex)
}
)
}
return entities
}
fun findQueriedEntities(reference: MethodReference, cls: String?, path: Array<String>): Collection<PhpClass> {
val rootEntities = if (cls == null || cls == "this") {
findQueriedEntities(reference)
} else {
val index = PhpIndex.getInstance(reference.project)
PhpIndexUtils.getByType(PhpType().add(cls), index)
}
if (rootEntities.isEmpty()) {
return emptyList()
}
return when {
path.size <= 1 -> rootEntities
else -> findTargetEntities(rootEntities, path, 0)
}
}
fun parsePathExpression(expression: String, isV3: Boolean): Pair<String?, Array<String>> {
if (isV3) {
val path = expression.split("->")
return when (path.size > 1) {
true -> Pair(
path.first(),
path.drop(1).toTypedArray()
)
false -> Pair(
null,
path.toTypedArray()
)
}
} else {
val delimiterPos = expression.indexOf("::")
val sourceClass = expression.substring(0, delimiterPos.coerceAtLeast(0))
val path = if (delimiterPos == -1) expression else expression.substring((delimiterPos + 2).coerceAtMost(expression.length))
return Pair(
sourceClass.ifEmpty { null },
path.split("->").toTypedArray()
)
}
}
private fun findTargetEntities(currentEntities: Collection<PhpClass>, path: Array<String>, pos: Int): Collection<PhpClass> {
if (path.size == pos + 1) {
return currentEntities
}
val entities = HashSet<PhpClass>()
for (cls in currentEntities) {
val field = cls.findFieldByName(path[pos], false) as? PhpDocProperty ?: continue
addEntitiesFromField(entities, field)
}
return findTargetEntities(entities, path, pos + 1)
}
private fun addEntitiesFromField(entities: MutableCollection<PhpClass>, field: PhpDocProperty) {
val index = PhpIndex.getInstance(field.project)
for (type in field.type.types) {
if (type.contains("Nextras\\Orm\\Relationship")) {
continue
}
val addType = if (type.endsWith("[]")) {
type.substring(0, type.length - 2)
} else {
type
}
for (entityCls in PhpIndexUtils.getByType(PhpType().add(addType), index)) {
if (!OrmClass.ENTITY.`is`(entityCls, index) && !OrmClass.EMBEDDABLE.`is`(entityCls, index)) {
continue
}
entities.add(entityCls)
}
}
}
}
| mit | e2e5eb664ae13a358e188d5edf1a9a45 | 30.982558 | 126 | 0.704236 | 3.56976 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/roots/builders/ModuleRootsIndexableIteratorHandler.kt | 1 | 3250 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.indexing.roots.builders
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PlatformUtils
import com.intellij.util.indexing.roots.IndexableEntityProvider
import com.intellij.util.indexing.roots.IndexableEntityProviderMethods
import com.intellij.util.indexing.roots.IndexableFilesIterator
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.moduleMap
import com.intellij.workspaceModel.ide.impl.virtualFile
import com.intellij.workspaceModel.ide.isEqualOrParentOf
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleId
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
class ModuleRootsIndexableIteratorHandler : IndexableIteratorBuilderHandler {
override fun accepts(builder: IndexableEntityProvider.IndexableIteratorBuilder): Boolean =
builder is ModuleRootsIteratorBuilder || builder is FullModuleContentIteratorBuilder
override fun instantiate(builders: Collection<IndexableEntityProvider.IndexableIteratorBuilder>,
project: Project,
entityStorage: WorkspaceEntityStorage): List<IndexableFilesIterator> {
val fullIndexedModules: Set<ModuleId> = builders.mapNotNull { (it as? FullModuleContentIteratorBuilder)?.moduleId }.toSet()
@Suppress("UNCHECKED_CAST")
val partialIterators = builders.filter {
it is ModuleRootsIteratorBuilder && !fullIndexedModules.contains(it.moduleId)
} as List<ModuleRootsIteratorBuilder>
val partialIteratorsMap = partialIterators.groupBy { builder -> builder.moduleId }
val result = mutableListOf<IndexableFilesIterator>()
fullIndexedModules.forEach { moduleId ->
entityStorage.resolve(moduleId)?.also { entity ->
result.addAll(IndexableEntityProviderMethods.createIterators(entity, entityStorage, project))
}
}
val moduleMap = entityStorage.moduleMap
partialIteratorsMap.forEach { pair ->
entityStorage.resolve(pair.key)?.also { entity ->
result.addAll(IndexableEntityProviderMethods.createIterators(entity, resolveRoots(pair.value), moduleMap, project))
}
}
return result
}
private fun resolveRoots(builders: List<ModuleRootsIteratorBuilder>): List<VirtualFile> {
if (PlatformUtils.isRider()) {
return builders.flatMap { builder -> builder.urls }.mapNotNull { url -> url.virtualFile }
}
val roots = mutableListOf<VirtualFileUrl>()
for (builder in builders) {
for (root in builder.urls) {
var isChild = false
val it = roots.iterator()
while (it.hasNext()) {
val next = it.next()
if (next.isEqualOrParentOf(root)) {
isChild = true
break
}
if (root.isEqualOrParentOf(next)) {
it.remove()
}
}
if (!isChild) {
roots.add(root)
}
}
}
return roots.mapNotNull { url -> url.virtualFile }
}
} | apache-2.0 | 02f4853928a1649e1b62b7e149482b84 | 42.932432 | 158 | 0.731385 | 5.015432 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/arguments/util.kt | 2 | 3244 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradleTooling.arguments
import org.gradle.api.Task
import org.gradle.api.logging.Logger
import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder
import org.jetbrains.kotlin.idea.gradleTooling.arguments.CompilerArgumentsCachingManager.cacheCompilerArgument
import org.jetbrains.kotlin.idea.gradleTooling.getDeclaredMethodOrNull
import org.jetbrains.kotlin.idea.gradleTooling.getMethodOrNull
import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheMapper
import java.io.File
import java.lang.reflect.Method
private fun buildDependencyClasspath(compileKotlinTask: Task): List<String> {
val abstractKotlinCompileClass =
compileKotlinTask.javaClass.classLoader.loadClass(AbstractKotlinGradleModelBuilder.ABSTRACT_KOTLIN_COMPILE_CLASS)
val getCompileClasspath =
abstractKotlinCompileClass.getDeclaredMethodOrNull("getCompileClasspath") ?: abstractKotlinCompileClass.getDeclaredMethodOrNull(
"getClasspath"
) ?: return emptyList()
@Suppress("UNCHECKED_CAST")
return (getCompileClasspath(compileKotlinTask) as? Collection<File>)?.map { it.path } ?: emptyList()
}
fun buildCachedArgsInfo(
compileKotlinTask: Task,
cacheMapper: CompilerArgumentsCacheMapper,
): CachedExtractedArgsInfo {
val cachedCurrentArguments = CompilerArgumentsCachingChain.extractAndCacheTask(compileKotlinTask, cacheMapper, defaultsOnly = false)
val cachedDefaultArguments = CompilerArgumentsCachingChain.extractAndCacheTask(compileKotlinTask, cacheMapper, defaultsOnly = true)
val dependencyClasspath = buildDependencyClasspath(compileKotlinTask).map { cacheCompilerArgument(it, cacheMapper) }
return CachedExtractedArgsInfo(cacheMapper.cacheOriginIdentifier, cachedCurrentArguments, cachedDefaultArguments, dependencyClasspath)
}
fun buildSerializedArgsInfo(
compileKotlinTask: Task,
cacheMapper: CompilerArgumentsCacheMapper,
logger: Logger
): CachedSerializedArgsInfo {
val compileTaskClass = compileKotlinTask.javaClass
val getCurrentArguments = compileTaskClass.getMethodOrNull("getSerializedCompilerArguments")
val getDefaultArguments = compileTaskClass.getMethodOrNull("getDefaultSerializedCompilerArguments")
val currentArguments = safelyGetArguments(compileKotlinTask, getCurrentArguments, logger).map { cacheCompilerArgument(it, cacheMapper) }
val defaultArguments = safelyGetArguments(compileKotlinTask, getDefaultArguments, logger).map { cacheCompilerArgument(it, cacheMapper) }
val dependencyClasspath = buildDependencyClasspath(compileKotlinTask).map { cacheCompilerArgument(it, cacheMapper) }
return CachedSerializedArgsInfo(cacheMapper.cacheOriginIdentifier, currentArguments, defaultArguments, dependencyClasspath)
}
@Suppress("UNCHECKED_CAST")
private fun safelyGetArguments(compileKotlinTask: Task, accessor: Method?, logger: Logger) = try {
accessor?.invoke(compileKotlinTask) as? List<String>
} catch (e: Exception) {
logger.warn(e.message ?: "Unexpected exception: $e", e)
null
} ?: emptyList()
| apache-2.0 | 7d45b2a158acb27fbede97596c3ffb29 | 56.928571 | 158 | 0.817509 | 5.309329 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt | 1 | 5601 | package info.nightscout.androidaps.plugins.general.automation.triggers
import android.location.Location
import android.widget.LinearLayout
import com.google.common.base.Optional
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.general.automation.elements.*
import info.nightscout.androidaps.utils.JsonHelper
import org.json.JSONObject
import java.text.DecimalFormat
class TriggerLocation(injector: HasAndroidInjector) : Trigger(injector) {
var latitude = InputDouble(injector, 0.0, -90.0, +90.0, 0.000001, DecimalFormat("0.000000"))
var longitude = InputDouble(injector, 0.0, -180.0, +180.0, 0.000001, DecimalFormat("0.000000"))
var distance = InputDouble(injector, 200.0, 0.0, 100000.0, 10.0, DecimalFormat("0"))
var modeSelected = InputLocationMode(injector)
var name: InputString = InputString(injector)
var lastMode = InputLocationMode.Mode.INSIDE
private val buttonAction = Runnable {
locationDataContainer.lastLocation?.let {
latitude.setValue(it.latitude)
longitude.setValue(it.longitude)
aapsLogger.debug(LTag.AUTOMATION, String.format("Grabbed location: %f %f", latitude.value, longitude.value))
}
}
private constructor(injector: HasAndroidInjector, triggerLocation: TriggerLocation) : this(injector) {
latitude = InputDouble(injector, triggerLocation.latitude)
longitude = InputDouble(injector, triggerLocation.longitude)
distance = InputDouble(injector, triggerLocation.distance)
modeSelected = InputLocationMode(injector, triggerLocation.modeSelected.value)
if (modeSelected.value == InputLocationMode.Mode.GOING_OUT)
lastMode = InputLocationMode.Mode.OUTSIDE
name = triggerLocation.name
}
@Synchronized override fun shouldRun(): Boolean {
val location: Location = locationDataContainer.lastLocation ?: return false
val a = Location("Trigger")
a.latitude = latitude.value
a.longitude = longitude.value
val calculatedDistance = location.distanceTo(a).toDouble()
if (modeSelected.value == InputLocationMode.Mode.INSIDE && calculatedDistance <= distance.value ||
modeSelected.value == InputLocationMode.Mode.OUTSIDE && calculatedDistance > distance.value ||
modeSelected.value == InputLocationMode.Mode.GOING_IN && calculatedDistance <= distance.value && lastMode == InputLocationMode.Mode.OUTSIDE ||
modeSelected.value == InputLocationMode.Mode.GOING_OUT && calculatedDistance > distance.value && lastMode == InputLocationMode.Mode.INSIDE) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
lastMode = currentMode(calculatedDistance)
return true
}
lastMode = currentMode(calculatedDistance) // current mode will be last mode for the next check
aapsLogger.debug(LTag.AUTOMATION, "NOT ready for execution: " + friendlyDescription())
return false
}
override fun toJSON(): String {
val data = JSONObject()
.put("latitude", latitude.value)
.put("longitude", longitude.value)
.put("distance", distance.value)
.put("name", name.value)
.put("mode", modeSelected.value)
return JSONObject()
.put("type", this::class.java.name)
.put("data", data)
.toString()
}
override fun fromJSON(data: String): Trigger {
val d = JSONObject(data)
latitude.value = JsonHelper.safeGetDouble(d, "latitude")
longitude.value = JsonHelper.safeGetDouble(d, "longitude")
distance.value = JsonHelper.safeGetDouble(d, "distance")
name.value = JsonHelper.safeGetString(d, "name")!!
modeSelected.value = InputLocationMode.Mode.valueOf(JsonHelper.safeGetString(d, "mode")!!)
if (modeSelected.value == InputLocationMode.Mode.GOING_OUT) lastMode = InputLocationMode.Mode.OUTSIDE
return this
}
override fun friendlyName(): Int = R.string.location
override fun friendlyDescription(): String =
resourceHelper.gs(R.string.locationis, resourceHelper.gs(modeSelected.value.stringRes), " " + name.value)
override fun icon(): Optional<Int?> = Optional.of(R.drawable.ic_location_on)
override fun duplicate(): Trigger = TriggerLocation(injector, this)
override fun generateDialog(root: LinearLayout) {
LayoutBuilder()
.add(StaticLabel(injector, R.string.location, this))
.add(LabelWithElement(injector, resourceHelper.gs(R.string.name_short), "", name))
.add(LabelWithElement(injector, resourceHelper.gs(R.string.latitude_short), "", latitude))
.add(LabelWithElement(injector, resourceHelper.gs(R.string.longitude_short), "", longitude))
.add(LabelWithElement(injector, resourceHelper.gs(R.string.distance_short), "", distance))
.add(LabelWithElement(injector, resourceHelper.gs(R.string.location_mode), "", modeSelected))
.add(InputButton(injector, resourceHelper.gs(R.string.currentlocation), buttonAction), locationDataContainer.lastLocation != null)
.build(root)
}
// Method to return the actual mode based on the current distance
fun currentMode(currentDistance: Double): InputLocationMode.Mode {
return if (currentDistance <= distance.value) InputLocationMode.Mode.INSIDE else InputLocationMode.Mode.OUTSIDE
}
} | agpl-3.0 | eacfea3e0a0a00a52d98138c72cb5954 | 50.87037 | 154 | 0.699518 | 4.498795 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/activities/VideoActivity.kt | 1 | 6356 | package com.kickstarter.ui.activities
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.source.hls.HlsMediaSource
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource
import com.google.android.exoplayer2.util.Util
import com.kickstarter.R
import com.kickstarter.databinding.VideoPlayerLayoutBinding
import com.kickstarter.libs.BaseActivity
import com.kickstarter.libs.Build
import com.kickstarter.libs.qualifiers.RequiresActivityViewModel
import com.kickstarter.libs.rx.transformers.Transformers
import com.kickstarter.libs.utils.WebUtils.userAgent
import com.kickstarter.ui.IntentKey
import com.kickstarter.viewmodels.VideoViewModel
import com.trello.rxlifecycle.ActivityEvent
@RequiresActivityViewModel(VideoViewModel.ViewModel::class)
class VideoActivity : BaseActivity<VideoViewModel.ViewModel>() {
private lateinit var build: Build
private var player: SimpleExoPlayer? = null
private var playerPosition: Long? = null
private var trackSelector: DefaultTrackSelector? = null
private lateinit var binding: VideoPlayerLayoutBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = VideoPlayerLayoutBinding.inflate(layoutInflater)
setContentView(binding.root)
build = requireNotNull(environment().build())
val fullscreenButton: ImageView = binding.playerView.findViewById(R.id.exo_fullscreen_icon)
fullscreenButton.setImageResource(R.drawable.ic_fullscreen_close)
fullscreenButton.setOnClickListener {
back()
}
viewModel.outputs.preparePlayerWithUrl()
.compose(Transformers.takeWhen(lifecycle().filter { other: ActivityEvent? -> ActivityEvent.RESUME.equals(other) }))
.compose(bindToLifecycle())
.subscribe { preparePlayer(it) }
viewModel.outputs.preparePlayerWithUrlAndPosition()
.compose(Transformers.takeWhen(lifecycle().filter { other: ActivityEvent? -> ActivityEvent.RESUME.equals(other) }))
.compose(bindToLifecycle())
.subscribe {
playerPosition = it.second
preparePlayer(it.first)
}
}
public override fun onDestroy() {
super.onDestroy()
releasePlayer()
}
public override fun onPause() {
super.onPause()
releasePlayer()
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
binding.videoPlayerLayout.systemUiVisibility = systemUIFlags()
}
}
override fun back() {
val intent = Intent()
.putExtra(IntentKey.VIDEO_SEEK_POSITION, player?.currentPosition)
setResult(Activity.RESULT_OK, intent)
finish()
}
private fun systemUIFlags(): Int {
return (
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_IMMERSIVE
)
}
private fun onStateChanged(playbackState: Int) {
if (playbackState == Player.STATE_READY) {
player?.duration?.let {
viewModel.inputs.onVideoStarted(it, playerPosition ?: 0L)
}
}
if (playbackState == Player.STATE_ENDED) {
finish()
}
if (playbackState == Player.STATE_BUFFERING) {
binding.loadingIndicator.visibility = View.VISIBLE
} else {
binding.loadingIndicator.visibility = View.GONE
}
}
private fun preparePlayer(videoUrl: String) {
val adaptiveTrackSelectionFactory: AdaptiveTrackSelection.Factory = AdaptiveTrackSelection.Factory()
trackSelector = DefaultTrackSelector(this, adaptiveTrackSelectionFactory)
// player = ExoPlayerFactory.newSimpleInstance(this, trackSelector)
val player2 = trackSelector?.let {
SimpleExoPlayer.Builder(this).setTrackSelector(
it
)
}
val playerBuilder = SimpleExoPlayer.Builder(this)
trackSelector?.let { playerBuilder.setTrackSelector(it) }
player = playerBuilder.build()
binding.playerView.player = player
player?.addListener(eventListener)
val playerIsResuming = (playerPosition != 0L)
player?.prepare(getMediaSource(videoUrl), playerIsResuming, false)
playerPosition?.let {
player?.seekTo(it)
}
player?.playWhenReady = true
}
private fun getMediaSource(videoUrl: String): MediaSource {
val dataSourceFactory = DefaultHttpDataSource.Factory().setUserAgent(userAgent(build))
val videoUri = Uri.parse(videoUrl)
val fileType = Util.inferContentType(videoUri)
return if (fileType == C.TYPE_HLS) {
HlsMediaSource.Factory(dataSourceFactory).createMediaSource(MediaItem.fromUri(videoUri))
} else {
ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(MediaItem.fromUri(videoUri))
}
}
private fun releasePlayer() {
if (player != null) {
playerPosition = player?.currentPosition
player?.duration?.let {
viewModel.inputs.onVideoCompleted(it, playerPosition ?: 0L)
}
player?.removeListener(eventListener)
player?.release()
trackSelector = null
player = null
}
}
private val eventListener: Player.Listener = object : Player.Listener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
onStateChanged(playbackState)
}
}
}
| apache-2.0 | b67da572f014dc46ea9005ff774db09b | 35.953488 | 127 | 0.687539 | 5.024506 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AbstractReferenceSubstitutionRenameHandler.kt | 1 | 3385 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.rename
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.refactoring.rename.PsiElementRenameHandler
import com.intellij.refactoring.rename.RenameHandler
import com.intellij.refactoring.rename.inplace.MemberInplaceRenameHandler
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
abstract class AbstractReferenceSubstitutionRenameHandler(
private val delegateHandler: RenameHandler = MemberInplaceRenameHandler()
) : PsiElementRenameHandler() {
companion object {
fun getReferenceExpression(file: PsiFile, offset: Int): KtSimpleNameExpression? {
var elementAtCaret = file.findElementAt(offset) ?: return null
if (elementAtCaret.node?.elementType == KtTokens.AT) return null
if (elementAtCaret is PsiWhiteSpace) {
elementAtCaret = CodeInsightUtils.getElementAtOffsetIgnoreWhitespaceAfter(file, offset) ?: return null
if (offset != elementAtCaret.endOffset) return null
}
return elementAtCaret.getNonStrictParentOfType<KtSimpleNameExpression>()
}
fun getReferenceExpression(dataContext: DataContext): KtSimpleNameExpression? {
val caret = CommonDataKeys.CARET.getData(dataContext) ?: return null
val ktFile = CommonDataKeys.PSI_FILE.getData(dataContext) as? KtFile ?: return null
return getReferenceExpression(ktFile, caret.offset)
}
}
protected abstract fun getElementToRename(dataContext: DataContext): PsiElement?
override fun isAvailableOnDataContext(dataContext: DataContext): Boolean {
return CommonDataKeys.EDITOR.getData(dataContext) != null && getElementToRename(dataContext) != null
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?, dataContext: DataContext) {
val elementToRename = getElementToRename(dataContext) ?: return
val wrappingContext = DataContext { id ->
if (CommonDataKeys.PSI_ELEMENT.`is`(id)) return@DataContext elementToRename
dataContext.getData(id)
}
// Can't provide new name for inplace refactoring in unit test mode
if (!ApplicationManager.getApplication().isUnitTestMode && delegateHandler.isAvailableOnDataContext(wrappingContext)) {
delegateHandler.invoke(project, editor, file, wrappingContext)
} else {
super.invoke(project, editor, file, wrappingContext)
}
}
override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext) {
// Can't be invoked outside of a text editor
}
} | apache-2.0 | 8c7f6a1fdb75e1c3c33bc823e7786320 | 49.537313 | 158 | 0.749483 | 5.207692 | false | false | false | false |
jwren/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/data/VcsUserRegistryImpl.kt | 2 | 4952 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.data
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import com.intellij.util.containers.HashSetInterner
import com.intellij.util.containers.Interner
import com.intellij.util.io.IOUtil
import com.intellij.util.io.KeyDescriptor
import com.intellij.util.io.PersistentBTreeEnumerator
import com.intellij.util.io.PersistentEnumeratorBase
import com.intellij.util.io.storage.AbstractStorage
import com.intellij.vcs.log.VcsUser
import com.intellij.vcs.log.VcsUserRegistry
import com.intellij.vcs.log.impl.VcsUserImpl
import java.io.DataInput
import java.io.DataOutput
import java.io.File
import java.io.IOException
import java.util.concurrent.atomic.AtomicReference
class VcsUserRegistryImpl internal constructor(project: Project) : Disposable, VcsUserRegistry {
private val _persistentEnumerator = AtomicReference<PersistentEnumeratorBase<VcsUser>?>()
private val persistentEnumerator: PersistentEnumeratorBase<VcsUser>?
get() = _persistentEnumerator.get()
private val interner: Interner<VcsUser>
private val mapFile = File(USER_CACHE_APP_DIR, project.locationHash + "." + STORAGE_VERSION)
init {
initEnumerator()
interner = HashSetInterner()
}
private fun initEnumerator(): Boolean {
try {
val enumerator = IOUtil.openCleanOrResetBroken({
PersistentBTreeEnumerator(mapFile.toPath(), VcsUserKeyDescriptor(this),
AbstractStorage.PAGE_SIZE, null, STORAGE_VERSION)
}, mapFile)
val wasSet = _persistentEnumerator.compareAndSet(null, enumerator)
if (!wasSet) {
LOG.error("Could not assign newly opened enumerator")
enumerator?.close()
}
return wasSet
}
catch (e: IOException) {
LOG.warn(e)
}
return false
}
override fun createUser(name: String, email: String): VcsUser {
synchronized(interner) {
return interner.intern(VcsUserImpl(name, email))
}
}
fun addUser(user: VcsUser) {
try {
persistentEnumerator?.enumerate(user)
}
catch (e: IOException) {
LOG.warn(e)
rebuild()
}
}
fun addUsers(users: Collection<VcsUser>) {
for (user in users) {
addUser(user)
}
}
override fun getUsers(): Set<VcsUser> {
return try {
persistentEnumerator?.getAllDataObjects { true }?.toMutableSet() ?: emptySet()
}
catch (e: IOException) {
LOG.warn(e)
rebuild()
emptySet()
}
catch (pce: ProcessCanceledException) {
throw pce
}
catch (t: Throwable) {
LOG.error(t)
emptySet()
}
}
fun all(condition: (t: VcsUser) -> Boolean): Boolean {
return try {
persistentEnumerator?.iterateData(condition) ?: false
}
catch (e: IOException) {
LOG.warn(e)
rebuild()
false
}
catch (pce: ProcessCanceledException) {
throw pce
}
catch (t: Throwable) {
LOG.error(t)
false
}
}
private fun rebuild() {
if (persistentEnumerator?.isCorrupted == true) {
_persistentEnumerator.getAndSet(null)?.let { oldEnumerator ->
ApplicationManager.getApplication().executeOnPooledThread {
try {
oldEnumerator.close()
}
catch (_: IOException) {
}
finally {
initEnumerator()
}
}
}
}
}
fun flush() {
persistentEnumerator?.force()
}
override fun dispose() {
try {
persistentEnumerator?.close()
}
catch (e: IOException) {
LOG.warn(e)
}
}
companion object {
private val LOG = Logger.getInstance(VcsUserRegistryImpl::class.java)
private val USER_CACHE_APP_DIR = File(PathManager.getSystemPath(), "vcs-users")
private const val STORAGE_VERSION = 2
}
}
class VcsUserKeyDescriptor(private val userRegistry: VcsUserRegistry) : KeyDescriptor<VcsUser> {
@Throws(IOException::class)
override fun save(out: DataOutput, value: VcsUser) {
IOUtil.writeUTF(out, value.name)
IOUtil.writeUTF(out, value.email)
}
@Throws(IOException::class)
override fun read(`in`: DataInput): VcsUser {
val name = IOUtil.readUTF(`in`)
val email = IOUtil.readUTF(`in`)
return userRegistry.createUser(name, email)
}
override fun getHashCode(value: VcsUser): Int {
return value.hashCode()
}
override fun isEqual(val1: VcsUser, val2: VcsUser): Boolean {
return val1 == val2
}
}
| apache-2.0 | 6c3e42969571df330a656294c8e0dfbb | 27.624277 | 140 | 0.659532 | 4.280035 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/model/VirtualStorageDevice.kt | 2 | 1925 | package com.github.kerubistan.kerub.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonTypeName
import com.fasterxml.jackson.annotation.JsonView
import com.github.kerubistan.kerub.model.expectations.VirtualStorageDeviceReference
import com.github.kerubistan.kerub.model.expectations.VirtualStorageExpectation
import com.github.kerubistan.kerub.model.index.Indexed
import com.github.kerubistan.kerub.model.views.Simple
import com.github.kerubistan.kerub.utils.validateSize
import io.github.kerubistan.kroki.collections.concat
import org.hibernate.search.annotations.DocumentId
import org.hibernate.search.annotations.Field
import java.math.BigInteger
import java.util.UUID
import kotlin.reflect.KClass
@JsonTypeName("virtual-storage")
data class
VirtualStorageDevice(
@DocumentId
@JsonProperty("id")
override val id: UUID = UUID.randomUUID(),
@Field
val size: BigInteger,
@Field
val readOnly: Boolean = false,
@Field
override
val expectations: List<VirtualStorageExpectation> = listOf(),
@Field
override
val name: String,
@Field
@JsonView(Simple::class)
@JsonProperty("owner")
override val owner: AssetOwner? = null,
override val recycling: Boolean = false
) : Entity<UUID>, Constrained<VirtualStorageExpectation>, Named, Asset, Recyclable, Indexed<VirtualStorageDeviceIndex> {
init {
size.validateSize("size")
}
override fun references(): Map<KClass<out Asset>, List<UUID>> {
val mapOf: Map<KClass<out Asset>, List<UUID>> = mapOf(
VirtualStorageDevice::class to expectations
.filter { it is VirtualStorageDeviceReference }
.map { (it as VirtualStorageDeviceReference).virtualStorageDeviceReferences }
.concat()
)
return mapOf.filter { it.value.isNotEmpty() }
}
@get:JsonIgnore
override val index by lazy { VirtualStorageDeviceIndex(this) }
} | apache-2.0 | 062b9415b6e7d1c0b83ca2c741f4446f | 30.064516 | 120 | 0.784416 | 3.936605 | false | false | false | false |
Subsets and Splits