repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
pavelaizen/SoundZones
app/src/main/java/com/gm/soundzones/manager/LocalMusicPlayer.kt
1
2660
package com.gm.soundzones.manager import android.media.MediaPlayer import com.gm.soundzones.log import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.async /** * Created by Pavel Aizendorf on 25/09/2017. */ class LocalMusicPlayer(baselineVolume: Int) : AudioPlayer(baselineVolume) { suspend override fun setVolumeMaster(volume: Int): Result { val adaptedVolume = volume / 100.toFloat() mp1?.setVolume(adaptedVolume, adaptedVolume).also { log("adaptedVolume $adaptedVolume") } return Result.SUCCESS } suspend override fun setVolumeSecondary(volume: Int): Result { val adaptedVolume = volume / 100.toFloat() mp2?.setVolume(adaptedVolume, adaptedVolume).also { log("adaptedVolume $adaptedVolume") } return Result.SUCCESS } private var mp1: MediaPlayer? = null private var mp2: MediaPlayer? = null private var mpNoise: MediaPlayer? = null private val primaryVolume:Float = getMasterBaselineVolume()/100f private val secondaryVolume:Float = getSlaveBaselineVolume(getMasterBaselineVolume())/100f init { log("primary volume ${getMasterBaselineVolume()}") log("secondary volume ${getSlaveBaselineVolume(getMasterBaselineVolume())}") } override suspend fun playTrack1(audioFile: String) = MediaPlayer().let { mp1 = it initAndPlay(it, audioFile, primaryVolume) } override suspend fun playTrack2(audioFile: String) = MediaPlayer().let { mp2 = it initAndPlay(it, audioFile, secondaryVolume) } override suspend fun playNoise(noiseFile: String) = MediaPlayer().let { mpNoise = it initAndPlay(it, noiseFile, 1f) } override fun stop(){ releasePlayer(mp1).also { mp1 = null } releasePlayer(mp2).also { mp2 = null } releasePlayer(mpNoise).also { mpNoise = null } } private fun releasePlayer(player: MediaPlayer?) { player?.let { if (it.isPlaying) { it.stop() } it.release() } } private suspend fun initAndPlay(player: MediaPlayer, filePath: String, volume:Float) = async(CommonPool) { log("playing ${filePath} with volume ${volume*100}") player.setDataSource(filePath) player.setVolume(volume, volume) player.setOnPreparedListener { player.start() } player.isLooping = true player.prepare() Result.SUCCESS }.await() }
apache-2.0
37751a0d26fb2ce992495df3583a0ecf
29.227273
94
0.625564
4.578313
false
false
false
false
tasks/tasks
app/src/main/java/com/todoroo/astrid/gtasks/GtasksListService.kt
1
2391
/* * Copyright (c) 2012 Todoroo Inc * * See the file "LICENSE" for the full license governing this code. */ package com.todoroo.astrid.gtasks import com.google.api.services.tasks.model.TaskList import com.todoroo.astrid.service.TaskDeleter import org.tasks.LocalBroadcastManager import org.tasks.data.GoogleTaskAccount import org.tasks.data.GoogleTaskList import org.tasks.data.GoogleTaskListDao import timber.log.Timber import java.util.* import javax.inject.Inject class GtasksListService @Inject constructor( private val googleTaskListDao: GoogleTaskListDao, private val taskDeleter: TaskDeleter, private val localBroadcastManager: LocalBroadcastManager) { /** * Reads in remote list information and updates local list objects. * * @param remoteLists remote information about your lists */ @Synchronized suspend fun updateLists(account: GoogleTaskAccount, remoteLists: List<TaskList>) { val lists = googleTaskListDao.getLists(account.account!!) val previousLists: MutableSet<Long> = HashSet() for (list in lists) { previousLists.add(list.id) } for (i in remoteLists.indices) { val remote = remoteLists[i] val id = remote.id var local: GoogleTaskList? = null for (list in lists) { if (list.remoteId == id) { local = list break } } val title = remote.title if (local == null) { val byRemoteId = googleTaskListDao.findExistingList(id) if (byRemoteId != null) { byRemoteId.account = account.account local = byRemoteId } else { Timber.d("Adding new gtask list %s", title) local = GoogleTaskList() local.account = account.account local.remoteId = id } } local.title = title googleTaskListDao.insertOrReplace(local) previousLists.remove(local.id) } // check for lists that aren't on remote server for (listId in previousLists) { taskDeleter.delete(googleTaskListDao.getById(listId)!!) } localBroadcastManager.broadcastRefreshList() } }
gpl-3.0
296204d965d0335bc6a6920dec56d573
33.666667
86
0.602258
4.782
false
false
false
false
NextFaze/dev-fun
devfun/src/main/java/com/nextfaze/devfun/internal/Reflected.kt
1
9724
package com.nextfaze.devfun.internal import android.text.SpannableStringBuilder import com.nextfaze.devfun.core.devFun import com.nextfaze.devfun.function.FunctionArgs import com.nextfaze.devfun.inject.InstanceProvider import com.nextfaze.devfun.inject.isSubclassOf import com.nextfaze.devfun.internal.log.* import com.nextfaze.devfun.internal.reflect.* import com.nextfaze.devfun.internal.string.* import com.nextfaze.devfun.invoke.doInvoke import com.nextfaze.devfun.invoke.parameterInstances import com.nextfaze.devfun.invoke.receiverInstance import java.lang.reflect.Field import java.lang.reflect.Method import kotlin.reflect.KClass import kotlin.reflect.KFunction import kotlin.reflect.KMutableProperty import kotlin.reflect.KProperty import kotlin.reflect.KProperty0 import kotlin.reflect.KProperty1 import kotlin.reflect.full.IllegalPropertyDelegateAccessException import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.jvm.isAccessible import kotlin.reflect.jvm.javaMethod import kotlin.reflect.jvm.kotlinProperty private val log = logger("Reflection") private val KProperty<*>.simpleName get() = "${type.simpleName}${if (returnType.isMarkedNullable) "?" else ""}" private val KProperty<*>.type get() = returnType.classifier as KClass<*> @Suppress("UNCHECKED_CAST") private fun KProperty<*>.isUninitialized(receiver: Any?): Boolean { fun tryGet() = try { when (this) { is KProperty0<*> -> (getDelegate() as? Lazy<*>)?.isInitialized() == false is KProperty1<*, *> -> ((this as KProperty1<Any?, Any>).getDelegate(receiver) as? Lazy<*>)?.isInitialized() == false else -> false } } catch (t: IllegalPropertyDelegateAccessException) { log.d(t) { "Kotlin Bug: Ignoring IllegalPropertyDelegateAccessException for $this" } null } isAccessible = true return tryGet() ?: tryGet() ?: false // try it again if it first fails } interface ReflectedMethod : Function0<Any?>, Function1<InstanceProvider, Any?> { val method: Method val clazz: KClass<*> val name: String val isProperty: Boolean val isStatic: Boolean val fieldName: String val parameterTypes: List<KClass<*>> fun receiverInstance(instanceProvider: InstanceProvider): Any? val receiver: Any? fun parameterInstances(instanceProvider: InstanceProvider, suppliedArgs: FunctionArgs = null): FunctionArgs val parameters: FunctionArgs } interface ReflectedProperty { val field: Field? val property: KProperty<*> val getter: Method? val setter: Method? val desc: String val descWithDeclaringClass: String fun getDesc(withDeclaringClass: Boolean = false): String val isLateinit: Boolean val type: KClass<*> fun getValue(instanceProvider: InstanceProvider): Any? fun setValue(instanceProvider: InstanceProvider, value: Any?): Any? var value: Any? fun isUninitialized(receiver: Any?): Boolean val isUninitialized: Boolean } fun Method.toReflected(instanceProviders: InstanceProvider = devFun.instanceProviders): ReflectedMethod = ReflectedMethodImpl(this, instanceProviders).let { when { it.isProperty -> ReflectedPropertyImpl(it, instanceProviders) else -> it } } private class ReflectedPropertyImpl(val reflectedMethod: ReflectedMethod, val instanceProviders: InstanceProvider) : ReflectedProperty, ReflectedMethod by reflectedMethod { override fun invoke() = value override fun invoke(instanceProvider: InstanceProvider) = getValue(instanceProvider) override val field by lazy { try { clazz.java.getDeclaredField(fieldName).apply { isAccessible = true } } catch (ignore: NoSuchFieldException) { null // is property without backing field (i.e. has custom getter/setter) } } override val property by lazy { when { field != null -> field!!.kotlinProperty!! else -> clazz.declaredMemberProperties.first { it.name == fieldName } }.apply { isAccessible = true } } override val getter by lazy { try { property.getter.javaMethod } catch (t: UnsupportedOperationException) { // "Packages and file facades are not yet supported in Kotlin reflection" // file-level property val getterName = "get${method.name.substringBeforeLast('$').capitalize()}" method.declaringClass.getDeclaredMethod(getterName, *method.parameterTypes) }?.apply { isAccessible = true } } override val setter by lazy { try { val property = property if (property is KMutableProperty<*>) property.setter.javaMethod else null } catch (t: UnsupportedOperationException) { // "Packages and file facades are not yet supported in Kotlin reflection" // file-level property val setterName = "set${method.name.substringBeforeLast('$').capitalize()}" method.declaringClass.getDeclaredMethod(setterName, *method.parameterTypes) }?.apply { isAccessible = true } } override val desc by lazy { getDesc(false) } override val descWithDeclaringClass by lazy { getDesc(true) } override fun getDesc(withDeclaringClass: Boolean): String { val lateInit = if (property.isLateinit) "lateinit " else "" val varType = if (property is KMutableProperty<*>) "var" else "val" val declaringClass = if (withDeclaringClass) clazz.simpleName?.let { "$it." } ?: "" else "" return "$lateInit$varType $declaringClass$fieldName: ${property.simpleName}" } override val isLateinit by lazy { property.isLateinit } override val type by lazy { property.type } override fun getValue(instanceProvider: InstanceProvider) = when { getter != null -> getter!!.doInvoke(instanceProvider) else -> this.field?.get(receiverInstance(instanceProvider)) } override fun setValue(instanceProvider: InstanceProvider, value: Any?) = when { setter != null -> setter!!.doInvoke(instanceProvider, listOf(value)) else -> this.field?.set(receiverInstance(instanceProvider), value) } override var value: Any? get() = getValue(instanceProviders) set(value) { setValue(instanceProviders, value) } override fun isUninitialized(receiver: Any?) = property.isUninitialized(receiver) override val isUninitialized: Boolean get() = isUninitialized(receiver) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ReflectedPropertyImpl if (reflectedMethod != other.reflectedMethod) return false if (isProperty != other.isProperty) return false return true } override fun hashCode(): Int { var result = reflectedMethod.hashCode() result = 31 * result + isProperty.hashCode() return result } override fun toString() = "ReflectedProperty(reflected=$reflectedMethod)" } internal fun ReflectedProperty.toStringRepresentation(withDeclaringClass: Boolean = false): CharSequence { val isUninitialized by lazy { isUninitialized } val value = value return SpannableStringBuilder().apply { this += getDesc(withDeclaringClass) this += " = " when { isLateinit && value == null -> this += i("undefined") isUninitialized -> this += i("uninitialized") value != null && type.isSubclassOf<CharSequence>() -> this += """"$value"""" else -> this += "$value" } if (isUninitialized) { this += "\n" this += color(scale(i("\t(tap will initialize)"), 0.85f), 0xFFAAAAAA.toInt()) } } } private data class ReflectedMethodImpl(override val method: Method, val instanceProviders: InstanceProvider) : ReflectedMethod { init { method.isAccessible = true } override val clazz = method.declaringClass.kotlin override val name: String = method.name override val isProperty = method.isProperty override val isStatic = method.isStatic override val fieldName by lazy { method.name.substringBefore('$') } override val parameterTypes by lazy { method.parameterTypes.map { it.kotlin } } override fun receiverInstance(instanceProvider: InstanceProvider) = method.receiverInstance(instanceProvider) override val receiver get() = receiverInstance(instanceProviders) override fun parameterInstances(instanceProvider: InstanceProvider, suppliedArgs: FunctionArgs) = method.parameterInstances(instanceProvider, suppliedArgs) override val parameters get() = parameterInstances(instanceProviders) override fun invoke(instanceProvider: InstanceProvider) = method.doInvoke(instanceProvider) override fun invoke() = invoke(instanceProviders) } internal fun KFunction<*>.toSignatureString(removePackageString: String? = null) = toString().toSignatureString(removePackageString) internal fun KProperty<*>.toSignatureString(removePackageString: String? = null) = toString().toSignatureString(removePackageString) private val stdPackages = listOf("kotlin", "java.util", "java.lang").map { Regex("([\\s(\\[<])$it.") } private fun String.toSignatureString(removePackageString: String? = null): String { var signature = this stdPackages.forEach { signature = it.replace(signature, "\$1") } if (removePackageString == null) return signature val regex = Regex(removePackageString.split(".").joinToString("\\.") { "($it)?" }) return regex.replace(signature, "") }
apache-2.0
f6192d51ea2f4201884fa74433ba7a8b
38.209677
135
0.694056
4.755012
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mcp/McpModule.kt
1
2252
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.AbstractModule import com.demonwav.mcdev.platform.PlatformType import com.demonwav.mcdev.platform.mcp.srg.SrgManager import com.demonwav.mcdev.translations.TranslationFileListener import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiClass import com.intellij.psi.PsiMethod import com.intellij.util.messages.MessageBusConnection import javax.swing.Icon class McpModule(facet: MinecraftFacet) : AbstractModule(facet) { private lateinit var connection: MessageBusConnection private val settings: McpModuleSettings = McpModuleSettings.getInstance(module) val accessTransformers = mutableSetOf<VirtualFile>() var srgManager: SrgManager? = null private set override fun init() { initSrg() connection = project.messageBus.connect() connection.subscribe(VirtualFileManager.VFS_CHANGES, TranslationFileListener) } private fun initSrg() { val settings = getSettings() val file = settings.mappingFile ?: return val srgType = settings.srgType ?: return srgManager = SrgManager.getInstance(file, srgType) srgManager?.parse() } override val moduleType = McpModuleType override val type = PlatformType.MCP override val icon: Icon? = null override fun writeErrorMessageForEventParameter(eventClass: PsiClass, method: PsiMethod) = "" fun getSettings() = settings.state fun updateSettings(data: McpModuleSettings.State) { this.settings.loadState(data) val mappingFile = data.mappingFile ?: return val srgType = data.srgType ?: return srgManager = SrgManager.getInstance(mappingFile, srgType) srgManager?.parse() } fun addAccessTransformerFile(file: VirtualFile) { accessTransformers.add(file) } override fun dispose() { super.dispose() connection.disconnect() accessTransformers.clear() srgManager = null } }
mit
f2b673b8052709e85fb34e09d9aa9126
27.871795
97
0.722469
4.62423
false
false
false
false
bbqapp/bbqapp-android
app/src/main/kotlin/org/bbqapp/android/service/GeocodeService.kt
1
2219
/* * The MIT License (MIT) * * Copyright (c) 2015 bbqapp * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.bbqapp.android.service import android.content.Context import android.location.Geocoder import android.location.Location import com.google.android.gms.maps.model.LatLng import org.bbqapp.android.extension.getLatLng import rx.Observable fun Geocoder.resolve(text: String, maxResults: Int) = Observable.fromCallable { getFromLocationName(text, maxResults) } fun Geocoder.resolve(lat: Double, long: Double, maxResults: Int) = Observable.fromCallable { getFromLocation(lat, long, maxResults) } fun Geocoder.resolve(latLng: LatLng, maxResults: Int) = resolve(latLng.latitude, latLng.longitude, maxResults) fun Geocoder.resolve(location: Location, maxResults: Int) = resolve(location.getLatLng(), maxResults) class GeocodeService(private val context: Context) { fun resolve(location: Location, maxResults: Int) = Geocoder(context).resolve(location, maxResults) fun resolve(position: LatLng, maxResults: Int) = Geocoder(context).resolve(position, maxResults) fun resolve(location: String, maxResults: Int) = Geocoder(context).resolve(location, maxResults) }
mit
b77b40caddc168f4e2d1a03df84c4ff0
50.627907
134
0.775575
4.259117
false
false
false
false
android/health-samples
health-connect/HealthConnectSample/app/src/main/java/com/example/healthconnectsample/presentation/screen/exercisesession/ExerciseSessionScreen.kt
1
7035
/* * Copyright 2022 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. */ package com.example.healthconnectsample.presentation.screen.exercisesession import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.health.connect.client.permission.HealthPermission import androidx.health.connect.client.records.ExerciseSessionRecord import com.example.healthconnectsample.R import com.example.healthconnectsample.data.ExerciseSession import com.example.healthconnectsample.data.HealthConnectAppInfo import com.example.healthconnectsample.presentation.component.ExerciseSessionRow import com.example.healthconnectsample.presentation.theme.HealthConnectTheme import java.time.ZonedDateTime import java.util.UUID /** * Shows a list of [ExerciseSessionRecord]s from today. */ @Composable fun ExerciseSessionScreen( permissions: Set<HealthPermission>, permissionsGranted: Boolean, sessionsList: List<ExerciseSession>, uiState: ExerciseSessionViewModel.UiState, onInsertClick: () -> Unit = {}, onDetailsClick: (String) -> Unit = {}, onDeleteClick: (String) -> Unit = {}, onError: (Throwable?) -> Unit = {}, onPermissionsResult: () -> Unit = {}, onPermissionsLaunch: (Set<HealthPermission>) -> Unit = {} ) { // Remember the last error ID, such that it is possible to avoid re-launching the error // notification for the same error when the screen is recomposed, or configuration changes etc. val errorId = rememberSaveable { mutableStateOf(UUID.randomUUID()) } LaunchedEffect(uiState) { // If the initial data load has not taken place, attempt to load the data. if (uiState is ExerciseSessionViewModel.UiState.Uninitialized) { onPermissionsResult() } // The [ExerciseSessionViewModel.UiState] provides details of whether the last action was a // success or resulted in an error. Where an error occurred, for example in reading and // writing to Health Connect, the user is notified, and where the error is one that can be // recovered from, an attempt to do so is made. if (uiState is ExerciseSessionViewModel.UiState.Error && errorId.value != uiState.uuid) { onError(uiState.exception) errorId.value = uiState.uuid } } if (uiState != ExerciseSessionViewModel.UiState.Uninitialized) { LazyColumn( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally ) { if (!permissionsGranted) { item { Button( onClick = { onPermissionsLaunch(permissions) } ) { Text(text = stringResource(R.string.permissions_button_label)) } } } else { item { Button( modifier = Modifier .fillMaxWidth() .height(48.dp) .padding(4.dp), onClick = { onInsertClick() } ) { Text(stringResource(id = R.string.insert_exercise_session)) } } items(sessionsList) { session -> val appInfo = session.sourceAppInfo ExerciseSessionRow( start = session.startTime, end = session.endTime, uid = session.id, name = session.title ?: stringResource(R.string.no_title), sourceAppName = appInfo?.appLabel ?: stringResource(R.string.unknown_app), sourceAppIcon = appInfo?.icon, onDeleteClick = { uid -> onDeleteClick(uid) }, onDetailsClick = { uid -> onDetailsClick(uid) } ) } } } } } @Preview @Composable fun ExerciseSessionScreenPreview() { val context = LocalContext.current HealthConnectTheme { val runningStartTime = ZonedDateTime.now() val runningEndTime = runningStartTime.plusMinutes(30) val walkingStartTime = ZonedDateTime.now().minusMinutes(120) val walkingEndTime = walkingStartTime.plusMinutes(30) val appInfo = HealthConnectAppInfo( packageName = "com.example.myfitnessapp", appLabel = "My Fitness App", icon = context.getDrawable(R.drawable.ic_launcher_foreground)!! ) ExerciseSessionScreen( permissions = setOf(), permissionsGranted = true, sessionsList = listOf( ExerciseSession( title = "Running", startTime = runningStartTime, endTime = runningEndTime, id = UUID.randomUUID().toString(), sourceAppInfo = appInfo ), ExerciseSession( title = "Walking", startTime = walkingStartTime, endTime = walkingEndTime, id = UUID.randomUUID().toString(), sourceAppInfo = appInfo ) ), uiState = ExerciseSessionViewModel.UiState.Done ) } }
apache-2.0
35193373036e6fb5ebe1946d4ceb0df2
39.2
99
0.613362
5.357959
false
false
false
false
openstreetview/android
app/src/main/java/com/telenav/osv/data/collector/obddata/sensors/type/RpmObdSensor.kt
1
1377
package com.telenav.osv.data.collector.obddata.sensors.type import timber.log.Timber /** * Created by ovidiuc2 on 11/10/16. */ /** * class used for extracting the rpm sensor value from OBD */ class RpmObdSensor : CarObdSensor<Double?> { /** * the first byte which follows the 41 0C response is A, the second is B * rpm is: (256*A+B)/4 * * @param hexResponse * @return Engine speed in rpm */ override fun convertValue(hexResponse: String): Double? { var hexResponse = hexResponse hexResponse = hexResponse.replace("\r".toRegex(), " ").replace(" ".toRegex(), "") val responseData: String return if (hexResponse.length > 4) { responseData = hexResponse.substring(hexResponse.length - 4) try { val a = Integer.decode("0x" + responseData[0] + responseData[1]) val b = Integer.decode("0x" + responseData[2] + responseData[3]) (256 * a + b) / 4.0 } catch (e: NumberFormatException) { Timber.tag(TAG).e(e, "Invalid response data for rpm: %s", responseData) null } } else { Timber.tag(TAG).e("word has less than 4 characters: %s", hexResponse) null } } companion object { val TAG = RpmObdSensor::class.java.simpleName } }
lgpl-3.0
61af85e4c1f411c9ca2a8b30229451dd
31.809524
89
0.576616
3.90085
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/LinkCreator.kt
1
6950
/* * 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 import android.net.Uri import de.vanita5.twittnuker.TwittnukerConstants.* import de.vanita5.twittnuker.annotation.AccountType import de.vanita5.twittnuker.extension.model.originalId import de.vanita5.twittnuker.model.ParcelableStatus import de.vanita5.twittnuker.model.ParcelableUser import de.vanita5.twittnuker.model.UserKey /** * Creates links for sharing */ object LinkCreator { private val AUTHORITY_TWITTER = "twitter.com" private val AUTHORITY_FANFOU = "fanfou.com" fun getTwidereStatusLink(accountKey: UserKey?, statusId: String): Uri { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_STATUS) if (accountKey != null) { builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString()) } builder.appendQueryParameter(QUERY_PARAM_STATUS_ID, statusId) return builder.build() } fun getTwidereUserLink(accountKey: UserKey?, userKey: UserKey?, screenName: String?): Uri { return getTwidereUserRelatedLink(AUTHORITY_USER, accountKey, userKey, screenName) } fun getTwidereUserRelatedLink(authority: String, accountKey: UserKey?, userKey: UserKey?, screenName: String?): Uri { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(authority) if (accountKey != null) { builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString()) } if (userKey != null) { builder.appendQueryParameter(QUERY_PARAM_USER_KEY, userKey.toString()) } if (screenName != null) { builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName) } return builder.build() } fun getTwidereUserListRelatedLink(authority: String, accountKey: UserKey?, listId: String?, userKey: UserKey?, screenName: String?, listName: String?): Uri { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(authority) if (accountKey != null) { builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString()) } if (listId != null) { builder.appendQueryParameter(QUERY_PARAM_LIST_ID, listId) } if (userKey != null) { builder.appendQueryParameter(QUERY_PARAM_USER_KEY, userKey.toString()) } if (screenName != null) { builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName) } if (listName != null) { builder.appendQueryParameter(QUERY_PARAM_LIST_NAME, listName) } return builder.build() } fun getTwitterUserListLink(userScreenName: String, listName: String): Uri { val builder = Uri.Builder() builder.scheme(SCHEME_HTTPS) builder.authority(AUTHORITY_TWITTER) builder.appendPath(userScreenName) builder.appendPath(listName) return builder.build() } fun getStatusWebLink(status: ParcelableStatus): Uri { status.extras?.external_url?.takeIf(String::isNotEmpty)?.let { return Uri.parse(it) } if (USER_TYPE_FANFOU_COM == status.account_key.host) { return getFanfouStatusLink(status.id) } return getTwitterStatusLink(status.user_screen_name, status.originalId) } fun getQuotedStatusWebLink(status: ParcelableStatus): Uri { val extras = status.extras if (extras != null) { extras.quoted_external_url?.takeIf(String::isNotEmpty)?.let { return Uri.parse(it) } extras.external_url?.takeIf(String::isNotEmpty)?.let { return Uri.parse(it) } } if (USER_TYPE_FANFOU_COM == status.account_key.host) { return getFanfouStatusLink(status.quoted_id) } return getTwitterStatusLink(status.quoted_user_screen_name, status.quoted_id) } fun getUserWebLink(user: ParcelableUser): Uri { if (user.extras != null && user.extras?.statusnet_profile_url != null) { return Uri.parse(user.extras?.statusnet_profile_url) } when (user.user_type) { AccountType.FANFOU -> return getFanfouUserLink(user.key.id) AccountType.MASTODON -> { val host = (user.key.host ?: user.account_key?.host)!! // Let it crash return getMastodonUserLink(host, user.screen_name) } } return getTwitterUserLink(user.screen_name) } internal fun getTwitterStatusLink(screenName: String, statusId: String): Uri { val builder = Uri.Builder() builder.scheme(SCHEME_HTTPS) builder.authority(AUTHORITY_TWITTER) builder.appendPath(screenName) builder.appendPath("status") builder.appendPath(statusId) return builder.build() } internal fun getTwitterUserLink(screenName: String): Uri { val builder = Uri.Builder() builder.scheme(SCHEME_HTTPS) builder.authority(AUTHORITY_TWITTER) builder.appendPath(screenName) return builder.build() } internal fun getFanfouStatusLink(id: String): Uri { val builder = Uri.Builder() builder.scheme(SCHEME_HTTP) builder.authority(AUTHORITY_FANFOU) builder.appendPath("statuses") builder.appendPath(id) return builder.build() } internal fun getFanfouUserLink(id: String): Uri { val builder = Uri.Builder() builder.scheme(SCHEME_HTTP) builder.authority(AUTHORITY_FANFOU) builder.appendPath(id) return builder.build() } internal fun getMastodonUserLink(host: String, username: String): Uri { val builder = Uri.Builder() builder.scheme(SCHEME_HTTPS) builder.authority(host) builder.appendEncodedPath(Uri.encode("@$username", "@")) return builder.build() } }
gpl-3.0
bf8ab26ae2a9efafc92954bb2bda8beb
36.171123
95
0.653381
4.42112
false
false
false
false
Nunnery/MythicDrops
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/items/MythicCustomItemManager.kt
1
2407
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tealcube.minecraft.bukkit.mythicdrops.items import com.tealcube.minecraft.bukkit.mythicdrops.api.choices.Choice import com.tealcube.minecraft.bukkit.mythicdrops.api.choices.WeightedChoice import com.tealcube.minecraft.bukkit.mythicdrops.api.items.CustomItem import com.tealcube.minecraft.bukkit.mythicdrops.api.items.CustomItemManager class MythicCustomItemManager : CustomItemManager { private val managedCustomItems = mutableMapOf<String, CustomItem>() override fun get(): Set<CustomItem> = managedCustomItems.values.toSet() override fun contains(id: String): Boolean = managedCustomItems.containsKey(id.toLowerCase()) override fun add(toAdd: CustomItem) { managedCustomItems[toAdd.name.toLowerCase()] = toAdd } override fun remove(id: String) { managedCustomItems.remove(id.toLowerCase()) } override fun getById(id: String): CustomItem? = managedCustomItems[id.toLowerCase()] override fun clear() { managedCustomItems.clear() } override fun random(): CustomItem? = Choice.between(get()).choose() override fun randomByWeight(block: (CustomItem) -> Boolean): CustomItem? = WeightedChoice.between(get()).choose(block) }
mit
ef438b698ae77fd4426cc4521e91fbb4
43.574074
105
0.75779
4.457407
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/print/PrintModule.kt
2
5529
package abi44_0_0.expo.modules.print import android.content.Context import android.os.Bundle import android.print.PrintAttributes import android.print.PrintDocumentAdapter import android.print.PrintManager import abi44_0_0.expo.modules.core.ExportedModule import abi44_0_0.expo.modules.core.ModuleRegistry import abi44_0_0.expo.modules.core.Promise import abi44_0_0.expo.modules.core.interfaces.ActivityProvider import abi44_0_0.expo.modules.core.interfaces.ExpoMethod import java.io.File import java.io.IOException class PrintModule(context: Context) : ExportedModule(context) { private val ORIENTATION_PORTRAIT = "portrait" private val ORIENTATION_LANDSCAPE = "landscape" private val jobName = "Printing" private lateinit var moduleRegistry: ModuleRegistry override fun onCreate(moduleRegistry: ModuleRegistry) { this.moduleRegistry = moduleRegistry } override fun getName(): String { return "ExponentPrint" } override fun getConstants(): MutableMap<String, Any?> { return hashMapOf( "Orientation" to hashMapOf( "portrait" to ORIENTATION_PORTRAIT, "landscape" to ORIENTATION_LANDSCAPE ) ) } @ExpoMethod fun print(options: Map<String?, Any?>, promise: Promise) { val html = if (options.containsKey("html")) { options["html"] as String? } else { null } val uri = if (options.containsKey("uri")) { options["uri"] as String? } else { null } if (html != null) { // Renders HTML to PDF and then prints try { val renderTask = PrintPDFRenderTask(context, options, moduleRegistry) renderTask.render( null, object : PrintPDFRenderTask.Callbacks() { override fun onRenderFinished(document: PrintDocumentAdapter, outputFile: File?, numberOfPages: Int) { printDocumentToPrinter(document, options) promise.resolve(null) } override fun onRenderError(errorCode: String?, errorMessage: String?, exception: Exception?) { promise.reject(errorCode, errorMessage, exception) } } ) } catch (e: Exception) { promise.reject("E_CANNOT_PRINT", "There was an error while trying to print HTML.", e) } } else { // Prints from given URI (file path or base64 data URI starting with `data:*;base64,`) try { val pda = PrintDocumentAdapter(context, promise, uri) printDocumentToPrinter(pda, options) promise.resolve(null) } catch (e: Exception) { promise.reject("E_CANNOT_PRINT", "There was an error while trying to print a file.", e) } } } @ExpoMethod fun printToFileAsync(options: Map<String?, Any?>, promise: Promise) { val filePath: String try { filePath = FileUtils.generateFilePath(context) } catch (e: IOException) { promise.reject("E_PRINT_FAILED", "An unknown I/O exception occurred.", e) return } val renderTask = PrintPDFRenderTask(context, options, moduleRegistry) renderTask.render( filePath, object : PrintPDFRenderTask.Callbacks() { override fun onRenderFinished(document: PrintDocumentAdapter, outputFile: File?, numberOfPages: Int) { val uri = FileUtils.uriFromFile(outputFile).toString() var base64: String? = null if (options.containsKey("base64") && (options["base64"] as Boolean? == true)) { try { base64 = outputFile?.let { FileUtils.encodeFromFile(it) } } catch (e: IOException) { promise.reject("E_PRINT_BASE64_FAILED", "An error occurred while encoding PDF file to base64 string.", e) return } } promise.resolve( Bundle().apply { putString("uri", uri) putInt("numberOfPages", numberOfPages) if (base64 != null) putString("base64", base64) } ) } override fun onRenderError(errorCode: String?, errorMessage: String?, exception: Exception?) { promise.reject(errorCode, errorMessage, exception) } } ) } private fun printDocumentToPrinter(document: PrintDocumentAdapter, options: Map<String?, Any?>) { val printManager = moduleRegistry .getModule(ActivityProvider::class.java) .currentActivity ?.getSystemService(Context.PRINT_SERVICE) as? PrintManager val attributes = getAttributesFromOptions(options) printManager?.print(jobName, document, attributes.build()) } private fun getAttributesFromOptions(options: Map<String?, Any?>): PrintAttributes.Builder { val orientation = if (options.containsKey("orientation")) { options["orientation"] as String? } else { null } val builder = PrintAttributes.Builder() // @tsapeta: Unfortunately these attributes might be ignored on some devices or Android versions, // in other words it might not change the default orientation in the print dialog, // however the user can change it there. if (ORIENTATION_LANDSCAPE == orientation) { builder.setMediaSize(PrintAttributes.MediaSize.UNKNOWN_LANDSCAPE) } else { builder.setMediaSize(PrintAttributes.MediaSize.UNKNOWN_PORTRAIT) } // @tsapeta: It should just copy the document without adding extra margins, // document's margins can be controlled by @page block in CSS. builder.setMinMargins(PrintAttributes.Margins.NO_MARGINS) return builder } }
bsd-3-clause
16c21ae8970cd3475f570dec4178b106
34.902597
119
0.662688
4.528256
false
false
false
false
exponent/exponent
packages/expo-camera/android/src/main/java/expo/modules/camera/events/CameraMountErrorEvent.kt
2
891
package expo.modules.camera.events import androidx.core.util.Pools import android.os.Bundle import expo.modules.camera.CameraViewManager import expo.modules.core.interfaces.services.EventEmitter.BaseEvent class CameraMountErrorEvent private constructor() : BaseEvent() { private lateinit var message: String private fun init(message: String) { this.message = message } override fun getEventName() = CameraViewManager.Events.EVENT_ON_MOUNT_ERROR.toString() override fun getEventBody() = Bundle().apply { putString("message", message) } companion object { private val EVENTS_POOL = Pools.SynchronizedPool<CameraMountErrorEvent>(3) fun obtain(message: String): CameraMountErrorEvent { var event = EVENTS_POOL.acquire() if (event == null) { event = CameraMountErrorEvent() } event.init(message) return event } } }
bsd-3-clause
38b4e4301f81182d7acc7f32f7833e87
26
88
0.723906
4.283654
false
false
false
false
AndroidX/androidx
compose/runtime/runtime-lint/src/main/java/androidx/compose/runtime/lint/ComposableStateFlowValueDetector.kt
3
3572
/* * 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 * * 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:Suppress("UnstableApiUsage") package androidx.compose.runtime.lint import androidx.compose.lint.Name import androidx.compose.lint.Package import androidx.compose.lint.inheritsFrom import androidx.compose.lint.isInvokedWithinComposable import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.SourceCodeScanner import com.intellij.psi.PsiMethod import org.jetbrains.uast.USimpleNameReferenceExpression import org.jetbrains.uast.tryResolve import java.util.EnumSet /** * [Detector] that checks calls to StateFlow.value to make sure they don't happen inside the body * of a composable function / lambda. */ class ComposableStateFlowValueDetector : Detector(), SourceCodeScanner { override fun getApplicableUastTypes() = listOf(USimpleNameReferenceExpression::class.java) override fun createUastHandler(context: JavaContext) = object : UElementHandler() { override fun visitSimpleNameReferenceExpression(node: USimpleNameReferenceExpression) { // Look for a call to .value that comes from StateFlow if (node.identifier != "value") return val method = node.tryResolve() as? PsiMethod ?: return if (method.containingClass?.inheritsFrom(StateFlowName) == true) { if (node.isInvokedWithinComposable()) { context.report( StateFlowValueCalledInComposition, node, context.getNameLocation(node), "StateFlow.value should not be called within composition" ) } } } } companion object { val StateFlowValueCalledInComposition = Issue.create( "StateFlowValueCalledInComposition", "StateFlow.value should not be called within composition", "Calling StateFlow.value within composition will not observe changes to the " + "StateFlow, so changes might not be reflected within the composition. Instead " + "you should use stateFlow.collectAsState() to observe changes to the StateFlow, " + "and recompose when it changes.", Category.CORRECTNESS, 3, Severity.ERROR, Implementation( ComposableStateFlowValueDetector::class.java, EnumSet.of(Scope.JAVA_FILE, Scope.TEST_SOURCES) ) ) } } private val StateFlowPackageName = Package("kotlinx.coroutines.flow") private val StateFlowName = Name(StateFlowPackageName, "StateFlow")
apache-2.0
6656d9694d1a521f7a6b59b6a878234a
42.560976
99
0.704647
4.807537
false
false
false
false
AndroidX/androidx
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/text/selection/MultiWidgetSelectionDelegateTest.kt
3
90684
/* * Copyright 2019 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.compose.foundation.text.selection import androidx.activity.ComponentActivity import androidx.compose.foundation.text.InternalFoundationTextApi import androidx.compose.foundation.text.TEST_FONT_FAMILY import androidx.compose.foundation.text.TextDelegate import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.ExperimentalTextApi import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.createFontFamilyResolver import androidx.compose.ui.text.style.ResolvedTextDirection import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.sp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @MediumTest class MultiWidgetSelectionDelegateTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() private val fontFamily = TEST_FONT_FAMILY private val context = InstrumentationRegistry.getInstrumentation().context private val defaultDensity = Density(density = 1f) @OptIn(ExperimentalTextApi::class) private val fontFamilyResolver = createFontFamilyResolver(context) @Test fun getHandlePosition_StartHandle_invalid() { composeTestRule.setContent { val text = "hello world\n" val fontSize = 20.sp val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectableId = 1L val selectable = MultiWidgetSelectionDelegate( selectableId = selectableId, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val selectableInvalidId = 2L val startOffset = text.indexOf('h') val endOffset = text.indexOf('o') val selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = startOffset, selectableId = selectableInvalidId ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = endOffset, selectableId = selectableInvalidId ), handlesCrossed = false ) // Act. val coordinates = selectable.getHandlePosition( selection = selection, isStartHandle = true ) // Assert. assertThat(coordinates).isEqualTo(Offset.Zero) } } @Test fun getHandlePosition_EndHandle_invalid() { composeTestRule.setContent { val text = "hello world\n" val fontSize = 20.sp val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectableId = 1L val selectable = MultiWidgetSelectionDelegate( selectableId = selectableId, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val selectableInvalidId = 2L val startOffset = text.indexOf('h') val endOffset = text.indexOf('o') val selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = startOffset, selectableId = selectableInvalidId ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = endOffset, selectableId = selectableInvalidId ), handlesCrossed = false ) // Act. val coordinates = selectable.getHandlePosition( selection = selection, isStartHandle = false ) // Assert. assertThat(coordinates).isEqualTo(Offset.Zero) } } @Test fun getHandlePosition_StartHandle_not_cross_ltr() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectableId = 1L val selectable = MultiWidgetSelectionDelegate( selectableId = selectableId, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val startOffset = text.indexOf('h') val endOffset = text.indexOf('o') val selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = startOffset, selectableId = selectableId ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = endOffset, selectableId = selectableId ), handlesCrossed = false ) // Act. val coordinates = selectable.getHandlePosition( selection = selection, isStartHandle = true ) // Assert. assertThat(coordinates).isEqualTo( Offset((fontSizeInPx * startOffset), fontSizeInPx) ) } @Test fun getHandlePosition_StartHandle_cross_ltr() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectableId = 1L val selectable = MultiWidgetSelectionDelegate( selectableId = selectableId, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val startOffset = text.indexOf('o') val endOffset = text.indexOf('h') val selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = startOffset, selectableId = selectableId ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = endOffset, selectableId = selectableId ), handlesCrossed = true ) // Act. val coordinates = selectable.getHandlePosition( selection = selection, isStartHandle = true ) // Assert. assertThat(coordinates).isEqualTo( Offset((fontSizeInPx * startOffset), fontSizeInPx) ) } @Test fun getHandlePosition_StartHandle_not_cross_rtl() { val text = "\u05D0\u05D1\u05D2 \u05D3\u05D4\u05D5\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectableId = 1L val selectable = MultiWidgetSelectionDelegate( selectableId = selectableId, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val startOffset = text.indexOf('\u05D1') val endOffset = text.indexOf('\u05D5') val selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = startOffset, selectableId = selectableId ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = endOffset, selectableId = selectableId ), handlesCrossed = false ) // Act. val coordinates = selectable.getHandlePosition( selection = selection, isStartHandle = true ) // Assert. assertThat(coordinates).isEqualTo( Offset((fontSizeInPx * (text.length - 1 - startOffset)), fontSizeInPx) ) } @Test fun getHandlePosition_StartHandle_cross_rtl() { val text = "\u05D0\u05D1\u05D2 \u05D3\u05D4\u05D5\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectableId = 1L val selectable = MultiWidgetSelectionDelegate( selectableId = selectableId, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val startOffset = text.indexOf('\u05D5') val endOffset = text.indexOf('\u05D1') val selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = startOffset, selectableId = selectableId ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = endOffset, selectableId = selectableId ), handlesCrossed = true ) // Act. val coordinates = selectable.getHandlePosition( selection = selection, isStartHandle = true ) // Assert. assertThat(coordinates).isEqualTo( Offset((fontSizeInPx * (text.length - 1 - startOffset)), fontSizeInPx) ) } @Test fun getHandlePosition_StartHandle_not_cross_bidi() { val textLtr = "Hello" val textRtl = "\u05D0\u05D1\u05D2" val text = textLtr + textRtl val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectableId = 1L val selectable = MultiWidgetSelectionDelegate( selectableId = selectableId, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val startOffset = text.indexOf('\u05D0') val endOffset = text.indexOf('\u05D2') val selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = startOffset, selectableId = selectableId ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = endOffset, selectableId = selectableId ), handlesCrossed = false ) // Act. val coordinates = selectable.getHandlePosition( selection = selection, isStartHandle = true ) // Assert. assertThat(coordinates).isEqualTo( Offset((fontSizeInPx * (text.length)), fontSizeInPx) ) } @Test fun getHandlePosition_StartHandle_cross_bidi() { val textLtr = "Hello" val textRtl = "\u05D0\u05D1\u05D2" val text = textLtr + textRtl val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectableId = 1L val selectable = MultiWidgetSelectionDelegate( selectableId = selectableId, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val startOffset = text.indexOf('\u05D0') val endOffset = text.indexOf('H') val selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = startOffset, selectableId = selectableId ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = endOffset, selectableId = selectableId ), handlesCrossed = true ) // Act. val coordinates = selectable.getHandlePosition( selection = selection, isStartHandle = true ) // Assert. assertThat(coordinates).isEqualTo( Offset((fontSizeInPx * (textLtr.length)), fontSizeInPx) ) } @Test fun getHandlePosition_EndHandle_not_cross_ltr() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectableId = 1L val selectable = MultiWidgetSelectionDelegate( selectableId = selectableId, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val startOffset = text.indexOf('h') val endOffset = text.indexOf('o') val selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = startOffset, selectableId = selectableId ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = endOffset, selectableId = selectableId ), handlesCrossed = false ) // Act. val coordinates = selectable.getHandlePosition( selection = selection, isStartHandle = false ) // Assert. assertThat(coordinates).isEqualTo( Offset((fontSizeInPx * endOffset), fontSizeInPx) ) } @Test fun getHandlePosition_EndHandle_cross_ltr() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectableId = 1L val selectable = MultiWidgetSelectionDelegate( selectableId = selectableId, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val startOffset = text.indexOf('o') val endOffset = text.indexOf('h') val selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = startOffset, selectableId = selectableId ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = endOffset, selectableId = selectableId ), handlesCrossed = true ) // Act. val coordinates = selectable.getHandlePosition( selection = selection, isStartHandle = false ) // Assert. assertThat(coordinates).isEqualTo( Offset((fontSizeInPx * endOffset), fontSizeInPx) ) } @Test fun getHandlePosition_EndHandle_not_cross_rtl() { val text = "\u05D0\u05D1\u05D2 \u05D3\u05D4\u05D5\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectableId = 1L val selectable = MultiWidgetSelectionDelegate( selectableId = selectableId, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val startOffset = text.indexOf('\u05D1') val endOffset = text.indexOf('\u05D5') val selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = startOffset, selectableId = selectableId ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = endOffset, selectableId = selectableId ), handlesCrossed = false ) // Act. val coordinates = selectable.getHandlePosition( selection = selection, isStartHandle = false ) // Assert. assertThat(coordinates).isEqualTo( Offset((fontSizeInPx * (text.length - 1 - endOffset)), fontSizeInPx) ) } @Test fun getHandlePosition_EndHandle_cross_rtl() { val text = "\u05D0\u05D1\u05D2 \u05D3\u05D4\u05D5\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectableId = 1L val selectable = MultiWidgetSelectionDelegate( selectableId = selectableId, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val startOffset = text.indexOf('\u05D5') val endOffset = text.indexOf('\u05D1') val selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = startOffset, selectableId = selectableId ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = endOffset, selectableId = selectableId ), handlesCrossed = true ) // Act. val coordinates = selectable.getHandlePosition( selection = selection, isStartHandle = false ) // Assert. assertThat(coordinates).isEqualTo( Offset((fontSizeInPx * (text.length - 1 - endOffset)), fontSizeInPx) ) } @Test fun getHandlePosition_EndHandle_not_cross_bidi() { val textLtr = "Hello" val textRtl = "\u05D0\u05D1\u05D2" val text = textLtr + textRtl val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectableId = 1L val selectable = MultiWidgetSelectionDelegate( selectableId = selectableId, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val startOffset = text.indexOf('e') val endOffset = text.indexOf('\u05D0') val selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = startOffset, selectableId = selectableId ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = endOffset, selectableId = selectableId ), handlesCrossed = false ) // Act. val coordinates = selectable.getHandlePosition( selection = selection, isStartHandle = false ) // Assert. assertThat(coordinates).isEqualTo( Offset((fontSizeInPx * (textLtr.length)), fontSizeInPx) ) } @Test fun getHandlePosition_EndHandle_cross_bidi() { val textLtr = "Hello" val textRtl = "\u05D0\u05D1\u05D2" val text = textLtr + textRtl val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectableId = 1L val selectable = MultiWidgetSelectionDelegate( selectableId = selectableId, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val startOffset = text.indexOf('\u05D2') val endOffset = text.indexOf('\u05D0') val selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = startOffset, selectableId = selectableId ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = endOffset, selectableId = selectableId ), handlesCrossed = true ) // Act. val coordinates = selectable.getHandlePosition( selection = selection, isStartHandle = false ) // Assert. assertThat(coordinates).isEqualTo( Offset((fontSizeInPx * (text.length)), fontSizeInPx) ) } @Test fun getText_textLayoutResult_Null_Return_Empty_AnnotatedString() { val layoutResult = null val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectable = MultiWidgetSelectionDelegate( 0, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) assertThat(selectable.getText()).isEqualTo(AnnotatedString("")) } @Test fun getText_textLayoutResult_NotNull_Return_AnnotatedString() { val textLtr = "Hello" val textRtl = "\u05D0\u05D1\u05D2" val text = textLtr + textRtl val fontSize = 20.sp val spanStyle = SpanStyle(fontSize = fontSize, fontFamily = fontFamily) val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectable = MultiWidgetSelectionDelegate( 0, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) assertThat(selectable.getText()).isEqualTo(AnnotatedString(text, spanStyle)) } @Test fun getBoundingBox_valid() { val text = "hello\nworld\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectable = MultiWidgetSelectionDelegate( 1, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) val textOffset = text.indexOf('w') // Act. val box = selectable.getBoundingBox(textOffset) // Assert. assertThat(box.left).isZero() assertThat(box.right).isEqualTo(fontSizeInPx) assertThat(box.top).isEqualTo(fontSizeInPx) assertThat(box.bottom).isEqualTo(2 * fontSizeInPx) } @Test fun getBoundingBox_zero_length_text_return_zero_rect() { val text = "" val fontSize = 20.sp val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectable = MultiWidgetSelectionDelegate( 0, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) // Act. val box = selectable.getBoundingBox(0) // Assert. assertThat(box).isEqualTo(Rect.Zero) } @Test fun getBoundingBox_negative_offset_should_return_zero_rect() { val text = "hello\nworld\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectable = MultiWidgetSelectionDelegate( 0, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) // Act. val box = selectable.getBoundingBox(-2) // Assert. assertThat(box.left).isZero() assertThat(box.right).isEqualTo(fontSizeInPx) assertThat(box.top).isZero() assertThat(box.bottom).isEqualTo(fontSizeInPx) } @Test fun getBoundingBox_offset_larger_than_range_should_return_largest() { val text = "hello\nworld" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val layoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectable = MultiWidgetSelectionDelegate( selectableId = 1, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) // Act. val box = selectable.getBoundingBox(text.indexOf('d') + 5) // Assert. assertThat(box.left).isEqualTo(4 * fontSizeInPx) assertThat(box.right).isEqualTo(5 * fontSizeInPx) assertThat(box.top).isEqualTo(fontSizeInPx) assertThat(box.bottom).isEqualTo(2 * fontSizeInPx) } @Test fun getRangeOfLineContaining_zeroOffset() { val text = "hello\nworld\n" val layoutResult = simpleTextLayout( text = text, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectable = MultiWidgetSelectionDelegate( 1, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) // Act. val lineRange = selectable.getRangeOfLineContaining(0) // Assert. assertThat(lineRange.start).isEqualTo(0) assertThat(lineRange.end).isEqualTo(5) } @Test fun getRangeOfLineContaining_secondLine() { val text = "hello\nworld\n" val layoutResult = simpleTextLayout( text = text, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectable = MultiWidgetSelectionDelegate( 1, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) // Act. val lineRange = selectable.getRangeOfLineContaining(7) // Assert. assertThat(lineRange.start).isEqualTo(6) assertThat(lineRange.end).isEqualTo(11) } @Test fun getRangeOfLineContaining_negativeOffset_returnsFirstLine() { val text = "hello\nworld\n" val layoutResult = simpleTextLayout( text = text, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectable = MultiWidgetSelectionDelegate( 1, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) // Act. val lineRange = selectable.getRangeOfLineContaining(-1) // Assert. assertThat(lineRange.start).isEqualTo(0) assertThat(lineRange.end).isEqualTo(5) } @Test fun getRangeOfLineContaining_offsetPastTextLength_returnsLastLine() { val text = "hello\nworld\n" val layoutResult = simpleTextLayout( text = text, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectable = MultiWidgetSelectionDelegate( 1, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) // Act. val lineRange = selectable.getRangeOfLineContaining(Int.MAX_VALUE) // Assert. assertThat(lineRange.start).isEqualTo(6) assertThat(lineRange.end).isEqualTo(11) } @Test fun getRangeOfLineContaining_offsetAtNewline_returnsPreviousLine() { val text = "hello\nworld\n" val layoutResult = simpleTextLayout( text = text, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectable = MultiWidgetSelectionDelegate( 1, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) // Act. val lineRange = selectable.getRangeOfLineContaining(5) // Assert. assertThat(lineRange.start).isEqualTo(0) assertThat(lineRange.end).isEqualTo(5) } @Test fun getRangeOfLineContaining_emptyString_returnsEmptyRange() { val text = "" val layoutResult = simpleTextLayout( text = text, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectable = MultiWidgetSelectionDelegate( 1, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) // Act. val lineRange = selectable.getRangeOfLineContaining(5) // Assert. assertThat(lineRange.start).isEqualTo(0) assertThat(lineRange.end).isEqualTo(0) } @Test fun getRangeOfLineContaining_emptyLine_returnsEmptyNonZeroRange() { val text = "hello\n\nworld" val layoutResult = simpleTextLayout( text = text, density = defaultDensity ) val layoutCoordinates = mock<LayoutCoordinates>() whenever(layoutCoordinates.isAttached).thenReturn(true) val selectable = MultiWidgetSelectionDelegate( 1, coordinatesCallback = { layoutCoordinates }, layoutResultCallback = { layoutResult } ) // Act. val lineRange = selectable.getRangeOfLineContaining(6) // Assert. assertThat(lineRange.start).isEqualTo(6) assertThat(lineRange.end).isEqualTo(6) } @Test fun getTextSelectionInfo_long_press_select_word_ltr() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val start = Offset((fontSizeInPx * 2), (fontSizeInPx / 2)) val end = start // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = end, endHandlePosition = start, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Word ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(0) } assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo("hello".length) } } @Test fun getTextSelectionInfo_long_press_select_word_rtl() { val text = "\u05D0\u05D1\u05D2 \u05D3\u05D4\u05D5\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val start = Offset((fontSizeInPx * 2), (fontSizeInPx / 2)) val end = start // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = end, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Word ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Rtl) assertThat(it.offset).isEqualTo(text.indexOf("\u05D3")) } assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Rtl) assertThat(it.offset).isEqualTo(text.indexOf("\u05D5") + 1) } } @Test fun getTextSelectionInfo_long_press_drag_handle_not_cross_select_word() { val text = "hello world" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val rawStartOffset = text.indexOf('e') val rawEndOffset = text.indexOf('r') val start = Offset((fontSizeInPx * rawStartOffset), (fontSizeInPx / 2)) val end = Offset((fontSizeInPx * rawEndOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Word ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(0) } assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(text.length) } assertThat(textSelectionInfo?.handlesCrossed).isFalse() } @Test fun getTextSelectionInfo_long_press_drag_handle_cross_select_word() { val text = "hello world" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val rawStartOffset = text.indexOf('r') val rawEndOffset = text.indexOf('e') val start = Offset((fontSizeInPx * rawStartOffset), (fontSizeInPx / 2)) val end = Offset((fontSizeInPx * rawEndOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Word ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(text.length) } assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(0) } assertThat(textSelectionInfo?.handlesCrossed).isTrue() } @Test fun getTextSelectionInfo_long_press_select_ltr_drag_down() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // long pressed between "h" and "e", "hello" should be selected val start = Offset((fontSizeInPx * 2), (fontSizeInPx / 2)) val end = start // Act. val (textSelectionInfo1, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Word ) // Drag downwards, after the drag the selection should remain the same. val (textSelectionInfo2, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = end + Offset(0f, fontSizeInPx / 4), endHandlePosition = start, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Word, previousSelection = textSelectionInfo1, isStartHandle = false ) // Assert. assertThat(textSelectionInfo1).isNotNull() assertThat(textSelectionInfo1?.start).isNotNull() textSelectionInfo1?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(0) } assertThat(textSelectionInfo1?.end).isNotNull() textSelectionInfo1?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo("hello".length) } assertThat(textSelectionInfo2).isNotNull() assertThat(textSelectionInfo2).isEqualTo(textSelectionInfo1) } @Test fun getTextSelectionInfo_drag_select_range_ltr() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "llo wor" is selected. val startOffset = text.indexOf("l") val endOffset = text.indexOf("r") + 1 val start = Offset((fontSizeInPx * startOffset), (fontSizeInPx / 2)) val end = Offset((fontSizeInPx * endOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.None ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(startOffset) } assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(endOffset) } } @Test fun getTextSelectionInfo_drag_select_range_rtl() { val text = "\u05D0\u05D1\u05D2 \u05D3\u05D4\u05D5\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "\u05D1\u05D2 \u05D3" is selected. val startOffset = text.indexOf("\u05D1") val endOffset = text.indexOf("\u05D3") + 1 val start = Offset( (fontSizeInPx * (text.length - 1 - startOffset)), (fontSizeInPx / 2) ) val end = Offset( (fontSizeInPx * (text.length - 1 - endOffset)), (fontSizeInPx / 2) ) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.None ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Rtl) assertThat(it.offset).isEqualTo(startOffset) } assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Rtl) assertThat(it.offset).isEqualTo(endOffset) } } @Test fun getTextSelectionInfo_drag_select_range_bidi() { val textLtr = "Hello" val textRtl = "\u05D0\u05D1\u05D2\u05D3\u05D4" val text = textLtr + textRtl val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "llo"+"\u05D0\u05D1\u05D2" is selected val startOffset = text.indexOf("l") val endOffset = text.indexOf("\u05D2") + 1 val start = Offset( (fontSizeInPx * startOffset), (fontSizeInPx / 2) ) val end = Offset( (fontSizeInPx * (textLtr.length + text.length - endOffset)), (fontSizeInPx / 2) ) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.None ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(startOffset) } assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Rtl) assertThat(it.offset).isEqualTo(endOffset) } } @Test fun getTextSelectionInfo_single_widget_handles_crossed_ltr() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "llo wor" is selected. val startOffset = text.indexOf("r") + 1 val endOffset = text.indexOf("l") val start = Offset((fontSizeInPx * startOffset), (fontSizeInPx / 2)) val end = Offset((fontSizeInPx * endOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.None ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(startOffset) } assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(endOffset) } assertThat(textSelectionInfo?.handlesCrossed).isTrue() } @Test fun getTextSelectionInfo_single_widget_handles_crossed_rtl() { val text = "\u05D0\u05D1\u05D2 \u05D3\u05D4\u05D5\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "\u05D1\u05D2 \u05D3" is selected. val startOffset = text.indexOf("\u05D3") + 1 val endOffset = text.indexOf("\u05D1") val start = Offset( (fontSizeInPx * (text.length - 1 - startOffset)), (fontSizeInPx / 2) ) val end = Offset( (fontSizeInPx * (text.length - 1 - endOffset)), (fontSizeInPx / 2) ) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.None ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Rtl) assertThat(it.offset).isEqualTo(startOffset) } assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Rtl) assertThat(it.offset).isEqualTo(endOffset) } assertThat(textSelectionInfo?.handlesCrossed).isTrue() } @Test fun getTextSelectionInfo_single_widget_handles_crossed_bidi() { val textLtr = "Hello" val textRtl = "\u05D0\u05D1\u05D2\u05D3\u05D4" val text = textLtr + textRtl val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "llo"+"\u05D0\u05D1\u05D2" is selected val startOffset = text.indexOf("\u05D2") + 1 val endOffset = text.indexOf("l") val start = Offset( (fontSizeInPx * (textLtr.length + text.length - startOffset)), (fontSizeInPx / 2) ) val end = Offset( (fontSizeInPx * endOffset), (fontSizeInPx / 2) ) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.None ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Rtl) assertThat(it.offset).isEqualTo(startOffset) } assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(endOffset) } assertThat(textSelectionInfo?.handlesCrossed).isTrue() } @Test fun getTextSelectionInfo_bound_to_one_character_ltr_drag_endHandle() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "llo" is selected. val oldStartOffset = text.indexOf("l") val oldEndOffset = text.indexOf("o") + 1 val selectableId = 1L val previousSelection = Selection( start = Selection.AnchorInfo( offset = oldStartOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), end = Selection.AnchorInfo( offset = oldEndOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), handlesCrossed = false ) // first "l" is selected. val start = Offset((fontSizeInPx * oldStartOffset), (fontSizeInPx / 2)) val end = Offset((fontSizeInPx * oldStartOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Character, previousSelection = previousSelection, isStartHandle = false ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isEqualTo(previousSelection.start) assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(oldStartOffset + 1) } assertThat(textSelectionInfo?.handlesCrossed).isFalse() } @Test fun getTextSelectionInfo_bound_to_one_character_rtl_drag_endHandle() { val text = "\u05D0\u05D1\u05D2 \u05D3\u05D4\u05D5\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "\u05D0\u05D1" is selected. val oldStartOffset = text.indexOf("\u05D1") val oldEndOffset = text.length val selectableId = 1L val previousSelection = Selection( start = Selection.AnchorInfo( offset = oldStartOffset, direction = ResolvedTextDirection.Rtl, selectableId = selectableId ), end = Selection.AnchorInfo( offset = oldEndOffset, direction = ResolvedTextDirection.Rtl, selectableId = selectableId ), handlesCrossed = false ) // "\u05D1" is selected. val start = Offset( (fontSizeInPx * (text.length - 1 - oldStartOffset)), (fontSizeInPx / 2) ) val end = Offset( (fontSizeInPx * (text.length - 1 - oldStartOffset)), (fontSizeInPx / 2) ) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Character, previousSelection = previousSelection, isStartHandle = false ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isEqualTo(previousSelection.start) assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Rtl) assertThat(it.offset).isEqualTo(oldStartOffset + 1) } assertThat(textSelectionInfo?.handlesCrossed).isFalse() } @Test fun getTextSelectionInfo_bound_to_one_character_drag_startHandle_not_crossed() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "llo" is selected. val oldStartOffset = text.indexOf("l") val oldEndOffset = text.indexOf("o") + 1 val selectableId = 1L val previousSelection = Selection( start = Selection.AnchorInfo( offset = oldStartOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), end = Selection.AnchorInfo( offset = oldEndOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), handlesCrossed = false ) // "o" is selected. val start = Offset((fontSizeInPx * oldEndOffset), (fontSizeInPx / 2)) val end = Offset((fontSizeInPx * oldEndOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Character, previousSelection = previousSelection, isStartHandle = true ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo((oldEndOffset - 1)) } assertThat(textSelectionInfo?.end).isEqualTo(previousSelection.end) assertThat(textSelectionInfo?.handlesCrossed).isFalse() } @Test fun getTextSelectionInfo_bound_to_one_character_drag_startHandle_crossed() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "llo" is selected. val oldStartOffset = text.indexOf("o") + 1 val oldEndOffset = text.indexOf("l") val selectableId = 1L val previousSelection = Selection( start = Selection.AnchorInfo( offset = oldStartOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), end = Selection.AnchorInfo( offset = oldEndOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), handlesCrossed = true ) // first "l" is selected. val start = Offset((fontSizeInPx * oldEndOffset), (fontSizeInPx / 2)) val end = Offset((fontSizeInPx * oldEndOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Character, previousSelection = previousSelection, isStartHandle = true ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo((oldEndOffset + 1)) } assertThat(textSelectionInfo?.end).isEqualTo(previousSelection.end) assertThat(textSelectionInfo?.handlesCrossed).isTrue() } @Test fun getTextSelectionInfo_bound_to_one_character_drag_startHandle_not_crossed_bounded() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "e" is selected. val oldStartOffset = text.indexOf("e") val oldEndOffset = text.indexOf("l") val selectableId = 1L val previousSelection = Selection( start = Selection.AnchorInfo( offset = oldStartOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), end = Selection.AnchorInfo( offset = oldEndOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), handlesCrossed = false ) // "e" should be selected. val start = Offset((fontSizeInPx * oldEndOffset), (fontSizeInPx / 2)) val end = Offset((fontSizeInPx * oldEndOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Character, previousSelection = previousSelection, isStartHandle = true ) // Assert. assertThat(textSelectionInfo?.start?.offset).isEqualTo(previousSelection.start.offset) assertThat(textSelectionInfo?.end?.offset).isEqualTo(previousSelection.end.offset) } @Test fun getTextSelectionInfo_bound_to_one_character_drag_startHandle_crossed_bounded() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "e" is selected. val oldStartOffset = text.indexOf("l") val oldEndOffset = text.indexOf("e") val selectableId = 1L val previousSelection = Selection( start = Selection.AnchorInfo( offset = oldStartOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), end = Selection.AnchorInfo( offset = oldEndOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), handlesCrossed = true ) // "e" should be selected. val start = Offset((fontSizeInPx * oldEndOffset), (fontSizeInPx / 2)) val end = Offset((fontSizeInPx * oldEndOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Character, previousSelection = previousSelection, isStartHandle = true ) // Assert. assertThat(textSelectionInfo?.start?.offset).isEqualTo(previousSelection.start.offset) assertThat(textSelectionInfo?.end?.offset).isEqualTo(previousSelection.end.offset) } @Test fun getTextSelectionInfo_bound_to_one_character_drag_startHandle_not_crossed_boundary() { val text = "hello world" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "d" is selected. val oldStartOffset = text.length - 1 val oldEndOffset = text.length val selectableId = 1L val previousSelection = Selection( start = Selection.AnchorInfo( offset = oldStartOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), end = Selection.AnchorInfo( offset = oldEndOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), handlesCrossed = false ) // "d" should be selected. val start = Offset( (fontSizeInPx * oldEndOffset) - (fontSizeInPx / 2), (fontSizeInPx / 2) ) val end = Offset( (fontSizeInPx * oldEndOffset) - 1, (fontSizeInPx / 2) ) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Character, previousSelection = previousSelection, isStartHandle = true ) // Assert. assertThat(textSelectionInfo?.start?.offset).isEqualTo(previousSelection.start.offset) assertThat(textSelectionInfo?.end?.offset).isEqualTo(previousSelection.end.offset) } @Test fun getTextSelectionInfo_bound_to_one_character_drag_startHandle_crossed_boundary() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "h" is selected. val oldStartOffset = text.indexOf("e") val oldEndOffset = 0 val selectableId = 1L val previousSelection = Selection( start = Selection.AnchorInfo( offset = oldStartOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), end = Selection.AnchorInfo( offset = oldEndOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), handlesCrossed = true ) // "e" should be selected. val start = Offset((fontSizeInPx * oldEndOffset), (fontSizeInPx / 2)) val end = Offset((fontSizeInPx * oldEndOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Character, previousSelection = previousSelection, isStartHandle = true ) // Assert. assertThat(textSelectionInfo?.start?.offset).isEqualTo(previousSelection.start.offset) assertThat(textSelectionInfo?.end?.offset).isEqualTo(previousSelection.end.offset) } @Test fun getTextSelectionInfo_bound_to_one_character_drag_endHandle_crossed() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "llo" is selected. val oldStartOffset = text.indexOf("o") + 1 val oldEndOffset = text.indexOf("l") val selectableId = 1L val previousSelection = Selection( start = Selection.AnchorInfo( offset = oldStartOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), end = Selection.AnchorInfo( offset = oldEndOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), handlesCrossed = true ) // "o" is selected. val start = Offset((fontSizeInPx * oldStartOffset), (fontSizeInPx / 2)) val end = Offset((fontSizeInPx * oldStartOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Character, previousSelection = previousSelection, isStartHandle = false ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isEqualTo(previousSelection.start) assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo((oldStartOffset - 1)) } assertThat(textSelectionInfo?.handlesCrossed).isTrue() } @Test fun getTextSelectionInfo_bound_to_one_character_drag_endHandle_not_crossed_bounded() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "e" is selected. val oldStartOffset = text.indexOf("e") val oldEndOffset = text.indexOf("l") val selectableId = 1L val previousSelection = Selection( start = Selection.AnchorInfo( offset = oldStartOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), end = Selection.AnchorInfo( offset = oldEndOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), handlesCrossed = false ) // "e" should be selected. val start = Offset((fontSizeInPx * oldStartOffset), (fontSizeInPx / 2)) val end = Offset((fontSizeInPx * oldStartOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Character, previousSelection = previousSelection, isStartHandle = false ) // Assert. assertThat(textSelectionInfo?.start?.offset).isEqualTo(previousSelection.start.offset) assertThat(textSelectionInfo?.end?.offset).isEqualTo(previousSelection.end.offset) } @Test fun getTextSelectionInfo_bound_to_one_character_drag_endHandle_crossed_bounded() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "e" is selected. val oldStartOffset = text.indexOf("l") val oldEndOffset = text.indexOf("e") val selectableId = 1L val previousSelection = Selection( start = Selection.AnchorInfo( offset = oldStartOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), end = Selection.AnchorInfo( offset = oldEndOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), handlesCrossed = true ) // "e" should be selected. val start = Offset((fontSizeInPx * oldStartOffset), (fontSizeInPx / 2)) val end = Offset((fontSizeInPx * oldStartOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Character, previousSelection = previousSelection, isStartHandle = false ) // Assert. assertThat(textSelectionInfo?.start?.offset).isEqualTo(previousSelection.start.offset) assertThat(textSelectionInfo?.end?.offset).isEqualTo(previousSelection.end.offset) } @Test fun getTextSelectionInfo_bound_to_one_character_drag_endHandle_not_crossed_boundary() { val text = "hello world" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "h" is selected. val oldStartOffset = 0 val oldEndOffset = text.indexOf('e') val selectableId = 1L val previousSelection = Selection( start = Selection.AnchorInfo( offset = oldStartOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), end = Selection.AnchorInfo( offset = oldEndOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), handlesCrossed = false ) // "h" should be selected. val start = Offset( (fontSizeInPx * oldStartOffset), (fontSizeInPx / 2) ) val end = Offset( (fontSizeInPx * oldStartOffset), (fontSizeInPx / 2) ) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Character, previousSelection = previousSelection, isStartHandle = false ) // Assert. assertThat(textSelectionInfo?.start?.offset).isEqualTo(previousSelection.start.offset) assertThat(textSelectionInfo?.end?.offset).isEqualTo(previousSelection.end.offset) } @Test fun getTextSelectionInfo_bound_to_one_character_drag_endHandle_crossed_boundary() { val text = "hello world" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "d" is selected. val oldStartOffset = text.length val oldEndOffset = text.length - 1 val selectableId = 1L val previousSelection = Selection( start = Selection.AnchorInfo( offset = oldStartOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), end = Selection.AnchorInfo( offset = oldEndOffset, direction = ResolvedTextDirection.Ltr, selectableId = selectableId ), handlesCrossed = true ) // "d" should be selected. val start = Offset( (fontSizeInPx * oldStartOffset) - 1, (fontSizeInPx / 2) ) val end = Offset( (fontSizeInPx * oldStartOffset) - 1, (fontSizeInPx / 2) ) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Character, previousSelection = previousSelection, isStartHandle = false ) // Assert. assertThat(textSelectionInfo?.start?.offset).isEqualTo(previousSelection.start.offset) assertThat(textSelectionInfo?.end?.offset).isEqualTo(previousSelection.end.offset) } @Test fun getTextSelectionInfo_cross_widget_not_contain_start() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "hello w" is selected. val endOffset = text.indexOf("w") + 1 val start = Offset(-50f, -50f) val end = Offset((fontSizeInPx * endOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.None ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(0) } assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(endOffset) } } @Test fun getTextSelectionInfo_cross_widget_not_contain_end() { val text = "hello world" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "o world" is selected. val startOffset = text.indexOf("o") val start = Offset((fontSizeInPx * startOffset), (fontSizeInPx / 2)) val end = Offset( (fontSizeInPx * text.length * 2), (fontSizeInPx * 2) ) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.None ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(startOffset) } assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(text.length) } } @Test fun getTextSelectionInfo_cross_widget_not_contain_start_handles_crossed() { val text = "hello world" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "world" is selected. val endOffset = text.indexOf("w") val start = Offset((fontSizeInPx * text.length * 2), (fontSizeInPx * 2)) val end = Offset((fontSizeInPx * endOffset), (fontSizeInPx / 2)) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.None ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(text.length) } assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(endOffset) } assertThat(textSelectionInfo?.handlesCrossed).isTrue() } @Test fun getTextSelectionInfo_cross_widget_not_contain_end_handles_crossed() { val text = "hello world" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) // "hell" is selected. val startOffset = text.indexOf("o") val start = Offset((fontSizeInPx * startOffset), (fontSizeInPx / 2)) val end = Offset(-50f, -50f) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.None ) // Assert. assertThat(textSelectionInfo).isNotNull() assertThat(textSelectionInfo?.start).isNotNull() textSelectionInfo?.start?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(startOffset) } assertThat(textSelectionInfo?.end).isNotNull() textSelectionInfo?.end?.let { assertThat(it.direction).isEqualTo(ResolvedTextDirection.Ltr) assertThat(it.offset).isEqualTo(0) } assertThat(textSelectionInfo?.handlesCrossed).isTrue() } @Test fun getTextSelectionInfo_not_selected() { val text = "hello world\n" val fontSize = 20.sp val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val start = Offset(-50f, -50f) val end = Offset(-20f, -20f) // Act. val (textSelectionInfo, _) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = null, selectableId = 1, adjustment = SelectionAdjustment.Word ) assertThat(textSelectionInfo).isNull() } @Test fun getTextSelectionInfo_handleNotMoved_selectionUpdated_consumed_isTrue() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val start = Offset(0f, fontSizeInPx / 2) val end = Offset(fontSizeInPx * 3, fontSizeInPx / 2) // Act. // Selection is updated but endHandlePosition is actually the same. Since selection is // updated, the movement is consumed. val (_, consumed) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = end, selectableId = 1, adjustment = SelectionAdjustment.Word, previousSelection = null, isStartHandle = false ) assertThat(consumed).isTrue() } @Test fun getTextSelectionInfo_handleMoved_selectionNotUpdated_consumed_isTrue() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val start = Offset(0f, fontSizeInPx / 2) val end = Offset(fontSizeInPx * 3, fontSizeInPx / 2) val previousEnd = Offset(fontSizeInPx * 2, fontSizeInPx / 2) val previousSelection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = 0, selectableId = 1 ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = 5, selectableId = 1 ), ) // Act. // End handle moved from offset 2 to 3. But we are using word based selection, so the // selection is still [0, 5). However, since handle moved to a new offset, the movement // is consumed. val (textSelectionInfo, consumed) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = previousEnd, selectableId = 1, previousSelection = previousSelection, adjustment = SelectionAdjustment.Word, isStartHandle = false ) // First check that Selection didn't update. assertThat(textSelectionInfo).isEqualTo(previousSelection) assertThat(consumed).isTrue() } @Test fun getTextSelectionInfo_handleNotMoved_selectionNotUpdated_consumed_isFalse() { val text = "hello world\n" val fontSize = 20.sp val fontSizeInPx = with(defaultDensity) { fontSize.toPx() } val textLayoutResult = simpleTextLayout( text = text, fontSize = fontSize, density = defaultDensity ) val start = Offset(0f, fontSizeInPx / 2) val end = Offset(fontSizeInPx * 2.8f, fontSizeInPx / 2) val previousEnd = Offset(fontSizeInPx * 3f, fontSizeInPx / 2) val previousSelection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = 0, selectableId = 1 ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = 5, selectableId = 1 ), ) // Act. // End handle moved, but is still at the offset 3. Selection is not updated either. // So the movement is not consumed. val (textSelectionInfo, consumed) = getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = start, endHandlePosition = end, previousHandlePosition = previousEnd, selectableId = 1, previousSelection = previousSelection, adjustment = SelectionAdjustment.Word, isStartHandle = false ) // First check that Selection didn't update. assertThat(textSelectionInfo).isEqualTo(previousSelection) assertThat(consumed).isFalse() } @OptIn(InternalFoundationTextApi::class) private fun simpleTextLayout( text: String = "", fontSize: TextUnit = TextUnit.Unspecified, density: Density ): TextLayoutResult { val spanStyle = SpanStyle(fontSize = fontSize, fontFamily = fontFamily) val annotatedString = AnnotatedString(text, spanStyle) return TextDelegate( text = annotatedString, style = TextStyle(), density = density, fontFamilyResolver = fontFamilyResolver ).layout(Constraints(), LayoutDirection.Ltr) } }
apache-2.0
dc1a640fdd2c8b8b039fc1468e858ba2
33.079293
95
0.590214
5.080052
false
false
false
false
RSDT/Japp16
app/src/main/java/nl/rsdt/japp/jotial/auth/AeSimpleSHA1.kt
1
1391
package nl.rsdt.japp.jotial.auth import android.util.Log import org.acra.ktx.sendWithAcra import java.io.UnsupportedEncodingException import java.security.MessageDigest import java.security.NoSuchAlgorithmException /** * @author ? * @version 1.0 * @since 15-1-2016 * Tool for SHA1. */ object AeSimpleSHA1 { private fun convertToHex(data: ByteArray): String { val buf = StringBuilder() for (b in data) { var halfbyte = (b.toInt() ushr 4) and 0x0F var two_halfs = 0 do { buf.append(if (0 <= halfbyte && halfbyte <= 9) ('0'.toInt() + halfbyte).toChar() else ('a'.toInt() + (halfbyte - 10)).toChar()) halfbyte = b.toInt() and 0x0F } while (two_halfs++ < 1) } return buf.toString() } @Throws(NoSuchAlgorithmException::class, UnsupportedEncodingException::class) fun SHA1(text: String): String { val md = MessageDigest.getInstance("SHA-1") md.update(text.toByteArray(charset("iso-8859-1")), 0, text.length) val sha1hash = md.digest() return convertToHex(sha1hash) } fun trySHA1(text: String): String { try { return SHA1(text) } catch (e: Exception) { Log.e("AeSImpleSHA1", e.localizedMessage, e) e.sendWithAcra() } return "error-in-trySHA1" } }
apache-2.0
d381ec24808e84ea5e90b060272068af
26.84
143
0.594536
3.719251
false
false
false
false
mikrobi/TransitTracker_android
app/src/main/java/de/jakobclass/transittracker/utilities/BiMap.kt
1
539
package de.jakobclass.transittracker.utilities class BiMap<K,V> { private val map = mutableMapOf<K,V>() private val inverseMap = mutableMapOf<V,K>() operator fun get(key: K): V? { return map[key] } operator fun set(key: K, value: V) { map[key] = value inverseMap[value] = key } fun getKey(value: V): K? { return inverseMap[value] } fun remove(key: K): V? { val value = map.remove(key) value?.let { inverseMap.remove(it) } return value } }
gpl-3.0
e86c2dff87a0c3a9b8c136badd1cd591
20.6
48
0.569573
3.455128
false
false
false
false
Soya93/Extract-Refactoring
platform/built-in-server/src/org/jetbrains/builtInWebServer/DefaultWebServerRootsProvider.kt
3
9000
/* * Copyright 2000-2014 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. */ package org.jetbrains.builtInWebServer import com.intellij.openapi.application.runReadAction import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.DirectoryIndex import com.intellij.openapi.roots.impl.ModuleLibraryOrderEntryImpl import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PlatformUtils import com.intellij.util.containers.computeOrNull private class DefaultWebServerRootsProvider : WebServerRootsProvider() { override fun resolve(path: String, project: Project): PathInfo? { var effectivePath = path if (PlatformUtils.isIntelliJ()) { val index = effectivePath.indexOf('/') if (index > 0 && !effectivePath.regionMatches(0, project.name, 0, index, !SystemInfo.isFileSystemCaseSensitive)) { val moduleName = effectivePath.substring(0, index) val module = runReadAction { ModuleManager.getInstance(project).findModuleByName(moduleName) } if (module != null && !module.isDisposed) { effectivePath = effectivePath.substring(index + 1) val resolver = WebServerPathToFileManager.getInstance(project).getResolver(effectivePath) val moduleRootManager = ModuleRootManager.getInstance(module) val result = RootProvider.values().computeOrNull { findByRelativePath(effectivePath, it.getRoots(moduleRootManager), resolver, moduleName) } ?: findInModuleLibraries(effectivePath, module, resolver) if (result != null) { return result } } } } val resolver = WebServerPathToFileManager.getInstance(project).getResolver(effectivePath) return RootProvider.values().computeOrNull { rootProvider -> runReadAction { ModuleManager.getInstance(project).modules } .computeOrNull { module -> if (!module.isDisposed) { val result = findByRelativePath(path, rootProvider.getRoots(ModuleRootManager.getInstance(module)), resolver, null) if (result != null) { result.moduleName = getModuleNameQualifier(project, module) return result } } null } } ?: findInLibraries(project, effectivePath, resolver) } override fun getPathInfo(file: VirtualFile, project: Project): PathInfo? { runReadAction { val directoryIndex = DirectoryIndex.getInstance(project) val info = directoryIndex.getInfoForFile(file) // we serve excluded files if (!info.isExcluded && !info.isInProject) { // javadoc jars is "not under project", but actually is, so, let's check library or SDK return if (file.fileSystem == JarFileSystem.getInstance()) getInfoForDocJar(file, project) else null } var root = info.sourceRoot val isLibrary: Boolean if (root == null) { root = info.contentRoot if (root == null) { root = info.libraryClassRoot isLibrary = true assert(root != null) { file.presentableUrl } } else { isLibrary = false } } else { isLibrary = info.isInLibrarySource } var module = info.module if (isLibrary && module == null) { for (entry in directoryIndex.getOrderEntries(info)) { if (entry is ModuleLibraryOrderEntryImpl) { module = entry.ownerModule break } } } return PathInfo(null, file, root!!, getModuleNameQualifier(project, module), isLibrary) } } } private enum class RootProvider { SOURCE { override fun getRoots(rootManager: ModuleRootManager) = rootManager.sourceRoots }, CONTENT { override fun getRoots(rootManager: ModuleRootManager) = rootManager.contentRoots }, EXCLUDED { override fun getRoots(rootManager: ModuleRootManager) = rootManager.excludeRoots }; abstract fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> } private val ORDER_ROOT_TYPES by lazy { val javaDocRootType = getJavadocOrderRootType() if (javaDocRootType == null) arrayOf(OrderRootType.DOCUMENTATION, OrderRootType.SOURCES, OrderRootType.CLASSES) else arrayOf(javaDocRootType, OrderRootType.DOCUMENTATION, OrderRootType.SOURCES, OrderRootType.CLASSES) } private fun getJavadocOrderRootType(): OrderRootType? { try { return JavadocOrderRootType.getInstance() } catch (e: Throwable) { return null } } private fun findInModuleLibraries(path: String, module: Module, resolver: FileResolver): PathInfo? { val index = path.indexOf('/') if (index <= 0) { return null } val libraryFileName = path.substring(0, index) val relativePath = path.substring(index + 1) return ORDER_ROOT_TYPES.computeOrNull { findInModuleLevelLibraries(module, it) { root, module -> if (StringUtil.equalsIgnoreCase(root.nameSequence, libraryFileName)) resolver.resolve(relativePath, root, isLibrary = true) else null } } } private fun findInLibraries(project: Project, path: String, resolver: FileResolver): PathInfo? { val index = path.indexOf('/') if (index < 0) { return null } val libraryFileName = path.substring(0, index) val relativePath = path.substring(index + 1) return findInLibrariesAndSdk(project, ORDER_ROOT_TYPES) { root, module -> if (StringUtil.equalsIgnoreCase(root.nameSequence, libraryFileName)) resolver.resolve(relativePath, root, isLibrary = true) else null } } private fun getInfoForDocJar(file: VirtualFile, project: Project): PathInfo? { val javaDocRootType = getJavadocOrderRootType() ?: return null return findInLibrariesAndSdk(project, arrayOf(javaDocRootType)) { root, module -> if (VfsUtilCore.isAncestor(root, file, false)) PathInfo(null, file, root, getModuleNameQualifier(project, module), true) else null } } private fun getModuleNameQualifier(project: Project, module: Module?): String? { if (module != null && PlatformUtils.isIntelliJ() && !(module.name.equals(project.name, ignoreCase = true) || compareNameAndProjectBasePath(module.name, project))) { return module.name } return null } private fun findByRelativePath(path: String, roots: Array<VirtualFile>, resolver: FileResolver, moduleName: String?) = roots.computeOrNull { resolver.resolve(path, it, moduleName) } private fun findInLibrariesAndSdk(project: Project, rootTypes: Array<OrderRootType>, fileProcessor: (root: VirtualFile, module: Module?) -> PathInfo?): PathInfo? { fun findInLibraryTable(table: LibraryTable, rootType: OrderRootType) = table.libraryIterator.computeOrNull { it.getFiles(rootType).computeOrNull { fileProcessor(it, null) } } fun findInProjectSdkOrInAll(rootType: OrderRootType): PathInfo? { val inSdkFinder = { sdk: Sdk -> sdk.rootProvider.getFiles(rootType).computeOrNull { fileProcessor(it, null) } } val projectSdk = ProjectRootManager.getInstance(project).projectSdk return projectSdk?.let(inSdkFinder) ?: ProjectJdkTable.getInstance().allJdks.computeOrNull { if (it === projectSdk) null else inSdkFinder(it) } } return rootTypes.computeOrNull { rootType -> runReadAction { findInLibraryTable(LibraryTablesRegistrar.getInstance().getLibraryTable(project), rootType) ?: findInProjectSdkOrInAll(rootType) ?: ModuleManager.getInstance(project).modules.computeOrNull { if (it.isDisposed) null else findInModuleLevelLibraries(it, rootType, fileProcessor) } ?: findInLibraryTable(LibraryTablesRegistrar.getInstance().libraryTable, rootType) } } } private fun findInModuleLevelLibraries(module: Module, rootType: OrderRootType, fileProcessor: (root: VirtualFile, module: Module?) -> PathInfo?): PathInfo? { return ModuleRootManager.getInstance(module).orderEntries.computeOrNull { if (it is LibraryOrderEntry && it.isModuleLevel) it.getFiles(rootType).computeOrNull { fileProcessor(it, module) } else null } }
apache-2.0
10bf299f518a2fcc4296479ccc8378c0
40.479263
181
0.724889
4.764426
false
false
false
false
Soya93/Extract-Refactoring
plugins/settings-repository/src/settings/upstreamEditor.kt
2
4141
/* * Copyright 2000-2015 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. */ package org.jetbrains.settingsRepository import com.intellij.notification.NotificationType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.util.ArrayUtil import org.jetbrains.settingsRepository.actions.NOTIFICATION_GROUP import java.awt.Container import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.Action fun updateSyncButtonState(url: String?, syncActions: Array<Action>) { val enabled: Boolean try { enabled = url != null && url.length > 1 && icsManager.repositoryService.checkUrl(url, null); } catch (e: Throwable) { enabled = false; } for (syncAction in syncActions) { syncAction.isEnabled = enabled; } } fun createMergeActions(project: Project?, urlTextField: TextFieldWithBrowseButton, dialogParent: Container, okAction: (() -> Unit)): Array<Action> { var syncTypes = SyncType.values() if (SystemInfo.isMac) { syncTypes = ArrayUtil.reverseArray(syncTypes) } val icsManager = icsManager return Array(3) { val syncType = syncTypes[it] object : AbstractAction(icsMessage("action.${if (syncType == SyncType.MERGE) "Merge" else (if (syncType == SyncType.OVERWRITE_LOCAL) "ResetToTheirs" else "ResetToMy")}Settings.text")) { private fun saveRemoteRepositoryUrl(): Boolean { val url = StringUtil.nullize(urlTextField.text) if (url != null && !icsManager.repositoryService.checkUrl(url, dialogParent)) { return false } val repositoryManager = icsManager.repositoryManager repositoryManager.createRepositoryIfNeed() repositoryManager.setUpstream(url, null) return true } override fun actionPerformed(event: ActionEvent) { val repositoryWillBeCreated = !icsManager.repositoryManager.isRepositoryExists() var upstreamSet = false try { if (!saveRemoteRepositoryUrl()) { if (repositoryWillBeCreated) { // remove created repository icsManager.repositoryManager.deleteRepository() } return } upstreamSet = true if (repositoryWillBeCreated && syncType != SyncType.OVERWRITE_LOCAL) { ApplicationManager.getApplication().saveSettings() icsManager.sync(syncType, project, { copyLocalConfig() }) } else { icsManager.sync(syncType, project, null) } } catch (e: Throwable) { if (repositoryWillBeCreated) { // remove created repository icsManager.repositoryManager.deleteRepository() } LOG.warn(e) if (!upstreamSet || e is NoRemoteRepositoryException) { Messages.showErrorDialog(dialogParent, icsMessage("set.upstream.failed.message", e.message), icsMessage("set.upstream.failed.title")) } else { Messages.showErrorDialog(dialogParent, StringUtil.notNullize(e.message, "Internal error"), icsMessage(if (e is AuthenticationException) "sync.not.authorized.title" else "sync.rejected.title")) } return } NOTIFICATION_GROUP.createNotification(icsMessage("sync.done.message"), NotificationType.INFORMATION).notify(project) okAction() } } } }
apache-2.0
9502fbdb459c9a2a7d5802b82b8db2f4
35.333333
204
0.691137
4.732571
false
false
false
false
mvosske/comlink
app/src/main/java/org/tnsfit/dragon/comlink/AroCoordinates.kt
1
1684
package org.tnsfit.dragon.comlink import android.view.ViewGroup import android.widget.RelativeLayout /** * Created by dragon on 26.10.16. * Enthält und speichert die Koordinaten für Pings und Marker (AROs) * */ class AroCoordinates(val x: Int, val y: Int) { fun layoutParams(dimension: ImageDimensions): ViewGroup.LayoutParams { val result = RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT) // hier kann eine Number Format Exception kommen, wäre aber ein nicht-Fangbarer Laufzeitfehler val newX: Int = ((dimension.width * x) / 100) + dimension.x val newY: Int = ((dimension.height * y) / 100)+ dimension.y result.topMargin = newY - 50 result.leftMargin = newX - 50 return result } override fun hashCode(): Int { return x + (y*1000) } override fun equals(other: Any?): Boolean { if (other?.javaClass != AroCoordinates::class.java) return false return other?.hashCode() == hashCode() } override fun toString(): String { return x.toString() + "," + y.toString() } } fun AroCoordinates(coordsString: String): AroCoordinates { val coords = coordsString.split(",", limit = 2) var x: Int = 50 var y: Int = 50 try { x = coords[0].toInt() y = coords[1].toInt() } catch (ie: IndexOutOfBoundsException) { // Standarwerte wurden festgelegt, keine Behandlung notwendig } catch (nfe: NumberFormatException) { // Auch hier die Standardwerte benutzen und alles wird gut } return AroCoordinates(x,y) }
gpl-3.0
abbd8fa527e23545f6a7f1d43c41a9da
28
102
0.64188
3.829157
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/widgets/dialog/BookcasesDialogView.kt
2
3119
package ru.fantlab.android.ui.widgets.dialog import android.content.Context import android.os.Bundle import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.simple_list_dialog.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.BookcaseSelection import ru.fantlab.android.helper.BundleConstant import ru.fantlab.android.helper.Bundler import ru.fantlab.android.ui.adapter.BookcaseSelectorAdapter import ru.fantlab.android.ui.adapter.viewholder.BookcaseSelectionViewHolder import ru.fantlab.android.ui.base.BaseDialogFragment import ru.fantlab.android.ui.base.mvp.BaseMvp import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder import java.util.* class BookcasesDialogView : BaseDialogFragment<BaseMvp.View, BasePresenter<BaseMvp.View>>(), BaseViewHolder.OnItemClickListener<BookcaseSelection>, BookcaseSelectionViewHolder.OnItemSelectListener<BookcaseSelection> { private var callbacks: BookcasesDialogViewActionCallback? = null private val adapter: BookcaseSelectorAdapter by lazy { BookcaseSelectorAdapter(arrayListOf()) } override fun fragmentLayout(): Int = R.layout.simple_list_dialog override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { val objects = arguments!!.getParcelableArrayList<BookcaseSelection>(BundleConstant.ITEM) val titleText = arguments!!.getString(BundleConstant.EXTRA) title.text = titleText if (objects != null) { adapter.addItems(objects) adapter.listener = this adapter.selectionListener = this recycler.addDivider() recycler.adapter = adapter recycler.layoutManager = LinearLayoutManager(activity) } else { dismiss() } fastScroller.attachRecyclerView(recycler) } override fun providePresenter(): BasePresenter<BaseMvp.View> = BasePresenter() override fun onMessageDialogActionClicked(isOk: Boolean, bundle: Bundle?) { } override fun onDialogDismissed() { } override fun onItemClick(position: Int, v: View?, item: BookcaseSelection) { callbacks?.onBookcaseClick(item, position) } override fun onItemLongClick(position: Int, v: View?, item: BookcaseSelection) {} override fun onItemSelected(position: Int, v: View?, item: BookcaseSelection) { callbacks?.onBookcaseSelected(item, position) } fun initArguments(title: String, objects: ArrayList<BookcaseSelection>) { arguments = Bundler.start() .put(BundleConstant.EXTRA, title) .put(BundleConstant.ITEM, objects) .end() } override fun onAttach(context: Context) { super.onAttach(context) if (parentFragment != null && parentFragment is BookcasesDialogViewActionCallback) { callbacks = parentFragment as BookcasesDialogViewActionCallback } else if (context is BookcasesDialogViewActionCallback) { callbacks = context } } override fun onDetach() { callbacks = null super.onDetach() } interface BookcasesDialogViewActionCallback { fun onBookcaseClick(item: BookcaseSelection, position: Int) fun onBookcaseSelected(item: BookcaseSelection, position: Int) } }
gpl-3.0
15ff78f159c384a83182cb97e5737211
34.05618
96
0.793203
4.180965
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/groups/dto/GroupsLinksItem.kt
1
2513
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.groups.dto import com.google.gson.annotations.SerializedName import com.vk.sdk.api.base.dto.BaseBoolInt import kotlin.Int import kotlin.String /** * @param name - Link title * @param desc - Link description * @param editTitle - Information whether the link title can be edited * @param id - Link ID * @param photo100 - URL of square image of the link with 100 pixels in width * @param photo50 - URL of square image of the link with 50 pixels in width * @param url - Link URL * @param imageProcessing - Information whether the image on processing */ data class GroupsLinksItem( @SerializedName("name") val name: String? = null, @SerializedName("desc") val desc: String? = null, @SerializedName("edit_title") val editTitle: BaseBoolInt? = null, @SerializedName("id") val id: Int? = null, @SerializedName("photo_100") val photo100: String? = null, @SerializedName("photo_50") val photo50: String? = null, @SerializedName("url") val url: String? = null, @SerializedName("image_processing") val imageProcessing: BaseBoolInt? = null )
mit
4a319a6bde932b1fc1d00fcfe08c6581
39.532258
81
0.685237
4.362847
false
false
false
false
saki4510t/libcommon
app/src/main/java/com/serenegiant/widget/VideoSourceCameraGLView.kt
1
11557
package com.serenegiant.widget /* * libcommon * utility/helper classes for myself * * Copyright (c) 2014-2022 saki [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. */ import android.annotation.SuppressLint import android.content.Context import android.graphics.SurfaceTexture import android.opengl.GLES20 import android.opengl.Matrix import android.util.AttributeSet import android.util.Log import android.view.Surface import androidx.annotation.Size import androidx.annotation.WorkerThread import com.serenegiant.glpipeline.SurfaceDistributePipeline import com.serenegiant.glpipeline.GLPipeline import com.serenegiant.glpipeline.GLPipelineSource.PipelineSourceCallback import com.serenegiant.glpipeline.VideoSourcePipeline import com.serenegiant.gl.GLDrawer2D import com.serenegiant.glutils.IMirror import com.serenegiant.graphics.MatrixUtils import com.serenegiant.math.Fraction import com.serenegiant.widget.CameraDelegator.ICameraRenderer import java.lang.IllegalStateException /** * カメラ映像をVideoSource経由で取得してプレビュー表示するためのICameraView実装 * GLViewを継承 * XXX useSharedContext = trueで共有コンテキストを使ったマルチスレッド処理を有効にするとGPUのドライバー内でクラッシュする端末がある */ class VideoSourceCameraGLView @JvmOverloads constructor( context: Context?, attrs: AttributeSet? = null, defStyle: Int = 0) : AspectScaledGLView(context, attrs, defStyle), ICameraView, GLPipelineView { private val mCameraDelegator: CameraDelegator private val mCameraRenderer: CameraRenderer private var mVideoSourcePipeline: VideoSourcePipeline? = null private var mDistributor: SurfaceDistributePipeline? = null private val mMvpMatrix = FloatArray(16) init { if (DEBUG) Log.v(TAG, "コンストラクタ:") mCameraRenderer = CameraRenderer() mCameraDelegator = CameraDelegator(this@VideoSourceCameraGLView, CameraDelegator.DEFAULT_PREVIEW_WIDTH, CameraDelegator.DEFAULT_PREVIEW_HEIGHT, mCameraRenderer) setRenderer(object : GLRenderer { @SuppressLint("WrongThread") @WorkerThread override fun onSurfaceCreated() { if (DEBUG) Log.v(TAG, "onSurfaceCreated:") mDrawer = GLDrawer2D.create(isOES3Supported(), true) mDrawer!!.setMvpMatrix(mMvpMatrix, 0) GLES20.glClearColor(1.0f, 1.0f, 0.0f, 1.0f) } @WorkerThread override fun onSurfaceChanged(format: Int, width: Int, height: Int) { mVideoSourcePipeline!!.resize(width, height) mCameraDelegator.startPreview( CameraDelegator.DEFAULT_PREVIEW_WIDTH, CameraDelegator.DEFAULT_PREVIEW_HEIGHT) } @SuppressLint("WrongThread") @WorkerThread override fun drawFrame() { if (mVideoSourcePipeline != null) { handleDraw(mVideoSourcePipeline!!.texId, mVideoSourcePipeline!!.texMatrix) } } @WorkerThread override fun onSurfaceDestroyed() { if (mDrawer != null) { // mDrawer!!.release() // GT-N7100で動作がおかしくなる mDrawer = null } } override fun applyTransformMatrix(@Size(min=16) transform: FloatArray) { if (mDrawer != null) { if (DEBUG) Log.v(TAG, "applyTransformMatrix:" + MatrixUtils.toGLMatrixString(transform)) System.arraycopy(transform, 0, mMvpMatrix, 0, 16) mDrawer!!.setMvpMatrix(mMvpMatrix, 0) mDrawer!!.setMirror(IMirror.MIRROR_VERTICAL) } } }) Matrix.setIdentityM(mMvpMatrix, 0) } /** * ICameraViewの実装 */ @Synchronized override fun onResume() { if (DEBUG) Log.v(TAG, "onResume:") mVideoSourcePipeline = createVideoSource( CameraDelegator.DEFAULT_PREVIEW_WIDTH, CameraDelegator.DEFAULT_PREVIEW_HEIGHT) mCameraDelegator.onResume() } /** * ICameraViewの実装 */ @Synchronized override fun onPause() { if (DEBUG) Log.v(TAG, "onPause:") mCameraDelegator.onPause() mVideoSourcePipeline?.pipeline = null mDistributor?.release() mDistributor = null mVideoSourcePipeline?.release() mVideoSourcePipeline = null } /** * ICameraViewの実装 */ override fun addListener(listener: CameraDelegator.OnFrameAvailableListener) { mCameraDelegator.addListener(listener) } /** * ICameraViewの実装 */ override fun removeListener(listener: CameraDelegator.OnFrameAvailableListener) { mCameraDelegator.removeListener(listener) } /** * ICameraViewの実装 */ override fun setScaleMode(mode: Int) { mCameraDelegator.scaleMode = mode (mCameraDelegator.cameraRenderer as CameraRenderer).updateViewport() } /** * ICameraViewの実装 */ override fun getScaleMode(): Int { return mCameraDelegator.scaleMode } /** * ICameraViewの実装 */ override fun setVideoSize(width: Int, height: Int) { mCameraDelegator.setVideoSize(width, height) } /** * ICameraViewの実装 */ override fun getVideoWidth(): Int { return mCameraDelegator.previewWidth } /** * ICameraViewの実装 */ override fun getVideoHeight(): Int { return mCameraDelegator.previewHeight } /** * プレビュー表示用Surfaceを追加 * @param id * @param surface * @param isRecordable */ @Synchronized override fun addSurface( id: Int, surface: Any, isRecordable: Boolean, maxFps: Fraction?) { if (DEBUG) Log.v(TAG, "addSurface:$id") if (mDistributor == null) { mDistributor = SurfaceDistributePipeline(mVideoSourcePipeline!!.glManager) GLPipeline.append(mVideoSourcePipeline!!, mDistributor!!) } mDistributor!!.addSurface(id, surface, isRecordable, maxFps) } /** * プレビュー表示用Surfaceを除去 * @param id */ @Synchronized override fun removeSurface(id: Int) { if (DEBUG) Log.v(TAG, "removeSurface:$id") mDistributor?.removeSurface(id) } override fun isRecordingSupported(): Boolean { return true } /** * GLPipelineViewの実装 */ override fun addPipeline(pipeline: GLPipeline) { val source = mVideoSourcePipeline if (source != null) { GLPipeline.append(source, pipeline) if (DEBUG) Log.v(TAG, "addPipeline:" + GLPipeline.pipelineString(source)) } else { throw IllegalStateException() } } // GLPipelineView#getGLManagerはGLViewに等価な#getGLManagerがあるので実装不要 /** * VideoSourceインスタンスを生成 * @param width * @param height * @return */ private fun createVideoSource( width: Int, height: Int): VideoSourcePipeline { return VideoSourcePipeline(getGLManager(), width, height, object : PipelineSourceCallback { override fun onCreate(surface: Surface) { if (DEBUG) Log.v(TAG, "PipelineSourceCallback#onCreate:$surface") } override fun onDestroy() { if (DEBUG) Log.v(TAG, "PipelineSourceCallback#onDestroy:") } }, USE_SHARED_CONTEXT) } private var mDrawer: GLDrawer2D? = null private var cnt2 = 0 /** * 描画処理の実体 * レンダリングスレッド上で実行 * @param texId * @param texMatrix */ @WorkerThread private fun handleDraw(texId: Int, texMatrix: FloatArray) { if (DEBUG && ((++cnt2 % 100) == 0)) Log.v(TAG, "handleDraw:$cnt2") // draw to preview screen if ((mDrawer != null) && (mVideoSourcePipeline != null)) { mDrawer!!.draw(GLES20.GL_TEXTURE0, texId, texMatrix, 0) } GLES20.glFlush() mCameraDelegator.callOnFrameAvailable() } /** * ICameraRendererの実装 */ @SuppressLint("WrongThread") private inner class CameraRenderer : ICameraRenderer { override fun hasSurface(): Boolean { return mVideoSourcePipeline != null } override fun onPreviewSizeChanged(width: Int, height: Int) { mVideoSourcePipeline!!.resize(width, height) } override fun getInputSurface(): SurfaceTexture { if (DEBUG) Log.v(TAG, "getInputSurfaceTexture:") checkNotNull(mVideoSourcePipeline) return mVideoSourcePipeline!!.inputSurfaceTexture } fun updateViewport() { // val viewWidth = width // val viewHeight = height // if ((viewWidth == 0) || (viewHeight == 0)) { // if (DEBUG) Log.v(TAG, String.format("updateViewport:view is not ready(%dx%d)", // viewWidth, viewHeight)) // return // } // if (!mHasSurface || (mTarget == null)) { // if (DEBUG) Log.v(TAG, "updateViewport:has no surface") // return // } // mTarget!!.makeCurrent() // mTarget!!.setViewPort(0, 0, viewWidth, viewHeight) // GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT) // val videoWidth = mCameraDelegator.width.toDouble() // val videoHeight = mCameraDelegator.height.toDouble() // if ((videoWidth == 0.0) || (videoHeight == 0.0)) { // if (DEBUG) Log.v(TAG, String.format("updateViewport:video is not ready(%dx%d)", // viewWidth, viewHeight)) // return // } // val viewAspect = viewWidth / viewHeight.toDouble() // Log.i(TAG, String.format("updateViewport:view(%d,%d)%f,video(%1.0f,%1.0f)", // viewWidth, viewHeight, viewAspect, videoWidth, videoHeight)) // Matrix.setIdentityM(mMvpMatrix, 0) // val scaleMode = mCameraDelegator.scaleMode // when (scaleMode) { // CameraDelegator.SCALE_STRETCH_FIT -> { // } // CameraDelegator.SCALE_KEEP_ASPECT_VIEWPORT -> { // val req = videoWidth / videoHeight // val x: Int // val y: Int // val width: Int // val height: Int // if (viewAspect > req) { // // if view is wider than camera image, calc width of drawing area based on view height // y = 0 // height = viewHeight // width = (req * viewHeight).toInt() // x = (viewWidth - width) / 2 // } else { // // if view is higher than camera image, calc height of drawing area based on view width // x = 0 // width = viewWidth // height = (viewWidth / req).toInt() // y = (viewHeight - height) / 2 // } // // set viewport to draw keeping aspect ration of camera image // Log.i(TAG, String.format("updateViewport;xy(%d,%d),size(%d,%d)", x, y, width, height)) // mTarget!!.setViewPort(0, 0, width, height) // } // CameraDelegator.SCALE_KEEP_ASPECT, CameraDelegator.SCALE_CROP_CENTER -> { // val scale_x = viewWidth / videoWidth // val scale_y = viewHeight / videoHeight // val scale // = if (scaleMode == CameraDelegator.SCALE_CROP_CENTER) // Math.max(scale_x, scale_y) else Math.min(scale_x, scale_y) // val width = scale * videoWidth // val height = scale * videoHeight // Log.i(TAG, String.format("updateViewport:size(%1.0f,%1.0f),scale(%f,%f),mat(%f,%f)", // width, height, scale_x, scale_y, width / viewWidth, height / viewHeight)) // Matrix.scaleM(mMvpMatrix, 0, // (width / viewWidth).toFloat(), // (height / viewHeight).toFloat(), // 1.0f) // } // } // mDrawer!!.setMvpMatrix(mMvpMatrix, 0) // mTarget!!.swap() } } // CameraRenderer companion object { private const val DEBUG = true // TODO set false on release private val TAG = VideoSourceCameraGLView::class.java.simpleName /** * 共有GLコンテキストコンテキストを使ったマルチスレッド処理を行うかどうか */ private const val USE_SHARED_CONTEXT = false } }
apache-2.0
0900fc3f5ab42211e91ebfea1061a80a
27.979112
95
0.701144
3.41718
false
false
false
false
Zeyad-37/GenericUseCase
sampleApp/src/main/java/com/zeyad/usecases/app/screens/user/detail/UserDetailActivity.kt
2
3167
package com.zeyad.usecases.app.screens.user.detail import android.content.Context import android.content.Intent import android.os.Bundle import android.support.design.widget.CollapsingToolbarLayout import android.support.v4.app.Fragment import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.util.Pair import android.view.MenuItem import android.view.View import android.widget.ImageView import com.zeyad.usecases.app.R import com.zeyad.usecases.app.screens.user.list.UserListActivity import kotlinx.android.synthetic.main.activity_user_detail.* /** * An activity representing a single Repository detail screen. This activity is only used narrow * width devices. On tablet-size devices, item details are presented side-by-side with a list of * items in a [UserListActivity]. */ class UserDetailActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_user_detail) setSupportActionBar(detail_toolbar) val actionBar = supportActionBar if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true) actionBar.title = "" } if (savedInstanceState == null) { val fragment = UserDetailFragment.newInstance(intent.getParcelableExtra(UI_MODEL)) addFragment(R.id.user_detail_container, fragment, fragment.tag, null) } } private fun addFragment(containerViewId: Int, fragment: Fragment, currentFragTag: String?, sharedElements: List<Pair<View, String>>?) { val fragmentTransaction = supportFragmentManager.beginTransaction() if (sharedElements != null) { for (pair in sharedElements) { fragmentTransaction.addSharedElement(pair.first, pair.second) } } if (currentFragTag == null || currentFragTag.isEmpty()) { fragmentTransaction.addToBackStack(fragment.tag) } else { fragmentTransaction.addToBackStack(currentFragTag) } fragmentTransaction.add(containerViewId, fragment, fragment.tag).commit() } override fun onBackPressed() { // navigateUpTo(new Intent(this, UserListActivity.class)); supportFinishAfterTransition() // exit animation } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } fun getImageViewAvatar(): ImageView = imageView_avatar fun getToolbar(): Toolbar = detail_toolbar fun getCollapsingToolbarLayout(): CollapsingToolbarLayout = toolbar_layout companion object { const val UI_MODEL = "uiModel" fun getCallingIntent(context: Context, userDetailModel: UserDetailState): Intent { return Intent(context, UserDetailActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .putExtra(UI_MODEL, userDetailModel) } } }
apache-2.0
2d3d66a2d55e00ba1a4e018c5cece6c0
38.098765
106
0.692453
4.933022
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-existdb/main/uk/co/reecedunn/intellij/plugin/existdb/lang/EXistDB.kt
1
2571
/* * Copyright (C) 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.existdb.lang import com.intellij.navigation.ItemPresentation import uk.co.reecedunn.intellij.plugin.existdb.resources.EXistDBIcons import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmProductType import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmProductVersion import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSchemaFile import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmVendorType import java.io.File import javax.swing.Icon object EXistDB : ItemPresentation, XpmVendorType, XpmProductType { // region ItemPresentation override fun getPresentableText(): String = "eXist-db / FusionDB" override fun getLocationString(): String? = null override fun getIcon(unused: Boolean): Icon = EXistDBIcons.Product.EXistDB // endregion // region XpmVendorType / XpmProductType override val id: String = "exist-db" override val presentation: ItemPresentation get() = this // endregion // region XpmVendorType override fun isValidInstallDir(installDir: String): Boolean = File("$installDir/exist.log").exists() override val modulePath: String? = null override fun schemaFiles(path: String): Sequence<XpmSchemaFile> = sequenceOf() // endregion // region Language Versions val VERSION_3_0: XpmProductVersion = EXistDBVersion(this, 3, 0, "XQuery 3.0 REC, array, map, json") val VERSION_3_1: XpmProductVersion = EXistDBVersion(this, 3, 1, "arrow operator '=>', string constructors") val VERSION_3_6: XpmProductVersion = EXistDBVersion(this, 3, 6, "declare context item") val VERSION_4_0: XpmProductVersion = EXistDBVersion(this, 4, 0, "XQuery 3.1 REC") val VERSION_4_3: XpmProductVersion = EXistDBVersion(this, 4, 0, "XMLSchema 1.1") @Suppress("unused") val languageVersions: List<XpmProductVersion> = listOf( VERSION_3_0, VERSION_3_1, VERSION_3_6, VERSION_4_0, VERSION_4_3 ) // endregion }
apache-2.0
01a3dd45e07a7232f5ef8175daa3436c
34.708333
111
0.726566
3.883686
false
false
false
false
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/common/basic/models/options/_basic/Utils.kt
1
4924
package wangdaye.com.geometricweather.common.basic.models.options._basic import android.content.Context import android.content.res.Resources import android.text.BidiFormatter import androidx.annotation.ArrayRes import kotlin.math.pow import kotlin.math.roundToInt object Utils { fun getName( context: Context, enum: BaseEnum ) = getNameByValue( res = context.resources, value = enum.id, nameArrayId = enum.nameArrayId, valueArrayId = enum.valueArrayId )!! fun getVoice( context: Context, enum: VoiceEnum ) = getNameByValue( res = context.resources, value = enum.id, nameArrayId = enum.voiceArrayId, valueArrayId = enum.valueArrayId )!! fun getNameByValue( res: Resources, value: String, @ArrayRes nameArrayId: Int, @ArrayRes valueArrayId: Int ): String? { val names = res.getStringArray(nameArrayId) val values = res.getStringArray(valueArrayId) return getNameByValue(value, names, values) } private fun getNameByValue( value: String, names: Array<String>, values: Array<String> ) = values.zip(names).firstOrNull { it.first == value }?.second fun getValueTextWithoutUnit( enum: UnitEnum<Float>, valueInDefaultUnit: Float, decimalNumber: Int ) = BidiFormatter .getInstance() .unicodeWrap( formatFloat( enum.getValueWithoutUnit(valueInDefaultUnit), decimalNumber ) ) fun getValueTextWithoutUnit( enum: UnitEnum<Int>, valueInDefaultUnit: Int ) = BidiFormatter .getInstance() .unicodeWrap( formatInt( enum.getValueWithoutUnit(valueInDefaultUnit), ) ) fun getValueText( context: Context, enum: UnitEnum<Float>, valueInDefaultUnit: Float, decimalNumber: Int, rtl: Boolean ) = if (rtl) { (BidiFormatter .getInstance() .unicodeWrap( formatFloat( enum.getValueWithoutUnit(valueInDefaultUnit), decimalNumber ) ) + "\u202f" + getName(context, enum)) } else { (formatFloat( enum.getValueWithoutUnit(valueInDefaultUnit), decimalNumber ) + "\u202f" + getName(context, enum)) } fun getValueText( context: Context, enum: UnitEnum<Int>, valueInDefaultUnit: Int, rtl: Boolean ) = if (rtl) { (BidiFormatter .getInstance() .unicodeWrap( formatInt( enum.getValueWithoutUnit(valueInDefaultUnit), ) ) + "\u202f" + getName(context, enum)) } else { (formatInt( enum.getValueWithoutUnit(valueInDefaultUnit), ) + "\u202f" + getName(context, enum)) } fun getVoiceText( context: Context, enum: UnitEnum<Float>, valueInDefaultUnit: Float, decimalNumber: Int, rtl: Boolean ) = if (rtl) { (BidiFormatter .getInstance() .unicodeWrap( formatFloat( enum.getValueWithoutUnit(valueInDefaultUnit), decimalNumber ) ) + "\u202f" + getVoice(context, enum)) } else { (formatFloat( enum.getValueWithoutUnit(valueInDefaultUnit), decimalNumber ) + "\u202f" + getVoice(context, enum)) } fun getVoiceText( context: Context, enum: UnitEnum<Int>, valueInDefaultUnit: Int, rtl: Boolean ) = if (rtl) { (BidiFormatter .getInstance() .unicodeWrap( formatInt( enum.getValueWithoutUnit(valueInDefaultUnit), ) ) + "\u202f" + getVoice(context, enum)) } else { (formatInt( enum.getValueWithoutUnit(valueInDefaultUnit), ) + "\u202f" + getVoice(context, enum)) } @JvmOverloads fun formatFloat(value: Float, decimalNumber: Int = 2): String { val factor = 10.0.pow(decimalNumber.toDouble()).toFloat() return if ( value.roundToInt() * factor == (value * factor).roundToInt().toFloat() ) { value.roundToInt().toString() } else { String.format("%." + decimalNumber + "f", value) } } fun formatInt(value: Int) = String.format("%d", value) }
lgpl-3.0
51b573e07c0d41b4d504518db198f15d
25.766304
82
0.522136
4.662879
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/ui/custom_exo/NavigationBarUtil.kt
2
1510
package org.stepic.droid.ui.custom_exo import android.app.Activity import android.os.Build import android.view.View import android.view.WindowManager import org.stepic.droid.util.AndroidDevices import org.stepic.droid.util.hasCombinationBar object NavigationBarUtil { fun hideNavigationBar(needHide: Boolean = true, activity: Activity?) { if (activity == null) { return } var visibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN var navigationBar = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION if (needHide) { activity.window?.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) @Suppress("DEPRECATION") navigationBar = navigationBar or View.SYSTEM_UI_FLAG_LOW_PROFILE if (!hasCombinationBar(activity.applicationContext)) { navigationBar = navigationBar or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION visibility = visibility or View.SYSTEM_UI_FLAG_IMMERSIVE visibility = visibility or View.SYSTEM_UI_FLAG_FULLSCREEN } } else { activity.window?.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) @Suppress("DEPRECATION") visibility = visibility or View.SYSTEM_UI_FLAG_VISIBLE } if (AndroidDevices.hasNavBar()) { visibility = visibility or navigationBar } activity.window?.decorView?.systemUiVisibility = visibility } }
apache-2.0
757b7d98876565d895b6870405129336
35.853659
99
0.672185
4.71875
false
false
false
false
rolandvitezhu/TodoCloud
app/src/main/java/com/rolandvitezhu/todocloud/repository/ListRepository.kt
1
3945
package com.rolandvitezhu.todocloud.repository import com.rolandvitezhu.todocloud.app.AppController.Companion.instance import com.rolandvitezhu.todocloud.data.List import java.util.* import javax.inject.Inject import javax.inject.Singleton @Singleton class ListRepository @Inject constructor() : BaseRepository() { private var listsToUpdate: ArrayList<List>? = null private var listsToInsert: ArrayList<List>? = null suspend fun syncListData() { val response = apiService.getLists(todoCloudDatabaseDao.getLastListRowVersion()) if (response.error.toUpperCase(Locale.getDefault()).equals("FALSE")) { // Process the response updateListsInLocalDatabase(response.lists) updateAndOrInsertLists() } else { // Process the error response throw Throwable(response.message) } } private suspend fun updateAndOrInsertLists() { val response = apiService.getNextRowVersion("list", todoCloudDatabaseDao.getCurrentApiKey()) if (response.error.toUpperCase(Locale.getDefault()).equals("FALSE")) { // Process the response nextRowVersion = response.nextRowVersion ?: 0 listsToUpdate = todoCloudDatabaseDao.getListsToUpdate() listsToInsert = todoCloudDatabaseDao.getListsToInsert() setRowVersionsForLists(listsToUpdate) setRowVersionsForLists(listsToInsert) updateLists() insertLists() } else { // Process the error response throw Throwable(response.message) } } private suspend fun updateListsInLocalDatabase(lists: ArrayList<List?>?) { if (!lists.isNullOrEmpty()) { for (list in lists) { val exists = list!!.listOnlineId?.let { todoCloudDatabaseDao.isListExists(it) } if (exists == true) { todoCloudDatabaseDao.updateList(list) } else { todoCloudDatabaseDao.insertList(list) } } } } private fun setRowVersionsForLists(lists: ArrayList<List>?) { if (!lists.isNullOrEmpty()) { for (list in lists) { list.rowVersion = nextRowVersion++ } } } private suspend fun updateLists() { if (!listsToUpdate.isNullOrEmpty()) { // Process the list for (listToUpdate in listsToUpdate!!) { // Process the list item val response = apiService.updateList(listToUpdate) if (response.error.toUpperCase(Locale.getDefault()).equals("FALSE")) { // Process the response makeListUpToDate(listToUpdate) } else { // Process the error response throw Throwable(response.message) } } } } private suspend fun insertLists() { if (!listsToInsert.isNullOrEmpty()) { // Process the list for (listToInsert in listsToInsert!!) { // Process the list item val response = apiService.insertList(listToInsert) if (response.error.toUpperCase(Locale.getDefault()).equals("FALSE")) { // Process the response makeListUpToDate(listToInsert) } else { // Process the error response throw Throwable(response.message) } } } } private suspend fun makeListUpToDate(listToUpdate: List) { listToUpdate.dirty = false todoCloudDatabaseDao.updateList(listToUpdate) } companion object { private val TAG = ListRepository::class.java.simpleName } init { Objects.requireNonNull(instance)?.appComponent?.inject(this) } }
mit
91394cd9ac3a87f1f15ee720ccc82caa
33.313043
95
0.586058
5.40411
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/GraphicalTilesetResources.kt
1
1514
package org.hexworks.zircon.api import org.hexworks.zircon.api.resource.TilesetResource import org.hexworks.zircon.internal.resource.BuiltInGraphicalTilesetResource import org.hexworks.zircon.internal.resource.GraphicalTilesetResource import org.hexworks.zircon.internal.resource.TilesetSourceType import kotlin.jvm.JvmStatic /** * This object can be used to load either built-in graphical * [TilesetResource]s or external ones. */ object GraphicalTilesetResources { @JvmStatic fun nethack16x16(): TilesetResource = BuiltInGraphicalTilesetResource.NETHACK_16X16 /** * Use this function if you want to load a [TilesetResource] * from the filesystem. */ @JvmStatic fun loadTilesetFromFilesystem( width: Int, height: Int, path: String ): TilesetResource { return GraphicalTilesetResource( width = width, height = height, path = path, tilesetSourceType = TilesetSourceType.FILESYSTEM ) } /** * Use this function if you want to load a [TilesetResource] * which is bundled into a jar file which you build from * your application. */ @JvmStatic fun loadTilesetFromJar( width: Int, height: Int, path: String ): TilesetResource { return GraphicalTilesetResource( width = width, height = height, path = path, tilesetSourceType = TilesetSourceType.JAR ) } }
apache-2.0
24639d002fee5e9736d46e0dda342372
27.037037
87
0.659181
4.746082
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/group/visual/EngineVisualGroup.kt
1
6033
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.group.visual import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimMotionGroupBase import com.maddyhome.idea.vim.api.VimVisualPosition import com.maddyhome.idea.vim.api.getLineEndOffset import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.isLineEmpty import com.maddyhome.idea.vim.command.VimStateMachine import com.maddyhome.idea.vim.helper.inBlockSubMode import com.maddyhome.idea.vim.helper.inSelectMode import com.maddyhome.idea.vim.helper.inVisualMode import com.maddyhome.idea.vim.helper.mode import com.maddyhome.idea.vim.helper.subMode fun setVisualSelection(selectionStart: Int, selectionEnd: Int, caret: VimCaret) { val (start, end) = if (selectionStart > selectionEnd) selectionEnd to selectionStart else selectionStart to selectionEnd val editor = caret.editor val subMode = editor.subMode val mode = editor.mode when (subMode) { VimStateMachine.SubMode.VISUAL_CHARACTER -> { val (nativeStart, nativeEnd) = charToNativeSelection(editor, start, end, mode) caret.vimSetSystemSelectionSilently(nativeStart, nativeEnd) } VimStateMachine.SubMode.VISUAL_LINE -> { val (nativeStart, nativeEnd) = lineToNativeSelection(editor, start, end) caret.vimSetSystemSelectionSilently(nativeStart, nativeEnd) } VimStateMachine.SubMode.VISUAL_BLOCK -> { // This will invalidate any secondary carets, but we shouldn't have any of these cached in local variables, etc. editor.removeSecondaryCarets() // Set system selection val (blockStart, blockEnd) = blockToNativeSelection(editor, selectionStart, selectionEnd, mode) val lastColumn = editor.primaryCaret().vimLastColumn // WARNING! This can invalidate the primary caret! I.e. the `caret` parameter will no longer be the primary caret. // Given an existing visual block selection, moving the caret will first remove all secondary carets (above) then // this method will ask IntelliJ to create a new multi-caret block selection. If we're moving up (`k`) a new caret // is added, and becomes the new primary caret. The current `caret` parameter remains valid, but is no longer the // primary caret. Make sure to fetch the new primary caret if necessary. editor.vimSetSystemBlockSelectionSilently(blockStart, blockEnd) // We've just added secondary carets again, hide them to better emulate block selection editor.updateCaretsVisualAttributes() for (aCaret in editor.nativeCarets()) { if (!aCaret.isValid) continue val line = aCaret.getBufferPosition().line val lineEndOffset = editor.getLineEndOffset(line, true) val lineStartOffset = editor.getLineStartOffset(line) // Extend selection to line end if it was made with `$` command if (lastColumn >= VimMotionGroupBase.LAST_COLUMN) { aCaret.vimSetSystemSelectionSilently(aCaret.selectionStart, lineEndOffset) val newOffset = (lineEndOffset - injector.visualMotionGroup.selectionAdj).coerceAtLeast(lineStartOffset) aCaret.moveToInlayAwareOffset(newOffset) } val visualPosition = editor.offsetToVisualPosition(aCaret.selectionEnd) if (aCaret.offset.point == aCaret.selectionEnd && visualPosition != aCaret.getVisualPosition()) { // Put right caret position for tab character aCaret.moveToVisualPosition(visualPosition) } if (mode != VimStateMachine.Mode.SELECT && !editor.isLineEmpty(line, false) && aCaret.offset.point == aCaret.selectionEnd && aCaret.selectionEnd - 1 >= lineStartOffset && aCaret.selectionEnd - aCaret.selectionStart != 0 ) { // Move all carets one char left in case if it's on selection end aCaret.moveToVisualPosition(VimVisualPosition(visualPosition.line, visualPosition.column - 1)) } } editor.primaryCaret().moveToInlayAwareOffset(selectionEnd) } else -> Unit } } /** * Set selection for caret * This method doesn't change CommandState and operates only with caret and it's properties * if [moveCaretToSelectionEnd] is true, caret movement to [end] will be performed */ fun VimCaret.vimSetSelection(start: Int, end: Int = start, moveCaretToSelectionEnd: Boolean = false) { vimSelectionStart = start setVisualSelection(start, end, this) if (moveCaretToSelectionEnd && !editor.inBlockSubMode) moveToInlayAwareOffset(end) } /** * Move selection end to current primary caret position * * This method is created only for block mode. Note that this method will invalidate all carets! * * @see vimMoveSelectionToCaret for character and line selection */ fun vimMoveBlockSelectionToOffset(editor: VimEditor, offset: Int) { val primaryCaret = editor.primaryCaret() val startOffsetMark = primaryCaret.vimSelectionStart setVisualSelection(startOffsetMark, offset, primaryCaret) } /** * Move selection end to current caret position * This method is created only for Character and Line mode * @see vimMoveBlockSelectionToOffset for blockwise selection */ fun VimCaret.vimMoveSelectionToCaret() { if (!editor.inVisualMode && !editor.inSelectMode) error("Attempt to extent selection in non-visual mode") if (editor.inBlockSubMode) error("Move caret with [vimMoveBlockSelectionToOffset]") val startOffsetMark = vimSelectionStart setVisualSelection(startOffsetMark, offset.point, this) } /** * Update selection according to new CommandState * This method should be used for switching from character to line wise selection and so on */ fun VimCaret.vimUpdateEditorSelection() { val startOffsetMark = vimSelectionStart setVisualSelection(startOffsetMark, offset.point, this) }
mit
8e5d91373f582aa8a630c50ba90df42d
43.036496
122
0.745235
4.508969
false
false
false
false
JoeSteven/HuaBan
bak/src/main/java/com/joey/bak/data/bean/Picture.kt
1
803
package com.joe.zatuji.data.bean import android.os.Parcelable /** * Description: * author:Joey * date:2018/11/19 */ @Parcelize data class Picture(@SerializedName("pin_id") val id: String, @SerializedName("file") val file: PicFile, @SerializedName("raw_text") var raw_text: String) : Parcelable { val url:String get() = file.url val type:String get() = file.type val width: Int get() = file.width val height: Int get() = file.height } @Parcelize data class PicFile(@SerializedName("key") var url: String, @SerializedName("type") var type: String, @SerializedName("width") var width: Int = 0, @SerializedName("height") var height: Int = 0) : Parcelable
apache-2.0
9b1daa6363396c06c6ec2e81998cb06d
24.935484
83
0.587796
4.055556
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/util/DateTimeUtilsWrapper.kt
1
831
package org.wordpress.android.util import android.content.Context import java.util.Date import javax.inject.Inject class DateTimeUtilsWrapper @Inject constructor( private val localeManagerWrapper: LocaleManagerWrapper, private val appContext: Context ) { fun currentTimeInIso8601(): String = DateTimeUtils.iso8601FromTimestamp(localeManagerWrapper.getCurrentCalendar().timeInMillis / 1000) fun javaDateToTimeSpan(date: Date?): String = DateTimeUtils.javaDateToTimeSpan(date, appContext) fun dateFromIso8601(date: String) = DateTimeUtils.dateFromIso8601(date) fun daysBetween(start: Date, end: Date) = DateTimeUtils.daysBetween(start, end) fun dateFromTimestamp(timestamp: Long) = DateTimeUtils.dateFromTimestamp(timestamp) fun getTodaysDate() = Date(System.currentTimeMillis()) }
gpl-2.0
2b607be69afa27c4c9a0aa964021526c
35.130435
109
0.78219
4.616667
false
false
false
false
Turbo87/intellij-rust
src/main/kotlin/org/rust/lang/core/resolve/indexes/RustModulesIndexExtension.kt
1
4447
package org.rust.lang.core.resolve.indexes import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.util.containers.HashMap import com.intellij.util.indexing.* import com.intellij.util.io.DataExternalizer import com.intellij.util.io.KeyDescriptor import org.rust.lang.RustFileType import org.rust.lang.core.names.RustFileModuleId import org.rust.lang.core.names.RustQualifiedName import org.rust.lang.core.psi.RustModItem import org.rust.lang.core.psi.RustVisitor import org.rust.lang.core.psi.impl.RustFileImpl import org.rust.lang.core.psi.util.canonicalNameInFile import org.rust.lang.core.psi.util.modDecls import java.io.DataInput import java.io.DataOutput class RustModulesIndexExtension : FileBasedIndexExtension<RustModulePath, RustQualifiedName>() { override fun getVersion(): Int = 1 override fun dependsOnFileContent(): Boolean = true override fun getName(): ID<RustModulePath, RustQualifiedName> = RustModulesIndex.ID override fun getInputFilter(): FileBasedIndex.InputFilter = DefaultFileTypeSpecificInputFilter(RustFileType) override fun getKeyDescriptor(): KeyDescriptor<RustModulePath> = keyDescriptor override fun getValueExternalizer(): DataExternalizer<RustQualifiedName> = valueExternalizer override fun getIndexer(): DataIndexer<RustModulePath, RustQualifiedName, FileContent> = dataIndexer companion object { val keyDescriptor = object: KeyDescriptor<RustModulePath> { override fun save(out: DataOutput, path: RustModulePath?) { path?.let { RustModulePath.writeTo(out, it) } } override fun read(`in`: DataInput): RustModulePath? = RustModulePath.readFrom(`in`) override fun isEqual(one: RustModulePath?, other: RustModulePath?): Boolean = one?.equals(other) ?: one == other override fun getHashCode(value: RustModulePath?): Int = value?.hashCode() ?: -1 } val valueExternalizer = object: DataExternalizer<RustQualifiedName> { override fun save(out: DataOutput, name: RustQualifiedName?) { name?.let({ val tip = it as RustFileModuleId RustModulePath .writeTo(out, tip.part.path) RustQualifiedName .writeTo(out, name.remove(tip)!!) }) } override fun read(`in`: DataInput): RustQualifiedName? { val path = RustModulePath .readFrom(`in`) val name = RustQualifiedName.readFrom(`in`) return name?.put(path?.let { RustFileModuleId(it) }) } } val dataIndexer = DataIndexer<RustModulePath, RustQualifiedName, FileContent> { val map = HashMap<RustModulePath, RustQualifiedName>() PsiManager.getInstance(it.project).findFile(it.file)?.let { process(it).entries.forEach { val qualName = it.key it.value.forEach { map.put(RustModulePath.devise(it), qualName) } } } map } private fun process(f: PsiFile): Map<RustQualifiedName, List<PsiFile>> { val raw = HashMap<RustQualifiedName, List<PsiFile>>() f.accept(object: RustVisitor() { // // TODO(kudinkin): move this `RustVisitor` // override fun visitFile(file: PsiFile?) { (file as? RustFileImpl)?.let { it.mod?.accept(this) } } override fun visitModItem(m: RustModItem) { val resolved = arrayListOf<PsiFile>() m.modDecls.forEach { decl -> decl.reference?.let { ref -> (ref.resolve() as RustModItem?)?.let { mod -> resolved.add(mod.containingFile) } } } if (resolved.size > 0) m.canonicalNameInFile?.let { raw.put(it, resolved) } m.acceptChildren(this) } }) return raw } } }
mit
a89325482d2dbff8b12b4cbdaf625fda
34.015748
104
0.574545
5.059158
false
false
false
false
ingokegel/intellij-community
platform/platform-impl/src/com/intellij/util/PopupUtils.kt
9
7234
// 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.util import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.VisualPosition import com.intellij.openapi.editor.ex.EditorGutterComponentEx import com.intellij.openapi.editor.ex.EditorGutterComponentEx.ICON_CENTER_POSITION import com.intellij.openapi.editor.ex.EditorGutterComponentEx.LOGICAL_LINE_AT_CURSOR import com.intellij.openapi.editor.ex.util.EditorUtil.getDefaultCaretWidth import com.intellij.openapi.editor.ex.util.EditorUtil.logicalToVisualLine import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.wm.WindowManager import com.intellij.ui.awt.RelativePoint import com.intellij.ui.popup.PopupFactoryImpl import java.awt.Dimension import java.awt.Point import java.awt.Rectangle import javax.swing.JComponent import javax.swing.JList import javax.swing.JTable import javax.swing.JTree fun getBestPopupPosition(context: DataContext): RelativePoint { return getBestPopupPositionInsideGutter(context) ?: getBestPopupPositionInsideComponent(context) } fun getBestBalloonPosition(context: DataContext): RelativePoint { return getBestBalloonPositionInsideGutter(context) ?: getBestBalloonPositionInsideEditor(context) ?: getBestBalloonPositionInsideList(context) ?: getBestBalloonPositionInsideTree(context) ?: getBestBalloonPositionInsideTable(context) ?: getBestBalloonPositionInsideComponent(context) } private fun getBestPopupPositionInsideGutter(context: DataContext): RelativePoint? { return getBestPositionInsideGutter(context, Rectangle::bottomCenter) } private fun getBestPopupPositionInsideComponent(context: DataContext): RelativePoint { return JBPopupFactory.getInstance().guessBestPopupLocation(context) } private fun getBestBalloonPositionInsideGutter(context: DataContext): RelativePoint? { return getBestPositionInsideGutter(context, Rectangle::topCenter) } private fun getBestPositionInsideGutter(context: DataContext, location: Rectangle.() -> Point): RelativePoint? { val component = getFocusComponent<EditorGutterComponentEx>(context) ?: return null val editor = CommonDataKeys.EDITOR.getData(context) ?: return null val logicalLine = context.getData(LOGICAL_LINE_AT_CURSOR) ?: return null val iconCenterPosition = context.getData(ICON_CENTER_POSITION) ?: return null val renderer = component.getGutterRenderer(iconCenterPosition) ?: return null val visualLine = logicalToVisualLine(editor, logicalLine) val visibleArea = component.visibleRect val x = iconCenterPosition.x - renderer.icon.iconWidth / 2 val rect = Rectangle(x, visualLine * editor.lineHeight, renderer.icon.iconWidth, editor.lineHeight) if (!visibleArea.contains(rect)) component.scrollRectToVisible(rect) return RelativePoint(component, rect.location()) } private fun getBestBalloonPositionInsideEditor(context: DataContext): RelativePoint? { val component = PlatformCoreDataKeys.CONTEXT_COMPONENT.getData(context) val editor = CommonDataKeys.EDITOR.getData(context) ?: return null val contentComponent = editor.contentComponent if (contentComponent !== component) return null val caretVisualPosition = editor.getCaretVisualPosition() val caretPosition = editor.visualPositionToXY(caretVisualPosition) val visibleArea = editor.scrollingModel.visibleArea val rect = Rectangle(caretPosition, Dimension(getDefaultCaretWidth(), editor.lineHeight)) if (!visibleArea.contains(rect)) component.scrollRectToVisible(rect) return RelativePoint(contentComponent, caretPosition) } private fun Editor.getCaretVisualPosition(): VisualPosition { val anchorPosition = getUserData(PopupFactoryImpl.ANCHOR_POPUP_POSITION) if (anchorPosition != null) return anchorPosition if (caretModel.isUpToDate) return caretModel.visualPosition return offsetToVisualPosition(caretModel.offset) } private fun getBestBalloonPositionInsideList(context: DataContext): RelativePoint? { val component = getFocusComponent<JList<*>>(context) ?: return null val visibleRect = component.visibleRect val firstVisibleIndex = component.firstVisibleIndex val lastVisibleIndex = component.lastVisibleIndex val selectedIndices = component.selectedIndices for (index in selectedIndices) { if (index in firstVisibleIndex..lastVisibleIndex) { val cellBounds = component.getCellBounds(index, index) val position = Point(visibleRect.x + visibleRect.width / 4, cellBounds.y) return RelativePoint(component, position) } } return null } private fun getBestBalloonPositionInsideTree(context: DataContext): RelativePoint? { val component = getFocusComponent<JTree>(context) ?: return null val visibleRect = component.visibleRect val selectionRows = component.selectionRows ?: return null for (row in selectionRows.sorted()) { val rowBounds = component.getRowBounds(row) if (!visibleRect.contains(rowBounds)) continue return RelativePoint(component, rowBounds.topCenter()) } val visibleCenter = visibleRect.center() val distance = { it: Int -> visibleCenter.distance(component.getRowBounds(it).center()) } val nearestRow = selectionRows.sortedBy(distance).firstOrNull() ?: return null val rowBounds = component.getRowBounds(nearestRow) val dimension = Dimension(Math.min(visibleRect.width, rowBounds.width), rowBounds.height) component.scrollRectToVisible(Rectangle(rowBounds.position(), dimension)) return RelativePoint(component, rowBounds.topCenter()) } private fun getBestBalloonPositionInsideTable(context: DataContext): RelativePoint? { val component = getFocusComponent<JTable>(context) ?: return null val visibleRect = component.visibleRect val column = component.columnModel.selectionModel.leadSelectionIndex val row = Math.max(component.selectionModel.leadSelectionIndex, component.selectionModel.anchorSelectionIndex) val rect = component.getCellRect(row, column, false) if (!visibleRect.intersects(rect)) component.scrollRectToVisible(rect) return RelativePoint(component, rect.position()) } private fun getBestBalloonPositionInsideComponent(context: DataContext): RelativePoint { val component = getFocusComponent<JComponent>(context)!! return RelativePoint(component, component.visibleRect.center()) } private inline fun <reified C : JComponent> getFocusComponent(context: DataContext): C? { val component = PlatformCoreDataKeys.CONTEXT_COMPONENT.getData(context) if (component is C) return component val project = CommonDataKeys.PROJECT.getData(context) val frame = project?.let { WindowManager.getInstance().getFrame(it) } val focusOwner = frame?.rootPane if (focusOwner is C) return focusOwner return null } private fun Rectangle.topCenter() = Point(centerX.toInt(), y) private fun Rectangle.bottomCenter() = Point(centerX.toInt(), y + height) private fun Rectangle.center() = Point(centerX.toInt(), centerY.toInt()) private fun Rectangle.position() = Point(x, y)
apache-2.0
8cff5a1b5122079b223986fa830c94ff
46.598684
140
0.802461
4.69131
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/structuralsearch/visitor/KotlinMatchingVisitor.kt
2
65387
// 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.structuralsearch.visitor import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.elementType import com.intellij.structuralsearch.StructuralSearchUtil import com.intellij.structuralsearch.impl.matcher.CompiledPattern import com.intellij.structuralsearch.impl.matcher.GlobalMatchingVisitor import com.intellij.structuralsearch.impl.matcher.handlers.LiteralWithSubstitutionHandler import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler import com.intellij.util.containers.reverse import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassifierDescriptor import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.core.resolveType import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.intentions.calleeName import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveToDescriptors import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.structuralsearch.* import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinAlsoMatchCompanionObjectPredicate import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinAlsoMatchValVarPredicate import org.jetbrains.kotlin.kdoc.lexer.KDocTokens import org.jetbrains.kotlin.kdoc.psi.api.KDoc import org.jetbrains.kotlin.kdoc.psi.impl.KDocImpl import org.jetbrains.kotlin.kdoc.psi.impl.KDocLink import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType import org.jetbrains.kotlin.psi.psiUtil.referenceExpression import org.jetbrains.kotlin.psi2ir.deparenthesize import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.types.typeUtil.supertypes import org.jetbrains.kotlin.util.OperatorNameConventions class KotlinMatchingVisitor(private val myMatchingVisitor: GlobalMatchingVisitor) : SSRKtVisitor() { /** Gets the next element in the query tree and removes unnecessary parentheses. */ private inline fun <reified T> getTreeElementDepar(): T? = when (val element = myMatchingVisitor.element) { is KtParenthesizedExpression -> { val deparenthesized = element.deparenthesize() if (deparenthesized is T) deparenthesized else { myMatchingVisitor.result = false null } } else -> getTreeElement<T>() } /** Gets the next element in the tree */ private inline fun <reified T> getTreeElement(): T? = when (val element = myMatchingVisitor.element) { is T -> element else -> { myMatchingVisitor.result = false null } } private inline fun <reified T:KtElement> factory(context: PsiElement, f: KtPsiFactory.() -> T): T { val psiFactory = KtPsiFactory(context, true) val result = psiFactory.f() (result.containingFile as KtFile).analysisContext = context return result } private fun GlobalMatchingVisitor.matchSequentially(elements: List<PsiElement?>, elements2: List<PsiElement?>) = matchSequentially(elements.toTypedArray(), elements2.toTypedArray()) private fun GlobalMatchingVisitor.matchInAnyOrder(elements: List<PsiElement?>, elements2: List<PsiElement?>) = matchInAnyOrder(elements.toTypedArray(), elements2.toTypedArray()) private fun GlobalMatchingVisitor.matchNormalized( element: KtExpression?, element2: KtExpression?, returnExpr: Boolean = false ): Boolean { val (e1, e2) = if (element is KtBlockExpression && element2 is KtBlockExpression) element to element2 else normalizeExpressions(element, element2, returnExpr) val impossible = e1?.let { val handler = getHandler(it) e2 !is KtBlockExpression && handler is SubstitutionHandler && handler.minOccurs > 1 } ?: false return !impossible && match(e1, e2) } private fun getHandler(element: PsiElement) = myMatchingVisitor.matchContext.pattern.getHandler(element) private fun matchTextOrVariable(el1: PsiElement?, el2: PsiElement?): Boolean { if (el1 == null) return true if (el2 == null) return false return substituteOrMatchText(el1, el2) } private fun matchTextOrVariableEq(el1: PsiElement?, el2: PsiElement?): Boolean { if (el1 == null && el2 == null) return true if (el1 == null) return false if (el2 == null) return false return substituteOrMatchText(el1, el2) } private fun substituteOrMatchText(el1: PsiElement, el2: PsiElement): Boolean { return when (val handler = getHandler(el1)) { is SubstitutionHandler -> handler.validate(el2, myMatchingVisitor.matchContext) else -> myMatchingVisitor.matchText(el1, el2) } } override fun visitLeafPsiElement(leafPsiElement: LeafPsiElement) { val other = getTreeElementDepar<LeafPsiElement>() ?: return // Match element type if (!myMatchingVisitor.setResult(leafPsiElement.elementType == other.elementType)) return when (leafPsiElement.elementType) { KDocTokens.TEXT -> { myMatchingVisitor.result = when (val handler = leafPsiElement.getUserData(CompiledPattern.HANDLER_KEY)) { is LiteralWithSubstitutionHandler -> handler.match(leafPsiElement, other, myMatchingVisitor.matchContext) else -> substituteOrMatchText(leafPsiElement, other) } } KDocTokens.TAG_NAME, KtTokens.IDENTIFIER -> myMatchingVisitor.result = substituteOrMatchText(leafPsiElement, other) } } override fun visitArrayAccessExpression(expression: KtArrayAccessExpression) { val other = getTreeElementDepar<KtExpression>() ?: return myMatchingVisitor.result = when (other) { is KtArrayAccessExpression -> myMatchingVisitor.match(expression.arrayExpression, other.arrayExpression) && myMatchingVisitor.matchSons(expression.indicesNode, other.indicesNode) is KtDotQualifiedExpression -> myMatchingVisitor.match(expression.arrayExpression, other.receiverExpression) && other.calleeName == "${OperatorNameConventions.GET}" && myMatchingVisitor.matchSequentially( expression.indexExpressions, other.callExpression?.valueArguments?.map(KtValueArgument::getArgumentExpression)!! ) else -> false } } /** Matches binary expressions including translated operators. */ override fun visitBinaryExpression(expression: KtBinaryExpression) { fun KtBinaryExpression.match(other: KtBinaryExpression) = operationToken == other.operationToken && myMatchingVisitor.match(left, other.left) && myMatchingVisitor.match(right, other.right) fun KtQualifiedExpression.match(name: Name?, receiver: KtExpression?, callEntry: KtExpression?): Boolean { val callExpr = callExpression return callExpr is KtCallExpression && calleeName == "$name" && myMatchingVisitor.match(receiver, receiverExpression) && myMatchingVisitor.match(callEntry, callExpr.valueArguments.first().getArgumentExpression()) } fun KtBinaryExpression.matchEq(other: KtBinaryExpression): Boolean { val otherLeft = other.left?.deparenthesize() val otherRight = other.right?.deparenthesize() return otherLeft is KtSafeQualifiedExpression && otherLeft.match(OperatorNameConventions.EQUALS, left, right) && other.operationToken == KtTokens.ELVIS && otherRight is KtBinaryExpression && myMatchingVisitor.match(right, otherRight.left) && otherRight.operationToken == KtTokens.EQEQEQ && myMatchingVisitor.match(factory(other) {createExpression("null")}, otherRight.right) } val other = getTreeElementDepar<KtExpression>() ?: return when (other) { is KtBinaryExpression -> { if (expression.operationToken == KtTokens.IDENTIFIER) { myMatchingVisitor.result = myMatchingVisitor.match(expression.left, other.left) && myMatchingVisitor.match(expression.right, other.right) && myMatchingVisitor.match(expression.operationReference, other.operationReference) return } if (myMatchingVisitor.setResult(expression.match(other))) return when (expression.operationToken) { // semantical matching KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ -> { // a.compareTo(b) OP 0 val left = other.left?.deparenthesize() myMatchingVisitor.result = left is KtDotQualifiedExpression && left.match(OperatorNameConventions.COMPARE_TO, expression.left, expression.right) && expression.operationToken == other.operationToken && myMatchingVisitor.match(other.right, factory(other) {createExpression("0")}) } in augmentedAssignmentsMap.keys -> { // x OP= y with x = x OP y if (other.operationToken == KtTokens.EQ) { val right = other.right?.deparenthesize() val left = other.left?.deparenthesize() myMatchingVisitor.result = right is KtBinaryExpression && augmentedAssignmentsMap[expression.operationToken] == right.operationToken && myMatchingVisitor.match(expression.left, left) && myMatchingVisitor.match(expression.left, right.left) && myMatchingVisitor.match(expression.right, right.right) } } KtTokens.EQ -> { // x = x OP y with x OP= y val right = expression.right?.deparenthesize() if (right is KtBinaryExpression && right.operationToken == augmentedAssignmentsMap[other.operationToken]) { myMatchingVisitor.result = myMatchingVisitor.match(expression.left, other.left) && myMatchingVisitor.match(right.left, other.left) && myMatchingVisitor.match(right.right, other.right) } } KtTokens.EQEQ -> { // a?.equals(b) ?: (b === null) myMatchingVisitor.result = expression.matchEq(other) } } } is KtDotQualifiedExpression -> { // translated matching val token = expression.operationToken val left = expression.left val right = expression.right when { token == KtTokens.IN_KEYWORD -> { // b.contains(a) val parent = other.parent val isNotNegated = if (parent is KtPrefixExpression) parent.operationToken != KtTokens.EXCL else true myMatchingVisitor.result = isNotNegated && other.match(OperatorNameConventions.CONTAINS, right, left) } token == KtTokens.NOT_IN -> myMatchingVisitor.result = false // already matches with prefix expression token == KtTokens.EQ && left is KtArrayAccessExpression -> { // a[x] = expression val matchedArgs = left.indexExpressions.apply { add(right) } myMatchingVisitor.result = myMatchingVisitor.match(left.arrayExpression, other.receiverExpression) && other.calleeName == "${OperatorNameConventions.SET}" && myMatchingVisitor.matchSequentially( matchedArgs, other.callExpression?.valueArguments?.map(KtValueArgument::getArgumentExpression)!! ) } else -> { // a.plus(b) all arithmetic operators val selector = other.selectorExpression if (expression.operationToken == KtTokens.EQ && right is KtBinaryExpression) { // Matching x = x + y with x.plusAssign(y) val opName = augmentedAssignmentsMap.reverse()[right.operationToken]?.binaryExprOpName() myMatchingVisitor.result = selector is KtCallExpression && myMatchingVisitor.match(left, other.receiverExpression) && other.match(opName, right.left, right.right) } else { myMatchingVisitor.result = selector is KtCallExpression && other.match( expression.operationToken.binaryExprOpName(), left, right ) } } } } is KtPrefixExpression -> { // translated matching val baseExpr = other.baseExpression?.deparenthesize() when (expression.operationToken) { KtTokens.NOT_IN -> { // !b.contains(a) myMatchingVisitor.result = other.operationToken == KtTokens.EXCL && baseExpr is KtDotQualifiedExpression && baseExpr.match(OperatorNameConventions.CONTAINS, expression.right, expression.left) } KtTokens.EXCLEQ -> { // !(a?.equals(b) ?: (b === null)) myMatchingVisitor.result = other.operationToken == KtTokens.EXCL && baseExpr is KtBinaryExpression && expression.matchEq(baseExpr) } } } else -> myMatchingVisitor.result = false } } override fun visitBlockExpression(expression: KtBlockExpression) { val other = getTreeElementDepar<KtBlockExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSequentially(expression.statements, other.statements) } override fun visitUnaryExpression(expression: KtUnaryExpression) { val other = getTreeElementDepar<KtExpression>() ?: return myMatchingVisitor.result = when (other) { is KtDotQualifiedExpression -> { myMatchingVisitor.match(expression.baseExpression, other.receiverExpression) && OperatorConventions.UNARY_OPERATION_NAMES[expression.operationToken].toString() == other.calleeName } is KtUnaryExpression -> myMatchingVisitor.match(expression.baseExpression, other.baseExpression) && myMatchingVisitor.match(expression.operationReference, other.operationReference) else -> false } } override fun visitParenthesizedExpression(expression: KtParenthesizedExpression) { fun KtExpression.countParenthesize(initial: Int = 0): Int { val parentheses = children.firstOrNull { it is KtParenthesizedExpression } as KtExpression? return parentheses?.countParenthesize(initial + 1) ?: initial } val other = getTreeElement<KtParenthesizedExpression>() ?: return if (!myMatchingVisitor.setResult(expression.countParenthesize() == other.countParenthesize())) return myMatchingVisitor.result = myMatchingVisitor.match(expression.deparenthesize(), other.deparenthesize()) } override fun visitConstantExpression(expression: KtConstantExpression) { val other = getTreeElementDepar<KtExpression>() ?: return myMatchingVisitor.result = substituteOrMatchText(expression, other) } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val other = getTreeElementDepar<PsiElement>() ?: return val exprHandler = getHandler(expression) if (other is KtReferenceExpression && exprHandler is SubstitutionHandler) { val ref = other.mainReference val bindingContext = ref.element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) val referenced = ref.resolveToDescriptors(bindingContext).firstOrNull()?.let { if (it is ConstructorDescriptor) it.constructedClass else it } if (referenced is ClassifierDescriptor) { val fqName = referenced.fqNameOrNull() val predicate = exprHandler.findRegExpPredicate() if (predicate != null && fqName != null && predicate.doMatch(fqName.asString(), myMatchingVisitor.matchContext, other)) { myMatchingVisitor.result = true exprHandler.addResult(other, myMatchingVisitor.matchContext) return } } } // Match Int::class with X.Int::class val skipReceiver = other.parent is KtDoubleColonExpression && other is KtDotQualifiedExpression && myMatchingVisitor.match(expression, other.selectorExpression) myMatchingVisitor.result = skipReceiver || substituteOrMatchText( expression.getReferencedNameElement(), if (other is KtSimpleNameExpression) other.getReferencedNameElement() else other ) val handler = getHandler(expression.getReferencedNameElement()) if (myMatchingVisitor.result && handler is SubstitutionHandler) { myMatchingVisitor.result = handler.handle( if (other is KtSimpleNameExpression) other.getReferencedNameElement() else other, myMatchingVisitor.matchContext ) } } override fun visitContinueExpression(expression: KtContinueExpression) { val other = getTreeElementDepar<KtContinueExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel()) } override fun visitBreakExpression(expression: KtBreakExpression) { val other = getTreeElementDepar<KtBreakExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel()) } override fun visitThisExpression(expression: KtThisExpression) { val other = getTreeElementDepar<KtThisExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel()) } override fun visitSuperExpression(expression: KtSuperExpression) { val other = getTreeElementDepar<KtSuperExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel()) && myMatchingVisitor.match(expression.superTypeQualifier, other.superTypeQualifier) } override fun visitReturnExpression(expression: KtReturnExpression) { val other = getTreeElementDepar<KtReturnExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel()) && myMatchingVisitor.match(expression.returnedExpression, other.returnedExpression) } override fun visitFunctionType(type: KtFunctionType) { val other = getTreeElementDepar<KtFunctionType>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(type.receiverTypeReference, other.receiverTypeReference) && myMatchingVisitor.match(type.parameterList, other.parameterList) && myMatchingVisitor.match(type.returnTypeReference, other.returnTypeReference) } override fun visitUserType(type: KtUserType) { val other = myMatchingVisitor.element myMatchingVisitor.result = when (other) { is KtUserType -> { type.qualifier?.let { typeQualifier -> // if query has fq type myMatchingVisitor.match(typeQualifier, other.qualifier) // recursively match qualifiers && myMatchingVisitor.match(type.referenceExpression, other.referenceExpression) && myMatchingVisitor.match(type.typeArgumentList, other.typeArgumentList) } ?: let { // no fq type myMatchingVisitor.match(type.referenceExpression, other.referenceExpression) && myMatchingVisitor.match(type.typeArgumentList, other.typeArgumentList) } } is KtTypeElement -> matchTextOrVariable(type.referenceExpression, other) else -> false } } override fun visitNullableType(nullableType: KtNullableType) { val other = getTreeElementDepar<KtNullableType>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(nullableType.innerType, other.innerType) } override fun visitDynamicType(type: KtDynamicType) { myMatchingVisitor.result = myMatchingVisitor.element is KtDynamicType } override fun visitTypeReference(typeReference: KtTypeReference) { val other = getTreeElementDepar<KtTypeReference>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSons(typeReference, other) } override fun visitQualifiedExpression(expression: KtQualifiedExpression) { val other = getTreeElementDepar<KtQualifiedExpression>() ?: return myMatchingVisitor.result = expression.operationSign == other.operationSign && myMatchingVisitor.match(expression.receiverExpression, other.receiverExpression) && myMatchingVisitor.match(expression.selectorExpression, other.selectorExpression) } override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) { val other = getTreeElementDepar<KtExpression>() ?: return val receiverHandler = getHandler(expression.receiverExpression) if (receiverHandler is SubstitutionHandler && receiverHandler.minOccurs == 0) { // can match without receiver myMatchingVisitor.result = other !is KtDotQualifiedExpression && other.parent !is KtDotQualifiedExpression && other.parent !is KtCallExpression && myMatchingVisitor.match(expression.selectorExpression, other) } else { myMatchingVisitor.result = other is KtDotQualifiedExpression && myMatchingVisitor.match(expression.receiverExpression, other.receiverExpression) && myMatchingVisitor.match(expression.selectorExpression, other.selectorExpression) } } override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) { val other = getTreeElementDepar<KtLambdaExpression>() ?: return val lambdaVP = lambdaExpression.valueParameters val otherVP = other.valueParameters myMatchingVisitor.result = (!lambdaExpression.functionLiteral.hasParameterSpecification() || myMatchingVisitor.matchSequentially(lambdaVP, otherVP) || lambdaVP.map { p -> getHandler(p).let { if (it is SubstitutionHandler) it.minOccurs else 1 } }.sum() == 1 && !other.functionLiteral.hasParameterSpecification() && (other.functionLiteral.descriptor as AnonymousFunctionDescriptor).valueParameters.size == 1) && myMatchingVisitor.match(lambdaExpression.bodyExpression, other.bodyExpression) } override fun visitTypeProjection(typeProjection: KtTypeProjection) { val other = getTreeElementDepar<KtTypeProjection>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(typeProjection.typeReference, other.typeReference) && myMatchingVisitor.match(typeProjection.modifierList, other.modifierList) && typeProjection.projectionKind == other.projectionKind } override fun visitTypeArgumentList(typeArgumentList: KtTypeArgumentList) { val other = getTreeElementDepar<KtTypeArgumentList>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSequentially(typeArgumentList.arguments, other.arguments) } override fun visitArgument(argument: KtValueArgument) { val other = getTreeElementDepar<KtValueArgument>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(argument.getArgumentExpression(), other.getArgumentExpression()) && (!argument.isNamed() || !other.isNamed() || matchTextOrVariable( argument.getArgumentName(), other.getArgumentName() )) } private fun MutableList<KtValueArgument>.addDefaultArguments(parameters: List<KtParameter?>) { if (parameters.isEmpty()) return val params = parameters.toTypedArray() var i = 0 while (i < size) { val arg = get(i) if (arg.isNamed()) { params[parameters.indexOfFirst { it?.nameAsName == arg.getArgumentName()?.asName }] = null i++ } else { val curParam = params[i] ?: throw IllegalStateException( KotlinBundle.message("error.param.can.t.be.null.at.index.0.in.1", i, params.map { it?.text }) ) params[i] = null if (curParam.isVarArg) { val varArgType = arg.getArgumentExpression()?.resolveType() var curArg: KtValueArgument? = arg while (varArgType != null && varArgType == curArg?.getArgumentExpression()?.resolveType() || curArg?.isSpread == true) { i++ curArg = getOrNull(i) } } else i++ } } params.filterNotNull().forEach { add(factory(myMatchingVisitor.element) {createArgument(it.defaultValue, it.nameAsName, reformat = false) }) } } private fun matchValueArguments( parameters: List<KtParameter>, valueArgList: KtValueArgumentList?, otherValueArgList: KtValueArgumentList?, lambdaArgList: List<KtLambdaArgument>, otherLambdaArgList: List<KtLambdaArgument> ): Boolean { if (valueArgList != null) { val handler = getHandler(valueArgList) val normalizedOtherArgs = otherValueArgList?.arguments?.toMutableList() ?: mutableListOf() normalizedOtherArgs.addAll(otherLambdaArgList) normalizedOtherArgs.addDefaultArguments(parameters) if (normalizedOtherArgs.isEmpty() && handler is SubstitutionHandler && handler.minOccurs == 0) { return myMatchingVisitor.matchSequentially(lambdaArgList, otherLambdaArgList) } val normalizedArgs = valueArgList.arguments.toMutableList() normalizedArgs.addAll(lambdaArgList) return matchValueArguments(normalizedArgs, normalizedOtherArgs) } return matchValueArguments(lambdaArgList, otherLambdaArgList) } private fun matchValueArguments(queryArgs: List<KtValueArgument>, codeArgs: List<KtValueArgument>): Boolean { var queryIndex = 0 var codeIndex = 0 while (queryIndex < queryArgs.size) { val queryArg = queryArgs[queryIndex] val codeArg = codeArgs.getOrElse(codeIndex) { return@matchValueArguments false } if (getHandler(queryArg) is SubstitutionHandler) { return myMatchingVisitor.matchSequentially( queryArgs.subList(queryIndex, queryArgs.lastIndex + 1), codeArgs.subList(codeIndex, codeArgs.lastIndex + 1) ) } // varargs declared in call matching with one-to-one argument passing if (queryArg.isSpread && !codeArg.isSpread) { val spreadArgExpr = queryArg.getArgumentExpression() if (spreadArgExpr is KtCallExpression) { spreadArgExpr.valueArguments.forEach { spreadedArg -> if (!myMatchingVisitor.match(spreadedArg, codeArgs[codeIndex++])) return@matchValueArguments false } queryIndex++ continue } // can't match array that is not created in the call itself myMatchingVisitor.result = false return myMatchingVisitor.result } if (!queryArg.isSpread && codeArg.isSpread) { val spreadArgExpr = codeArg.getArgumentExpression() if (spreadArgExpr is KtCallExpression) { spreadArgExpr.valueArguments.forEach { spreadedArg -> if (!myMatchingVisitor.match(queryArgs[queryIndex++], spreadedArg)) return@matchValueArguments false } codeIndex++ continue } return false// can't match array that is not created in the call itself } // normal argument matching if (!myMatchingVisitor.match(queryArg, codeArg)) { return if (queryArg.isNamed() || codeArg.isNamed()) { // start comparing for out of order arguments myMatchingVisitor.matchInAnyOrder( queryArgs.subList(queryIndex, queryArgs.lastIndex + 1), codeArgs.subList(codeIndex, codeArgs.lastIndex + 1) ) } else false } queryIndex++ codeIndex++ } if (codeIndex != codeArgs.size) return false return true } private fun resolveParameters(other: KtElement): List<KtParameter> { return other.resolveToCall()?.candidateDescriptor?.original?.valueParameters?.mapNotNull { it.source.getPsi() as? KtParameter } ?: emptyList() } override fun visitCallExpression(expression: KtCallExpression) { val other = getTreeElementDepar<KtExpression>() ?: return val parameters = resolveParameters(other) myMatchingVisitor.result = when (other) { is KtCallExpression -> { myMatchingVisitor.match(expression.calleeExpression, other.calleeExpression) && myMatchingVisitor.match(expression.typeArgumentList, other.typeArgumentList) && matchValueArguments( parameters, expression.valueArgumentList, other.valueArgumentList, expression.lambdaArguments, other.lambdaArguments ) } is KtDotQualifiedExpression -> other.callExpression is KtCallExpression && myMatchingVisitor.match(expression.calleeExpression, other.receiverExpression) && other.calleeName == "${OperatorNameConventions.INVOKE}" && matchValueArguments( parameters, expression.valueArgumentList, other.callExpression?.valueArgumentList, expression.lambdaArguments, other.callExpression?.lambdaArguments ?: emptyList() ) else -> false } } override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) { val other = getTreeElementDepar<KtCallableReferenceExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.callableReference, other.callableReference) && myMatchingVisitor.matchOptionally(expression.receiverExpression, other.receiverExpression) } override fun visitTypeParameter(parameter: KtTypeParameter) { val other = getTreeElementDepar<KtTypeParameter>() ?: return myMatchingVisitor.result = substituteOrMatchText(parameter.firstChild, other.firstChild) // match generic identifier && myMatchingVisitor.match(parameter.extendsBound, other.extendsBound) && parameter.variance == other.variance parameter.nameIdentifier?.let { nameIdentifier -> val handler = getHandler(nameIdentifier) if (myMatchingVisitor.result && handler is SubstitutionHandler) { handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext) } } } override fun visitParameter(parameter: KtParameter) { val other = getTreeElementDepar<KtParameter>() ?: return val otherNameIdentifier = if (getHandler(parameter) is SubstitutionHandler && parameter.nameIdentifier != null && other.nameIdentifier == null ) other else other.nameIdentifier myMatchingVisitor.result = myMatchingVisitor.match(parameter.typeReference, other.typeReference) && myMatchingVisitor.match(parameter.defaultValue, other.defaultValue) && (parameter.isVarArg == other.isVarArg || getHandler(parameter) is SubstitutionHandler) && myMatchingVisitor.match(parameter.valOrVarKeyword, other.valOrVarKeyword) && (parameter.nameIdentifier == null || matchTextOrVariable(parameter.nameIdentifier, otherNameIdentifier)) && myMatchingVisitor.match(parameter.modifierList, other.modifierList) && myMatchingVisitor.match(parameter.destructuringDeclaration, other.destructuringDeclaration) parameter.nameIdentifier?.let { nameIdentifier -> val handler = getHandler(nameIdentifier) if (myMatchingVisitor.result && handler is SubstitutionHandler) { handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext) } } } override fun visitTypeParameterList(list: KtTypeParameterList) { val other = getTreeElementDepar<KtTypeParameterList>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSequentially(list.parameters, other.parameters) } override fun visitParameterList(list: KtParameterList) { val other = getTreeElementDepar<KtParameterList>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSequentially(list.parameters, other.parameters) } override fun visitConstructorDelegationCall(call: KtConstructorDelegationCall) { val other = getTreeElementDepar<KtConstructorDelegationCall>() ?: return val parameters = resolveParameters(other) myMatchingVisitor.result = myMatchingVisitor.match(call.calleeExpression, other.calleeExpression) && myMatchingVisitor.match(call.typeArgumentList, other.typeArgumentList) && matchValueArguments( parameters, call.valueArgumentList, other.valueArgumentList, call.lambdaArguments, other.lambdaArguments ) } override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) { val other = getTreeElementDepar<KtSecondaryConstructor>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(constructor.modifierList, other.modifierList) && myMatchingVisitor.match(constructor.typeParameterList, other.typeParameterList) && myMatchingVisitor.match(constructor.valueParameterList, other.valueParameterList) && myMatchingVisitor.match(constructor.getDelegationCallOrNull(), other.getDelegationCallOrNull()) && myMatchingVisitor.match(constructor.bodyExpression, other.bodyExpression) } override fun visitPrimaryConstructor(constructor: KtPrimaryConstructor) { val other = getTreeElementDepar<KtPrimaryConstructor>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(constructor.modifierList, other.modifierList) && myMatchingVisitor.match(constructor.typeParameterList, other.typeParameterList) && myMatchingVisitor.match(constructor.valueParameterList, other.valueParameterList) } override fun visitAnonymousInitializer(initializer: KtAnonymousInitializer) { val other = getTreeElementDepar<KtAnonymousInitializer>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(initializer.body, other.body) } override fun visitClassBody(classBody: KtClassBody) { val other = getTreeElementDepar<KtClassBody>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSonsInAnyOrder(classBody, other) } override fun visitSuperTypeCallEntry(call: KtSuperTypeCallEntry) { val other = getTreeElementDepar<KtSuperTypeCallEntry>() ?: return val parameters = resolveParameters(other) myMatchingVisitor.result = myMatchingVisitor.match(call.calleeExpression, other.calleeExpression) && myMatchingVisitor.match(call.typeArgumentList, other.typeArgumentList) && matchValueArguments( parameters, call.valueArgumentList, other.valueArgumentList, call.lambdaArguments, other.lambdaArguments ) } override fun visitSuperTypeEntry(specifier: KtSuperTypeEntry) { val other = getTreeElementDepar<KtSuperTypeEntry>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(specifier.typeReference, other.typeReference) } private fun matchTypeAgainstElement( type: String, element: PsiElement, other: PsiElement ): Boolean { return when (val predicate = (getHandler(element) as? SubstitutionHandler)?.findRegExpPredicate()) { null -> element.text == type // Ignore type parameters if absent from the pattern || !element.text.contains('<') && element.text == type.removeTypeParameters() else -> predicate.doMatch(type, myMatchingVisitor.matchContext, other) } } override fun visitSuperTypeList(list: KtSuperTypeList) { val other = getTreeElementDepar<KtSuperTypeList>() ?: return val withinHierarchyEntries = list.entries.filter { val type = it.typeReference; type is KtTypeReference && getHandler(type).withinHierarchyTextFilterSet } (other.parent as? KtClassOrObject)?.let { klass -> val supertypes = (klass.descriptor as ClassDescriptor).toSimpleType().supertypes() withinHierarchyEntries.forEach { entry -> val typeReference = entry.typeReference if (!matchTextOrVariable(typeReference, klass.nameIdentifier) && typeReference != null && supertypes.none { it.renderNames().any { type -> matchTypeAgainstElement(type, typeReference, other) } }) { myMatchingVisitor.result = false return@visitSuperTypeList } } } myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder(list.entries.filter { it !in withinHierarchyEntries }, other.entries) } override fun visitClass(klass: KtClass) { val other = getTreeElementDepar<KtClass>() ?: return val otherDescriptor = other.descriptor ?: return val identifier = klass.nameIdentifier val otherIdentifier = other.nameIdentifier var matchNameIdentifiers = matchTextOrVariable(identifier, otherIdentifier) || identifier != null && otherIdentifier != null && matchTypeAgainstElement( (otherDescriptor as LazyClassDescriptor).defaultType.fqName.toString(), identifier, otherIdentifier ) // Possible match if "within hierarchy" is set if (!matchNameIdentifiers && identifier != null && otherIdentifier != null) { val identifierHandler = getHandler(identifier) val checkHierarchyDown = identifierHandler.withinHierarchyTextFilterSet if (checkHierarchyDown) { // Check hierarchy down (down of pattern element = supertypes of code element) matchNameIdentifiers = (otherDescriptor as ClassDescriptor).toSimpleType().supertypes().any { type -> type.renderNames().any { renderedType -> matchTypeAgainstElement(renderedType, identifier, otherIdentifier) } } } else if (identifier.getUserData(KotlinCompilingVisitor.WITHIN_HIERARCHY) == true) { // Check hierarchy up (up of pattern element = inheritors of code element) matchNameIdentifiers = HierarchySearchRequest( other, GlobalSearchScope.allScope(other.project), true ).searchInheritors().any { psiClass -> arrayOf(psiClass.name, psiClass.qualifiedName).filterNotNull().any { renderedType -> matchTypeAgainstElement(renderedType, identifier, otherIdentifier) } } } } myMatchingVisitor.result = myMatchingVisitor.match(klass.getClassOrInterfaceKeyword(), other.getClassOrInterfaceKeyword()) && myMatchingVisitor.match(klass.modifierList, other.modifierList) && matchNameIdentifiers && myMatchingVisitor.match(klass.typeParameterList, other.typeParameterList) && myMatchingVisitor.match(klass.primaryConstructor, other.primaryConstructor) && myMatchingVisitor.matchInAnyOrder(klass.secondaryConstructors, other.secondaryConstructors) && myMatchingVisitor.match(klass.getSuperTypeList(), other.getSuperTypeList()) && myMatchingVisitor.match(klass.body, other.body) && myMatchingVisitor.match(klass.docComment, other.docComment) val handler = getHandler(klass.nameIdentifier!!) if (myMatchingVisitor.result && handler is SubstitutionHandler) { handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext) } } override fun visitObjectLiteralExpression(expression: KtObjectLiteralExpression) { val other = getTreeElementDepar<KtObjectLiteralExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.objectDeclaration, other.objectDeclaration) } override fun visitObjectDeclaration(declaration: KtObjectDeclaration) { val other = getTreeElementDepar<KtObjectDeclaration>() ?: return val inferredNameIdentifier = declaration.nameIdentifier ?: if (declaration.isCompanion()) (declaration.parent.parent as KtClass).nameIdentifier else null val handler = inferredNameIdentifier?.let { getHandler(inferredNameIdentifier) } val matchIdentifier = if (handler is SubstitutionHandler && handler.maxOccurs > 0 && handler.minOccurs == 0) { true // match count filter with companion object without identifier } else matchTextOrVariableEq(declaration.nameIdentifier, other.nameIdentifier) myMatchingVisitor.result = (declaration.isCompanion() == other.isCompanion() || (handler is SubstitutionHandler && handler.predicate is KotlinAlsoMatchCompanionObjectPredicate)) && myMatchingVisitor.match(declaration.modifierList, other.modifierList) && matchIdentifier && myMatchingVisitor.match(declaration.getSuperTypeList(), other.getSuperTypeList()) && myMatchingVisitor.match(declaration.body, other.body) if (myMatchingVisitor.result && handler is SubstitutionHandler) { handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext) } } private fun normalizeExpressionRet(expression: KtExpression?): KtExpression? = when { expression is KtBlockExpression && expression.statements.size == 1 -> expression.firstStatement?.let { if (it is KtReturnExpression) it.returnedExpression else it } else -> expression } private fun normalizeExpression(expression: KtExpression?): KtExpression? = when { expression is KtBlockExpression && expression.statements.size == 1 -> expression.firstStatement else -> expression } private fun normalizeExpressions( patternExpr: KtExpression?, codeExpr: KtExpression?, returnExpr: Boolean ): Pair<KtExpression?, KtExpression?> { val normalizedExpr = if (returnExpr) normalizeExpressionRet(patternExpr) else normalizeExpression(patternExpr) val normalizedCodeExpr = if (returnExpr) normalizeExpressionRet(codeExpr) else normalizeExpression(codeExpr) return when { normalizedExpr is KtBlockExpression || normalizedCodeExpr is KtBlockExpression -> patternExpr to codeExpr else -> normalizedExpr to normalizedCodeExpr } } override fun visitNamedFunction(function: KtNamedFunction) { val other = getTreeElementDepar<KtNamedFunction>() ?: return val (patternBody, codeBody) = normalizeExpressions(function.bodyBlockExpression, other.bodyBlockExpression, true) val bodyHandler = patternBody?.let(::getHandler) val bodyMatch = when { patternBody is KtNameReferenceExpression && codeBody == null -> bodyHandler is SubstitutionHandler && bodyHandler.minOccurs <= 1 && bodyHandler.maxOccurs >= 1 && myMatchingVisitor.match(patternBody, other.bodyExpression) patternBody is KtNameReferenceExpression -> myMatchingVisitor.match( function.bodyBlockExpression, other.bodyBlockExpression ) patternBody == null && codeBody == null -> myMatchingVisitor.match(function.bodyExpression, other.bodyExpression) patternBody == null -> function.bodyExpression == null || codeBody !is KtBlockExpression && myMatchingVisitor.match(function.bodyExpression, codeBody) codeBody == null -> patternBody !is KtBlockExpression && myMatchingVisitor.match(patternBody, other.bodyExpression) else -> myMatchingVisitor.match(function.bodyBlockExpression, other.bodyBlockExpression) } myMatchingVisitor.result = myMatchingVisitor.match(function.modifierList, other.modifierList) && matchTextOrVariable(function.nameIdentifier, other.nameIdentifier) && myMatchingVisitor.match(function.typeParameterList, other.typeParameterList) && myMatchingVisitor.match(function.typeReference, other.typeReference) && myMatchingVisitor.match(function.valueParameterList, other.valueParameterList) && myMatchingVisitor.match(function.receiverTypeReference, other.receiverTypeReference) && bodyMatch function.nameIdentifier?.let { nameIdentifier -> val handler = getHandler(nameIdentifier) if (myMatchingVisitor.result && handler is SubstitutionHandler) { handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext) } } } override fun visitModifierList(list: KtModifierList) { val other = getTreeElementDepar<KtModifierList>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSonsInAnyOrder(list, other) } override fun visitIfExpression(expression: KtIfExpression) { val other = getTreeElementDepar<KtIfExpression>() ?: return val elseBranch = normalizeExpression(expression.`else`) myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition) && myMatchingVisitor.matchNormalized(expression.then, other.then) && (elseBranch == null || myMatchingVisitor.matchNormalized(expression.`else`, other.`else`)) } override fun visitForExpression(expression: KtForExpression) { val other = getTreeElementDepar<KtForExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.loopParameter, other.loopParameter) && myMatchingVisitor.match(expression.loopRange, other.loopRange) && myMatchingVisitor.matchNormalized(expression.body, other.body) } override fun visitWhileExpression(expression: KtWhileExpression) { val other = getTreeElementDepar<KtWhileExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition) && myMatchingVisitor.matchNormalized(expression.body, other.body) } override fun visitDoWhileExpression(expression: KtDoWhileExpression) { val other = getTreeElementDepar<KtDoWhileExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition) && myMatchingVisitor.matchNormalized(expression.body, other.body) } override fun visitWhenConditionInRange(condition: KtWhenConditionInRange) { val other = getTreeElementDepar<KtWhenConditionInRange>() ?: return myMatchingVisitor.result = condition.isNegated == other.isNegated && myMatchingVisitor.match(condition.rangeExpression, other.rangeExpression) } override fun visitWhenConditionIsPattern(condition: KtWhenConditionIsPattern) { val other = getTreeElementDepar<KtWhenConditionIsPattern>() ?: return myMatchingVisitor.result = condition.isNegated == other.isNegated && myMatchingVisitor.match(condition.typeReference, other.typeReference) } override fun visitWhenConditionWithExpression(condition: KtWhenConditionWithExpression) { val other = getTreeElementDepar<PsiElement>() ?: return val handler = getHandler(condition) if (handler is SubstitutionHandler) { myMatchingVisitor.result = handler.handle(other, myMatchingVisitor.matchContext) } else { myMatchingVisitor.result = other is KtWhenConditionWithExpression && myMatchingVisitor.match(condition.expression, other.expression) } } override fun visitWhenEntry(ktWhenEntry: KtWhenEntry) { val other = getTreeElementDepar<KtWhenEntry>() ?: return // $x$ -> $y$ should match else branches val bypassElseTest = ktWhenEntry.firstChild is KtWhenConditionWithExpression && ktWhenEntry.firstChild.children.size == 1 && ktWhenEntry.firstChild.firstChild is KtNameReferenceExpression myMatchingVisitor.result = (bypassElseTest && other.isElse || myMatchingVisitor.matchInAnyOrder(ktWhenEntry.conditions, other.conditions)) && myMatchingVisitor.match(ktWhenEntry.expression, other.expression) && (bypassElseTest || ktWhenEntry.isElse == other.isElse) } override fun visitWhenExpression(expression: KtWhenExpression) { val other = getTreeElementDepar<KtWhenExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.subjectExpression, other.subjectExpression) && myMatchingVisitor.matchInAnyOrder(expression.entries, other.entries) } override fun visitFinallySection(finallySection: KtFinallySection) { val other = getTreeElementDepar<KtFinallySection>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(finallySection.finalExpression, other.finalExpression) } override fun visitCatchSection(catchClause: KtCatchClause) { val other = getTreeElementDepar<KtCatchClause>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(catchClause.parameterList, other.parameterList) && myMatchingVisitor.match(catchClause.catchBody, other.catchBody) } override fun visitTryExpression(expression: KtTryExpression) { val other = getTreeElementDepar<KtTryExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.tryBlock, other.tryBlock) && myMatchingVisitor.matchInAnyOrder(expression.catchClauses, other.catchClauses) && myMatchingVisitor.match(expression.finallyBlock, other.finallyBlock) } override fun visitTypeAlias(typeAlias: KtTypeAlias) { val other = getTreeElementDepar<KtTypeAlias>() ?: return myMatchingVisitor.result = matchTextOrVariable(typeAlias.nameIdentifier, other.nameIdentifier) && myMatchingVisitor.match(typeAlias.getTypeReference(), other.getTypeReference()) && myMatchingVisitor.matchInAnyOrder(typeAlias.annotationEntries, other.annotationEntries) val handler = getHandler(typeAlias.nameIdentifier!!) if (myMatchingVisitor.result && handler is SubstitutionHandler) { handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext) } } override fun visitConstructorCalleeExpression(constructorCalleeExpression: KtConstructorCalleeExpression) { val other = getTreeElementDepar<KtConstructorCalleeExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match( constructorCalleeExpression.constructorReferenceExpression, other.constructorReferenceExpression ) } override fun visitAnnotationEntry(annotationEntry: KtAnnotationEntry) { val other = getTreeElementDepar<KtAnnotationEntry>() ?: return val parameters = resolveParameters(other) myMatchingVisitor.result = myMatchingVisitor.match(annotationEntry.calleeExpression, other.calleeExpression) && myMatchingVisitor.match(annotationEntry.typeArgumentList, other.typeArgumentList) && matchValueArguments( parameters, annotationEntry.valueArgumentList, other.valueArgumentList, annotationEntry.lambdaArguments, other.lambdaArguments ) && matchTextOrVariable(annotationEntry.useSiteTarget, other.useSiteTarget) } override fun visitAnnotatedExpression(expression: KtAnnotatedExpression) { myMatchingVisitor.result = when (val other = myMatchingVisitor.element) { is KtAnnotatedExpression -> myMatchingVisitor.match(expression.baseExpression, other.baseExpression) && myMatchingVisitor.matchInAnyOrder(expression.annotationEntries, other.annotationEntries) else -> myMatchingVisitor.match(expression.baseExpression, other) && expression.annotationEntries.all { val handler = getHandler(it); handler is SubstitutionHandler && handler.minOccurs == 0 } } } override fun visitProperty(property: KtProperty) { val other = getTreeElementDepar<KtProperty>() ?: return val handler = getHandler(property.nameIdentifier!!) myMatchingVisitor.result = ( property.isVar == other.isVar || (handler is SubstitutionHandler && handler.predicate is KotlinAlsoMatchValVarPredicate) ) && myMatchingVisitor.match(property.typeReference, other.typeReference) && myMatchingVisitor.match(property.modifierList, other.modifierList) && matchTextOrVariable(property.nameIdentifier, other.nameIdentifier) && myMatchingVisitor.match(property.docComment, other.docComment) && myMatchingVisitor.matchOptionally(property.delegateExpressionOrInitializer, other.delegateExpressionOrInitializer) && myMatchingVisitor.match(property.getter, other.getter) && myMatchingVisitor.match(property.setter, other.setter) && myMatchingVisitor.match(property.receiverTypeReference, other.receiverTypeReference) if (myMatchingVisitor.result && handler is SubstitutionHandler) { handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext) } } override fun visitPropertyAccessor(accessor: KtPropertyAccessor) { val other = getTreeElementDepar<KtPropertyAccessor>() ?: return val accessorBody = if (accessor.hasBlockBody()) accessor.bodyBlockExpression else accessor.bodyExpression val otherBody = if (other.hasBlockBody()) other.bodyBlockExpression else other.bodyExpression myMatchingVisitor.result = myMatchingVisitor.match(accessor.modifierList, other.modifierList) && myMatchingVisitor.matchNormalized(accessorBody, otherBody, true) } override fun visitStringTemplateExpression(expression: KtStringTemplateExpression) { val other = getTreeElementDepar<KtStringTemplateExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSequentially(expression.entries, other.entries) } override fun visitSimpleNameStringTemplateEntry(entry: KtSimpleNameStringTemplateEntry) { val other = getTreeElement<KtStringTemplateEntry>() ?: return val handler = getHandler(entry) if (handler is SubstitutionHandler) { myMatchingVisitor.result = handler.handle(other, myMatchingVisitor.matchContext) return } myMatchingVisitor.result = when (other) { is KtSimpleNameStringTemplateEntry, is KtBlockStringTemplateEntry -> myMatchingVisitor.match(entry.expression, other.expression) else -> false } } override fun visitLiteralStringTemplateEntry(entry: KtLiteralStringTemplateEntry) { val other = myMatchingVisitor.element myMatchingVisitor.result = when (val handler = entry.getUserData(CompiledPattern.HANDLER_KEY)) { is LiteralWithSubstitutionHandler -> handler.match(entry, other, myMatchingVisitor.matchContext) else -> substituteOrMatchText(entry, other) } } override fun visitBlockStringTemplateEntry(entry: KtBlockStringTemplateEntry) { val other = getTreeElementDepar<KtBlockStringTemplateEntry>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(entry.expression, other.expression) } override fun visitEscapeStringTemplateEntry(entry: KtEscapeStringTemplateEntry) { val other = getTreeElementDepar<KtEscapeStringTemplateEntry>() ?: return myMatchingVisitor.result = substituteOrMatchText(entry, other) } override fun visitBinaryWithTypeRHSExpression(expression: KtBinaryExpressionWithTypeRHS) { val other = getTreeElementDepar<KtBinaryExpressionWithTypeRHS>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.operationReference, other.operationReference) && myMatchingVisitor.match(expression.left, other.left) && myMatchingVisitor.match(expression.right, other.right) } override fun visitIsExpression(expression: KtIsExpression) { val other = getTreeElementDepar<KtIsExpression>() ?: return myMatchingVisitor.result = expression.isNegated == other.isNegated && myMatchingVisitor.match(expression.leftHandSide, other.leftHandSide) && myMatchingVisitor.match(expression.typeReference, other.typeReference) } override fun visitDestructuringDeclaration(destructuringDeclaration: KtDestructuringDeclaration) { val other = getTreeElementDepar<KtDestructuringDeclaration>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSequentially(destructuringDeclaration.entries, other.entries) && myMatchingVisitor.match(destructuringDeclaration.initializer, other.initializer) && myMatchingVisitor.match(destructuringDeclaration.docComment, other.docComment) } override fun visitDestructuringDeclarationEntry(multiDeclarationEntry: KtDestructuringDeclarationEntry) { val other = getTreeElementDepar<KtDestructuringDeclarationEntry>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(multiDeclarationEntry.typeReference, other.typeReference) && myMatchingVisitor.match(multiDeclarationEntry.modifierList, other.modifierList) && multiDeclarationEntry.isVar == other.isVar && matchTextOrVariable(multiDeclarationEntry.nameIdentifier, other.nameIdentifier) } override fun visitThrowExpression(expression: KtThrowExpression) { val other = getTreeElementDepar<KtThrowExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.referenceExpression(), other.referenceExpression()) } override fun visitClassLiteralExpression(expression: KtClassLiteralExpression) { val other = getTreeElementDepar<KtClassLiteralExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.receiverExpression, other.receiverExpression) } override fun visitComment(comment: PsiComment) { val other = getTreeElementDepar<PsiComment>() ?: return when (val handler = comment.getUserData(CompiledPattern.HANDLER_KEY)) { is LiteralWithSubstitutionHandler -> { if (other is KDocImpl) { myMatchingVisitor.result = handler.match(comment, other, myMatchingVisitor.matchContext) } else { val offset = 2 + other.text.substring(2).indexOfFirst { it > ' ' } myMatchingVisitor.result = handler.match(other, getCommentText(other), offset, myMatchingVisitor.matchContext) } } is SubstitutionHandler -> { handler.findRegExpPredicate()?.let { it.setNodeTextGenerator { comment -> getCommentText(comment as PsiComment) } } myMatchingVisitor.result = handler.handle( other, 2, other.textLength - if (other.tokenType == KtTokens.EOL_COMMENT) 0 else 2, myMatchingVisitor.matchContext ) } else -> myMatchingVisitor.result = myMatchingVisitor.matchText( StructuralSearchUtil.normalize(getCommentText(comment)), StructuralSearchUtil.normalize(getCommentText(other)) ) } } override fun visitKDoc(kDoc: KDoc) { val other = getTreeElementDepar<KDoc>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder( kDoc.getChildrenOfType<KDocSection>(), other.getChildrenOfType<KDocSection>() ) } override fun visitKDocSection(section: KDocSection) { val other = getTreeElementDepar<KDocSection>() ?: return val important: (PsiElement) -> Boolean = { it.elementType != KDocTokens.LEADING_ASTERISK && !(it.elementType == KDocTokens.TEXT && it.text.trim().isEmpty()) } myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder( section.allChildren.filter(important).toList(), other.allChildren.filter(important).toList() ) } override fun visitKDocTag(tag: KDocTag) { val other = getTreeElementDepar<KDocTag>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder(tag.getChildrenOfType(), other.getChildrenOfType()) } override fun visitKDocLink(link: KDocLink) { val other = getTreeElementDepar<KDocLink>() ?: return myMatchingVisitor.result = substituteOrMatchText(link, other) } companion object { private val augmentedAssignmentsMap = mapOf( KtTokens.PLUSEQ to KtTokens.PLUS, KtTokens.MINUSEQ to KtTokens.MINUS, KtTokens.MULTEQ to KtTokens.MUL, KtTokens.DIVEQ to KtTokens.DIV, KtTokens.PERCEQ to KtTokens.PERC ) } }
apache-2.0
3778ac737a7729ca3bbc338b70015584
53.808885
162
0.67102
5.701195
false
false
false
false
mdaniel/intellij-community
plugins/devkit/intellij.devkit.workspaceModel/src/WorkspaceModelGenerator.kt
1
4159
// 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.devkit.workspaceModel import com.intellij.openapi.application.WriteAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.SourceFolder import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.workspaceModel.codegen.CodeWriter import org.jetbrains.jps.model.java.JavaSourceRootProperties import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.java.JpsJavaExtensionService private val LOG = logger<WorkspaceModelGenerator>() object WorkspaceModelGenerator { private const val GENERATED_FOLDER_NAME = "gen" fun generate(project: Project, module: Module) { val acceptedSourceRoots = getSourceRoot(module) if (acceptedSourceRoots.isEmpty()) { LOG.info("Acceptable module source roots not found") return } acceptedSourceRoots.forEach{ sourceRoot -> WriteAction.run<RuntimeException> { CodeWriter.generate(project, sourceRoot.file!!, Registry.`is`("workspace.model.generator.keep.unknown.fields")) { createGeneratedSourceFolder(module, sourceRoot) } } } println("Selected module ${module.name}") } private fun createGeneratedSourceFolder(module: Module, sourceFolder: SourceFolder): VirtualFile? { // Create gen folder if it doesn't exist val generatedFolder = WriteAction.compute<VirtualFile, RuntimeException> { VfsUtil.createDirectoryIfMissing(sourceFolder.file?.parent, GENERATED_FOLDER_NAME) } val moduleRootManager = ModuleRootManager.getInstance(module) val modifiableModel = moduleRootManager.modifiableModel // Searching for the related content root for (contentEntry in modifiableModel.contentEntries) { val contentEntryFile = contentEntry.file if (contentEntryFile != null && VfsUtilCore.isAncestor(contentEntryFile, generatedFolder, false)) { // Checking if it already contains generation folder val existingGenFolder = contentEntry.sourceFolders.firstOrNull { (it.jpsElement.properties as? JavaSourceRootProperties)?.isForGeneratedSources == true && it.file == generatedFolder } if (existingGenFolder != null) return generatedFolder // If it doesn't, create new get folder for the selected content root val properties = JpsJavaExtensionService.getInstance().createSourceRootProperties("", true) val sourceFolderType = if (sourceFolder.isTestSource) JavaSourceRootType.TEST_SOURCE else JavaSourceRootType.SOURCE contentEntry.addSourceFolder(generatedFolder, sourceFolderType, properties) WriteAction.run<RuntimeException>(modifiableModel::commit) module.project.save() return generatedFolder } } modifiableModel.dispose() return null } private fun getSourceRoot(module: Module): List<SourceFolder> { val moduleRootManager = ModuleRootManager.getInstance(module) val contentEntries = moduleRootManager.contentEntries //val contentEntryFile = contentEntry.file //val sourceFolders = contentEntry.sourceFolders // if (contentEntryFile != null && VfsUtilCore.isAncestor(contentEntryFile, selectedFolder, false)) { // val sourceFolder = contentEntry.sourceFolders.firstOrNull { sourceRoot -> VfsUtil.isUnder(selectedFolder, setOf(sourceRoot.file)) } // if (sourceFolder != null) return sourceFolder // } //} return contentEntries.flatMap { it.sourceFolders.asIterable() }.filter { if (it.file == null) return@filter false val javaSourceRootProperties = it.jpsElement.properties as? JavaSourceRootProperties if (javaSourceRootProperties == null) return@filter true return@filter !javaSourceRootProperties.isForGeneratedSources } } }
apache-2.0
837ee338502b953e556ef655b1512c37
46.272727
141
0.756191
5.096814
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/Trip.kt
1
14531
/* * Trip.kt * * Copyright 2011 Eric Butler <[email protected]> * Copyright 2016-2018 Michael Farrell <[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 au.id.micolous.metrodroid.transit import au.id.micolous.metrodroid.multi.FormattedString import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.Parcelable import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.multi.StringResource import au.id.micolous.metrodroid.time.Daystamp import au.id.micolous.metrodroid.time.Timestamp import au.id.micolous.metrodroid.time.TimestampFormatter import au.id.micolous.metrodroid.time.TimestampFull import au.id.micolous.metrodroid.util.Preferences abstract class Trip : Parcelable { /** * Starting time of the trip. */ abstract val startTimestamp: Timestamp? /** * Ending time of the trip. If this is not known, return null. * * This returns null if not overridden in a subclass. */ open val endTimestamp: Timestamp? get() = null /** * Route name for the trip. This could be a bus line, a tram line, a rail line, etc. * If this is not known, then return null. * * The default implementation attempts to get the route name based on the * {@link #getStartStation()} and {@link #getEndStation()}, using the * {@link Station#getLineNames()} method. * * It does this by attempting to find a common set of Line Names between the Start and End * stations. * * If there is no start or end station data available, or {@link Station#getLineNames()} returns * null, then this also returns null. * * If getting for display purposes, use {@link #getRouteDisplayName()} instead. */ open val routeName: FormattedString? get() { val startLines = startStation?.lineNames.orEmpty() val endLines = endStation?.lineNames.orEmpty() return getRouteName(startLines, endLines) } /** * Vehicle number where the event was recorded. * * This is generally *not* the Station ID, which is declared in * [.getStartStation]. * * This is *not* the Farebox or Machine number. */ open val vehicleID: String? get() = null /** * Machine ID that recorded the transaction. A machine in this context is a farebox, ticket * machine, or ticket validator. * * This is generally *not* the Station ID, which is declared in * [.getStartStation]. * * This is *not* the Vehicle number. */ open val machineID: String? get() = null /** * Number of passengers. * * -1 is unknown or irrelevant (eg: ticket machine purchases). */ open val passengerCount: Int get() = -1 /** * Starting station info for the trip, or null if there is no station information available. * * If supplied, this will be used to render a map of the trip. * * If there is station information available on the card, but the station is unknown (maybe it * doesn't appear in a MdST file, or there is no MdST data available yet), use * [Station.unknown] or [Station.unknown] to create an unknown * [Station]. */ open val startStation: Station? get() = null /** * Ending station info for the trip, or null if there is no station information available. * * If supplied, this will be used to render a map of the trip. * * If there is station information available on the card, but the station is unknown (maybe it * doesn't appear in a MdST file, or there is no MdST data available yet), use * [Station.unknown] or [Station.unknown] to create an unknown * [Station]. */ open val endStation: Station? get() = null /** * Formats the cost of the trip in the appropriate local currency. Be aware that your * implementation should use language-specific formatting and not rely on the system language * for that information. * * * For example, if a phone is set to English and travels to Japan, it does not make sense to * format their travel costs in dollars. Instead, it should be shown in Yen, which the Japanese * currency formatter does. * * @return The cost of the fare formatted in the local currency of the card. */ abstract val fare: TransitCurrency? abstract val mode: Mode /** * If the trip is a transfer from another service, return true. * * If this is not a transfer, or this is unknown, return false. By default, this method returns * false. * * The typical use of this is if an agency allows you to transfer to other services within a * time window. eg: The first trip is $2, but other trips within the next two hours are free. * * This may still return true even if [.getFare] is non-null and non-zero -- this * can indicate a discounted (rather than free) transfer. eg: The trips are $2.50, but other * trips within the next two hours have a $2 discount, making the second trip cost $0.50. */ open val isTransfer: Boolean get() = false /** * If the tap-on event was rejected for the trip, return true. * * This should be used for where a record is added to the card in the case of insufficient * funds to pay for the journey. * * Otherwise, return false. The default is to return false. */ open val isRejected: Boolean get() = false /** * Full name of the agency for the trip. This is used on the map of the trip, where there is * space for longer agency names. * * If this is not known (or there is only one agency for the card), then return null. * * By default, this returns null. * * When isShort is true it means to return short name for trip list where space is limited. */ open fun getAgencyName(isShort: Boolean): FormattedString? = null /** * Is there geographic data associated with this trip? */ fun hasLocation(): Boolean { val startStation = startStation val endStation = endStation return startStation != null && startStation.hasLocation() || endStation != null && endStation.hasLocation() } enum class Mode(val idx: Int, val contentDescription: StringResource) { BUS(0, R.string.mode_bus), /** Used for non-metro (rapid transit) trains */ TRAIN(1, R.string.mode_train), /** Used for trams and light rail */ TRAM(2, R.string.mode_tram), /** Used for electric metro and subway systems */ METRO(3, R.string.mode_metro), FERRY(4, R.string.mode_ferry), TICKET_MACHINE(5, R.string.mode_ticket_machine), VENDING_MACHINE(6, R.string.mode_vending_machine), /** Used for transactions at a store, buying something other than travel. */ POS(7, R.string.mode_pos), OTHER(8, R.string.mode_unknown), BANNED(9, R.string.mode_banned), TROLLEYBUS(10, R.string.mode_trolleybus), TOLL_ROAD(11, R.string.mode_toll_road), MONORAIL(12, R.string.mode_monorail), } class Comparator : kotlin.Comparator<Trip> { private fun getSortingKey(t: Trip): Long? { val s = t.startTimestamp val e = t.endTimestamp val x = when { s is TimestampFull -> s e is TimestampFull -> e s != null -> s else -> e } return when (x) { null -> null is TimestampFull -> x.timeInMillis is Daystamp -> x.daysSinceEpoch * 86400L * 1000L } } override fun compare(a: Trip, b: Trip): Int { val t1 = getSortingKey(a) val t2 = getSortingKey(b) return if (t2 != null && t1 != null) { t2.compareTo(t1) } else if (t2 != null) { 1 } else { 0 } } } /** * Route IDs for the trip. This could be a bus line, a tram line, a rail line, etc. * If this is not known, then return null. * * The default implementation attempts to get the route name based on the * {@link #getStartStation()} and {@link #getEndStation()}, using the * {@link Station#getHumanReadableLineIDs()} method. * * It does this by attempting to find a common set of Line Names between the Start and End * stations. * * If there is no start or end station data available, or * {@link Station#getHumanReadableLineIDs()} returns null, then this also returns null. */ open val humanReadableRouteID: String? get() { val startLines = startStation?.humanReadableLineIds ?: emptyList() val endLines = endStation?.humanReadableLineIds ?: emptyList() return getRouteName(startLines, endLines) } open fun getRawFields(level: TransitData.RawLevel): String? = null companion object { fun getRouteName(startLines: List<String>, endLines: List<String>): String? { if (startLines.isEmpty() && endLines.isEmpty()) { return null } // Method 1: if only the start is set, use the first start line. if (endLines.isEmpty()) { return startLines[0] } // Method 2: if only the end is set, use the first end line. if (startLines.isEmpty()) { return endLines[0] } // Now there is at least 1 candidate line from each group. // Method 3: get the intersection of the two list of candidate stations val lines = startLines.toSet() intersect endLines.toSet() if (!lines.isEmpty()) { // There is exactly 1 common line -- return it if (lines.size == 1) { return lines.iterator().next() } // There are more than one common line. Return the first one that appears in the order // of the starting line stations. for (candidateLine in startLines) { if (lines.contains(candidateLine)) { return candidateLine } } } // There are no overlapping lines. Return the first associated with the start station. return startLines[0] } fun getRouteName(startLines: List<FormattedString>, endLines: List<FormattedString>): FormattedString? { val unformatted = getRouteName( startLines.map { it.unformatted }, endLines.map { it.unformatted }) ?: return null return startLines.find { it.unformatted == unformatted } ?: endLines.find { it.unformatted == unformatted } ?: FormattedString(unformatted) } /** * Get the route name for display purposes. * * This handles the "showRawStationIds" setting. */ fun getRouteDisplayName(trip: Trip): FormattedString? { if (!Preferences.showRawStationIds) return trip.routeName val routeName = trip.routeName val routeID = trip.humanReadableRouteID ?: return routeName if (routeName == null) { // No Name // Only do this if the raw display is on, because the route name may be hidden // because it is zero. return FormattedString(routeID) } return if (routeName.unformatted.contains(routeID)) { // Likely unknown route routeName } else { // Known route routeName + " [$routeID]" } } fun formatTimes(trip: Trip): FormattedString? { val start = trip.startTimestamp val end = trip.endTimestamp return when { start is TimestampFull && end is TimestampFull -> Localizer.localizeFormatted(R.string.time_from_to, TimestampFormatter.timeFormat(start), TimestampFormatter.timeFormat(end)) start is TimestampFull -> TimestampFormatter.timeFormat(start) end is TimestampFull -> Localizer.localizeFormatted(R.string.time_from_unknown_to, TimestampFormatter.timeFormat(end)) else -> null } } /** * Formats a trip description into a localised label, with appropriate language annotations. * * @param trip The trip to describe. * @return null if both the start and end stations are unknown. */ fun formatStationNames(trip: Trip): FormattedString? { val startStationName = trip.startStation?.getStationName(true) val endStationName: FormattedString? if (trip.endStation?.getStationName(false) == trip.startStation?.getStationName(false)) { endStationName = null } else { endStationName = trip.endStation?.getStationName(true) } if (endStationName == null) { return startStationName } if (startStationName == null) { return Localizer.localizeTts(R.string.trip_description_unknown_start, endStationName) } return Localizer.localizeTts(R.string.trip_description, startStationName, endStationName) } } }
gpl-3.0
149d6c528b0d74ce9c495e5e05e8baa4
36.451031
115
0.599959
4.516941
false
false
false
false
GunoH/intellij-community
platform/execution-impl/src/com/intellij/execution/impl/RCInArbitraryFileManager.kt
8
11406
// 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.execution.impl import com.intellij.configurationStore.digest import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.* import org.jdom.Element import java.io.ByteArrayInputStream import java.util.* /** * Manages run configurations that are stored in arbitrary `*.run.xml` files in project (not in .idea/runConfigurations or project.ipr file). */ internal class RCInArbitraryFileManager(private val project: Project) { private val LOG = logger<RCInArbitraryFileManager>() internal class DeletedAndAddedRunConfigs(deleted: Collection<RunnerAndConfigurationSettingsImpl>, added: Collection<RunnerAndConfigurationSettingsImpl>) { // new lists are created to make sure that lists used in model are not available outside this class val deletedRunConfigs: Collection<RunnerAndConfigurationSettingsImpl> = if (deleted.isEmpty()) emptyList() else ArrayList(deleted) val addedRunConfigs: Collection<RunnerAndConfigurationSettingsImpl> = if (added.isEmpty()) emptyList() else ArrayList(added) } private val filePathToRunConfigs = mutableMapOf<String, MutableList<RunnerAndConfigurationSettingsImpl>>() // Remember digest in order not to overwrite file with an equivalent content (e.g. different line endings or smth non-meaningful) private val filePathToDigests = Collections.synchronizedMap(mutableMapOf<String, MutableList<ByteArray>>()) private var saveInProgress = false /** * This function should be called with RunManagerImpl.lock.write */ internal fun addRunConfiguration(runConfig: RunnerAndConfigurationSettingsImpl) { val filePath = runConfig.pathIfStoredInArbitraryFileInProject if (!runConfig.isStoredInArbitraryFileInProject || filePath == null) { LOG.error("Unexpected run configuration, path: $filePath") return } val runConfigs = filePathToRunConfigs[filePath] if (runConfigs != null) { if (!runConfigs.contains(runConfig)) { runConfigs.add(runConfig) } } else { filePathToRunConfigs[filePath] = mutableListOf(runConfig) } } /** * This function should be called with RunManagerImpl.lock.write */ internal fun removeRunConfiguration(runConfig: RunnerAndConfigurationSettingsImpl, removeRunConfigOnlyIfFileNameChanged: Boolean = false, deleteContainingFile: Boolean = true) { val fileEntryIterator = filePathToRunConfigs.iterator() for (fileEntry in fileEntryIterator) { val filePath = fileEntry.key val runConfigIterator = fileEntry.value.iterator() for (rc in runConfigIterator) { if (rc == runConfig || rc.isTemplate && runConfig.isTemplate && rc.type == runConfig.type) { if (filePath != runConfig.pathIfStoredInArbitraryFileInProject || !removeRunConfigOnlyIfFileNameChanged) { runConfigIterator.remove() if (fileEntry.value.isEmpty()) { fileEntryIterator.remove() filePathToDigests.remove(filePath) if (deleteContainingFile) { LocalFileSystem.getInstance().findFileByPath(filePath)?.let { deleteFile(it) } } } } return } } } } private fun deleteFile(file: VirtualFile) { ModalityUiUtil.invokeLaterIfNeeded( ModalityState.NON_MODAL) { runWriteAction { file.delete(this@RCInArbitraryFileManager) } } } /** * This function doesn't change the model, caller should iterate through the returned list and remove/add run configurations as needed. * This function should be called with RunManagerImpl.lock.read */ internal fun loadChangedRunConfigsFromFile(runManager: RunManagerImpl, filePath: String): DeletedAndAddedRunConfigs { if (saveInProgress) { return DeletedAndAddedRunConfigs(emptyList(), emptyList()) } // shadow mutable map to ensure unchanged model val filePathToRunConfigs: Map<String, List<RunnerAndConfigurationSettingsImpl>> = filePathToRunConfigs val file = LocalFileSystem.getInstance().findFileByPath(filePath) if (file == null) { LOG.warn("It's unexpected that the file doesn't exist at this point ($filePath)") val rcsToDelete = filePathToRunConfigs[filePath] ?: emptyList() return DeletedAndAddedRunConfigs(rcsToDelete, emptyList()) } if (!ProjectFileIndex.getInstance(project).isInContent(file)) { val rcsToDelete = filePathToRunConfigs[filePath] ?: emptyList() if (rcsToDelete.isNotEmpty()) { LOG.warn("It's unexpected that the model contains run configurations for file, which is not within the project content ($filePath)") } return DeletedAndAddedRunConfigs(rcsToDelete, emptyList()) } val previouslyLoadedRunConfigs = filePathToRunConfigs[filePath] ?: emptyList() val bytes = try { VfsUtil.loadBytes(file) } catch (e: Exception) { LOG.warn("Failed to load file $filePath: $e") return DeletedAndAddedRunConfigs(previouslyLoadedRunConfigs, emptyList()) } val element = try { JDOMUtil.load(CharsetToolkit.inputStreamSkippingBOM(ByteArrayInputStream(bytes))) } catch (e: Exception) { LOG.info("Failed to parse file $filePath: $e") return DeletedAndAddedRunConfigs(previouslyLoadedRunConfigs, emptyList()) } if (element.name != "component" || element.getAttributeValue("name") != "ProjectRunConfigurationManager") { LOG.trace("Unexpected root element ${element.name} with name=${element.getAttributeValue("name")} in $filePath") return DeletedAndAddedRunConfigs(previouslyLoadedRunConfigs, emptyList()) } val loadedRunConfigs = mutableListOf<RunnerAndConfigurationSettingsImpl>() val loadedDigests = mutableListOf<ByteArray>() for (configElement in element.getChildren("configuration")) { try { val runConfig = RunnerAndConfigurationSettingsImpl(runManager) runConfig.readExternal(configElement, true) runConfig.storeInArbitraryFileInProject(filePath) loadedRunConfigs.add(runConfig) loadedDigests.add(runConfig.writeScheme().digest()) } catch (e: Throwable /* classloading problems are expected too */) { LOG.warn("Failed to read run configuration in $filePath", e) } } val previouslyLoadedDigests = filePathToDigests[filePath] ?: emptyList() if (sameDigests(loadedDigests, previouslyLoadedDigests)) { return DeletedAndAddedRunConfigs(emptyList(), emptyList()) } else { filePathToDigests[filePath] = loadedDigests return DeletedAndAddedRunConfigs(previouslyLoadedRunConfigs, loadedRunConfigs) } } /** * This function doesn't change the model, caller should iterate through the returned list and remove run configurations. * This function should be called with RunManagerImpl.lock.read */ internal fun findRunConfigsThatAreNotWithinProjectContent(): List<RunnerAndConfigurationSettingsImpl> { // shadow mutable map to ensure unchanged model val filePathToRunConfigs: Map<String, List<RunnerAndConfigurationSettingsImpl>> = filePathToRunConfigs if (filePathToRunConfigs.isEmpty()) return emptyList() val fileIndex = ProjectFileIndex.getInstance(project) val deletedRunConfigs = mutableListOf<RunnerAndConfigurationSettingsImpl>() for (entry in filePathToRunConfigs) { val filePath = entry.key val runConfigs = entry.value val file = LocalFileSystem.getInstance().findFileByPath(filePath) if (file == null) { if (!saveInProgress) { deletedRunConfigs.addAll(runConfigs) LOG.warn("It's unexpected that the file doesn't exist at this point ($filePath)") } } else { if (!fileIndex.isInContent(file)) { deletedRunConfigs.addAll(runConfigs) } } } return deletedRunConfigs } /** * This function should be called with RunManagerImpl.lock.read */ internal fun getRunConfigsFromFiles(filePaths: Collection<String>): Collection<RunnerAndConfigurationSettingsImpl> { val result = mutableListOf<RunnerAndConfigurationSettingsImpl>() for (filePath in filePaths) { filePathToRunConfigs[filePath]?.let { result.addAll(it) } } return result } /** * This function should be called with RunManagerImpl.lock.read */ internal fun saveRunConfigs() { val errors = SmartList<Throwable>() for (entry in filePathToRunConfigs.entries) { val filePath = entry.key val runConfigs = entry.value saveInProgress = true try { val rootElement = Element("component").setAttribute("name", "ProjectRunConfigurationManager") val newDigests = mutableListOf<ByteArray>() for (runConfig in runConfigs) { val element = runConfig.writeScheme() rootElement.addContent(element) newDigests.add(element.digest()) } val previouslyLoadedDigests = filePathToDigests[filePath] ?: emptyList() if (!sameDigests(newDigests, previouslyLoadedDigests)) { saveToFile(filePath, rootElement.toBufferExposingByteArray()) filePathToDigests[filePath] = newDigests } } catch (e: Exception) { errors.add(RuntimeException("Cannot save run configuration in $filePath", e)) } finally { saveInProgress = false } } throwIfNotEmpty(errors) } private fun sameDigests(digests1: List<ByteArray>, digests2: List<ByteArray>): Boolean { if (digests1.size != digests2.size) return false val iterator2 = digests2.iterator() digests1.forEach { if (!it.contentEquals(iterator2.next())) return@sameDigests false } return true } private fun saveToFile(filePath: String, byteOut: BufferExposingByteArrayOutputStream) { runWriteAction { var file = LocalFileSystem.getInstance().findFileByPath(filePath) if (file == null) { val parentPath = PathUtil.getParentPath(filePath) val dir = VfsUtil.createDirectoryIfMissing(parentPath) if (dir == null) { LOG.error("Failed to create directory $parentPath") return@runWriteAction } file = dir.createChildData(this@RCInArbitraryFileManager, PathUtil.getFileName(filePath)) } file.getOutputStream(this@RCInArbitraryFileManager).use { byteOut.writeTo(it) } } } /** * This function should be called with RunManagerImpl.lock.write */ internal fun clearAllAndReturnFilePaths(): Collection<String> { val filePaths = filePathToRunConfigs.keys.toList() filePathToRunConfigs.clear() filePathToDigests.clear() return filePaths } }
apache-2.0
0e72ee99034bcc3ae89ca011703fbabb
38.74216
141
0.711468
4.914261
false
true
false
false
GunoH/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/utils/HtmlUtils.kt
8
3350
// 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.grazie.utils import ai.grazie.nlp.utils.takeNonWhitespaces import com.intellij.grazie.text.TextContent import com.intellij.grazie.text.TextContent.Exclusion import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.TextRange import kotlinx.html.* import kotlinx.html.stream.createHTML import java.util.regex.Pattern fun html(body: BODY.() -> Unit) = createHTML(false).html { body { body(this) } } var TABLE.cellpading: String get() = attributes["cellpadding"] ?: "" set(value) { attributes["cellpadding"] = value } var TABLE.cellspacing: String get() = attributes["cellspacing"] ?: "" set(value) { attributes["cellspacing"] = value } var TD.valign: String get() = attributes["valign"] ?: "" set(value) { attributes["valign"] = value } fun FlowContent.nbsp() = +Entities.nbsp private val anyTag = Pattern.compile("</?\\w+[^>]*>") private val closingTag = Pattern.compile("</\\w+\\s*>") fun removeHtml(_content: TextContent?): TextContent? { var content: TextContent = _content ?: return null while (content.startsWith("<html>") || content.startsWith("<body>")) { content = content.excludeRange(TextRange(0, 6)) } while (content.endsWith("</html>") || content.endsWith("</body>")) { content = content.excludeRange(TextRange.from(content.length - 7, 7)) } val exclusions = arrayListOf<Exclusion>() fun openingTagName(tagRangeStart: Int, tagRangeEnd: Int): String? = if (Character.isLetter(content[tagRangeStart + 1])) content.substring(tagRangeStart + 1, tagRangeEnd - 1).takeNonWhitespaces() else null fun tagClosed(tagName: String) { val openingIndex = exclusions.indexOfLast { openingTagName(it.start, it.end) == tagName && content[it.end - 2] != '/' } if (openingIndex >= 0) { exclusions[openingIndex] = Exclusion.markUnknown(TextRange(exclusions[openingIndex].start, exclusions.last().end)) exclusions.subList(openingIndex + 1, exclusions.size).clear() } } for (tagRange in Text.allOccurrences(anyTag, content)) { ProgressManager.checkCanceled() if (closingTag.matcher(content.subSequence(tagRange.startOffset, tagRange.endOffset)).matches()) { exclusions.add(Exclusion.markUnknown(tagRange)) tagClosed(content.substring(tagRange.startOffset + 2, tagRange.endOffset - 1).trim()) } else if (openingTagName(tagRange.startOffset, tagRange.endOffset) != null) { exclusions.add(Exclusion.markUnknown(tagRange)) } } return content.excludeRanges(exclusions) } private val nbsp = Pattern.compile("&nbsp;") fun nbspToSpace(content: TextContent?): TextContent? { if (content == null) return null val spaces = Text.allOccurrences(nbsp, content) if (spaces.isEmpty()) return content.trimWhitespace() val components = arrayListOf<TextContent?>() for (i in spaces.indices) { val prevEnd = if (i == 0) 0 else spaces[i - 1].endOffset components.add(content.subText(TextRange(prevEnd, spaces[i].startOffset))?.trimWhitespace()) } components.add(content.subText(TextRange(spaces.last().endOffset, content.length))?.trimWhitespace()) return TextContent.joinWithWhitespace(' ', components.filterNotNull()) }
apache-2.0
96a2f33aade45dac736a5732947752bd
36.222222
140
0.716418
3.877315
false
false
false
false
GunoH/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/archetype/MavenManageCatalogsDialog.kt
2
1066
// 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.maven.wizards.archetype import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.dsl.builder.Align import com.intellij.ui.dsl.builder.panel import org.jetbrains.idea.maven.indices.archetype.MavenCatalogManager import org.jetbrains.idea.maven.wizards.MavenWizardBundle class MavenManageCatalogsDialog(private val project: Project) : DialogWrapper(project, true) { override fun createCenterPanel() = panel { val catalogsManager = MavenCatalogManager.getInstance() val table = MavenCatalogsTable(project) table.catalogs = catalogsManager.getCatalogs(project) row { cell(table.component) .align(Align.FILL) }.resizableRow() onApply { catalogsManager.setCatalogs(table.catalogs) } } init { title = MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.manage.dialog.title") init() } }
apache-2.0
6442826bae51feb1de9564324aef25a6
34.566667
120
0.766417
4.084291
false
false
false
false
ftomassetti/kolasu
core/src/main/kotlin/com/strumenta/kolasu/model/SymbolResolution.kt
1
1252
package com.strumenta.kolasu.model import kotlin.reflect.KClass interface Symbol : PossiblyNamed class Scope private constructor( private val symbols: MutableMap<String, MutableList<Symbol>> = mutableMapOf(), private val parent: Scope? = null, ) { constructor(vararg symbols: Symbol, parent: Scope? = null) : this(symbols = listOf(*symbols), parent = parent) constructor(symbols: List<Symbol> = emptyList(), parent: Scope? = null) : this( symbols = symbols.groupBy { it.name ?: throw IllegalArgumentException("All given symbols must have a name") } .mapValues { it.value.toMutableList() }.toMutableMap(), parent = parent ) fun add(symbol: Symbol) { val symbolName: String = symbol.name ?: throw IllegalArgumentException("The given symbol must have a name") this.symbols.computeIfAbsent(symbolName) { mutableListOf() }.add(symbol) } fun lookup(symbolName: String, symbolType: KClass<*> = Symbol::class): Symbol? { return this.symbols.getOrDefault(symbolName, mutableListOf()).find { symbolType.isInstance(it) } ?: this.parent?.lookup(symbolName, symbolType) } fun getSymbols(): Map<String, List<Symbol>> { return this.symbols } }
apache-2.0
177182314046564a44ee18737d603623
38.125
117
0.682109
4.455516
false
false
false
false
mvmike/min-cal-widget
app/src/main/kotlin/cat/mvmike/minimalcalendarwidget/domain/configuration/item/Transparency.kt
1
1627
// Copyright (c) 2016, Miquel Martí <[email protected]> // See LICENSE for licensing information package cat.mvmike.minimalcalendarwidget.domain.configuration.item import cat.mvmike.minimalcalendarwidget.infrastructure.resolver.GraphicResolver import java.util.Locale // ranges from 0 (fully transparent) to 255 (fully opaque) private const val MIN_ALPHA = 0 private const val MAX_ALPHA = 255 private const val MIN_PERCENTAGE = 0 private const val MAX_PERCENTAGE = 100 private const val HEX_STRING_FORMAT = "%02X" data class Transparency( val percentage: Int ) { init { require(percentage in MIN_PERCENTAGE..MAX_PERCENTAGE) } internal fun getAlpha( transparencyRange: TransparencyRange ) = (transparencyRange.maxAlpha - transparencyRange.minAlpha).toFloat() .div(MAX_PERCENTAGE) .times(MAX_PERCENTAGE - percentage) .plus(transparencyRange.minAlpha) .toInt() internal fun getAlphaInHex( transparencyRange: TransparencyRange ) = String.format(Locale.ENGLISH, HEX_STRING_FORMAT, getAlpha(transparencyRange)) } enum class TransparencyRange( val minAlpha: Int, val maxAlpha: Int ) { COMPLETE( minAlpha = MIN_ALPHA, maxAlpha = MAX_ALPHA ), MODERATE( minAlpha = MIN_ALPHA, maxAlpha = 80 ), LOW( minAlpha = MIN_ALPHA, maxAlpha = 30 ); } internal fun String.withTransparency( transparency: Transparency, transparencyRange: TransparencyRange ) = GraphicResolver.parseColour("#${transparency.getAlphaInHex(transparencyRange)}${this.takeLast(6)}")
bsd-3-clause
33020f15013cbd7ca919a12359967530
26.1
103
0.704182
4.190722
false
false
false
false
ktorio/ktor
ktor-network/jvm/src/io/ktor/network/selector/ActorSelectorManager.kt
1
6499
/* * 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.network.selector import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import java.io.* import java.nio.channels.* import java.util.concurrent.atomic.* import kotlin.coroutines.* import kotlin.coroutines.intrinsics.* /** * Default CIO selector manager implementation */ @Suppress("BlockingMethodInNonBlockingContext") public class ActorSelectorManager(context: CoroutineContext) : SelectorManagerSupport(), Closeable, CoroutineScope { @Volatile private var selectorRef: Selector? = null private val wakeup = AtomicLong() @Volatile private var inSelect = false private val continuation = ContinuationHolder<Unit, Continuation<Unit>>() @Volatile private var closed = false private val selectionQueue = LockFreeMPSCQueue<Selectable>() override val coroutineContext: CoroutineContext = context + CoroutineName("selector") init { launch { val selector = provider.openSelector() ?: error("openSelector() = null") selectorRef = selector selector.use { currentSelector -> try { process(selectionQueue, currentSelector) } catch (cause: Throwable) { closed = true selectionQueue.close() cancelAllSuspensions(currentSelector, cause) } finally { closed = true selectionQueue.close() selectorRef = null cancelAllSuspensions(currentSelector, null) } while (true) { val selectable = selectionQueue.removeFirstOrNull() ?: break val cause = ClosedSendChannelException("Failed to apply interest: selector closed") cancelAllSuspensions(selectable, cause) } } } } private suspend fun process(mb: LockFreeMPSCQueue<Selectable>, selector: Selector) { while (!closed) { processInterests(mb, selector) if (pending > 0) { if (select(selector) > 0) { handleSelectedKeys(selector.selectedKeys(), selector.keys()) } else { val received = mb.removeFirstOrNull() if (received != null) applyInterest(selector, received) else yield() } continue } if (cancelled > 0) { selector.selectNow() if (pending > 0) { handleSelectedKeys(selector.selectedKeys(), selector.keys()) } else { cancelled = 0 } continue } val received = mb.receiveOrNull() ?: break applyInterest(selector, received) } } private suspend fun select(selector: Selector): Int { inSelect = true dispatchIfNeeded() return if (wakeup.get() == 0L) { val count = selector.select(500L) inSelect = false count } else { inSelect = false wakeup.set(0) selector.selectNow() } } private suspend inline fun dispatchIfNeeded() { yield() // it will always redispatch it to the right thread // it is very important here because we do _unintercepted_ resume that may lead to blocking on a wrong thread // that may cause deadlock } private fun selectWakeup() { if (wakeup.incrementAndGet() == 1L && inSelect) { selectorRef?.wakeup() } } private fun processInterests(mb: LockFreeMPSCQueue<Selectable>, selector: Selector) { while (true) { val selectable = mb.removeFirstOrNull() ?: break applyInterest(selector, selectable) } } override fun notifyClosed(selectable: Selectable) { cancelAllSuspensions(selectable, ClosedChannelException()) selectorRef?.let { selector -> selectable.channel.keyFor(selector)?.let { key -> key.cancel() selectWakeup() } } } /** * Publish current [selectable] interest */ override fun publishInterest(selectable: Selectable) { try { if (selectionQueue.addLast(selectable)) { continuation.resume(Unit) selectWakeup() } else if (selectable.channel.isOpen) throw ClosedSelectorException() else throw ClosedChannelException() } catch (cause: Throwable) { cancelAllSuspensions(selectable, cause) } } private suspend fun LockFreeMPSCQueue<Selectable>.receiveOrNull(): Selectable? = removeFirstOrNull() ?: receiveOrNullSuspend() private suspend fun LockFreeMPSCQueue<Selectable>.receiveOrNullSuspend(): Selectable? { while (true) { val selectable: Selectable? = removeFirstOrNull() if (selectable != null) return selectable if (closed) return null suspendCoroutineUninterceptedOrReturn<Unit> { continuation.suspendIf(it) { isEmpty && !closed } ?: Unit } } } /** * Close selector manager and release all resources */ override fun close() { closed = true selectionQueue.close() if (!continuation.resume(Unit)) { selectWakeup() } } private class ContinuationHolder<R, C : Continuation<R>> { private val ref = AtomicReference<C?>(null) fun resume(value: R): Boolean { val continuation = ref.getAndSet(null) ?: return false continuation.resume(value) return true } /** * @return `null` if not suspended due to failed condition or `COROUTINE_SUSPENDED` if successfully applied */ inline fun suspendIf(continuation: C, condition: () -> Boolean): Any? { if (!condition()) return null if (!ref.compareAndSet(null, continuation)) { throw IllegalStateException("Continuation is already set") } if (!condition() && ref.compareAndSet(continuation, null)) return null return COROUTINE_SUSPENDED } } }
apache-2.0
9494586ad7ec642625e012e1caebf02f
31.495
118
0.575473
5.266613
false
false
false
false
ktorio/ktor
ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/Parser.kt
1
5125
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.tls import io.ktor.network.tls.extensions.* import io.ktor.utils.io.* import io.ktor.utils.io.core.* import java.io.* import java.math.* import java.security.cert.* import java.security.spec.* import kotlin.experimental.* private const val MAX_TLS_FRAME_SIZE = 0x4800 internal suspend fun ByteReadChannel.readTLSRecord(): TLSRecord { val type = TLSRecordType.byCode(readByte().toInt() and 0xff) val version = readTLSVersion() val length = readShortCompatible() and 0xffff if (length > MAX_TLS_FRAME_SIZE) throw TLSException("Illegal TLS frame size: $length") val packet = readPacket(length) return TLSRecord(type, version, packet) } internal fun ByteReadPacket.readTLSHandshake(): TLSHandshake = TLSHandshake().apply { val typeAndVersion = readInt() type = TLSHandshakeType.byCode(typeAndVersion ushr 24) val length = typeAndVersion and 0xffffff packet = buildPacket { writeFully(readBytes(length)) } } internal fun ByteReadPacket.readTLSServerHello(): TLSServerHello { val version = readTLSVersion() val random = ByteArray(32) readFully(random) val sessionIdLength = readByte().toInt() and 0xff if (sessionIdLength > 32) { throw TLSException("sessionId length limit of 32 bytes exceeded: $sessionIdLength specified") } val sessionId = ByteArray(32) readFully(sessionId, 0, sessionIdLength) val suite = readShort() val compressionMethod = readByte().toShort() and 0xff if (compressionMethod.toInt() != 0) { throw TLSException( "Unsupported TLS compression method $compressionMethod (only null 0 compression method is supported)" ) } if (remaining.toInt() == 0) return TLSServerHello(version, random, sessionId, suite, compressionMethod) // handle extensions val extensionSize = readShort().toInt() and 0xffff if (remaining.toInt() != extensionSize) { throw TLSException("Invalid extensions size: requested $extensionSize, available $remaining") } val extensions = mutableListOf<TLSExtension>() while (remaining > 0) { val type = readShort().toInt() and 0xffff val length = readShort().toInt() and 0xffff extensions += TLSExtension( TLSExtensionType.byCode(type), length, buildPacket { writeFully(readBytes(length)) } ) } return TLSServerHello(version, random, sessionId, suite, compressionMethod, extensions) } internal fun ByteReadPacket.readCurveParams(): NamedCurve { val type = readByte().toInt() and 0xff when (ServerKeyExchangeType.byCode(type)) { ServerKeyExchangeType.NamedCurve -> { val curveId = readShort() return NamedCurve.fromCode(curveId) ?: throw TLSException("Unknown EC id") } ServerKeyExchangeType.ExplicitPrime -> error("ExplicitPrime server key exchange type is not yet supported") ServerKeyExchangeType.ExplicitChar -> error("ExplicitChar server key exchange type is not yet supported") } } internal fun ByteReadPacket.readTLSCertificate(): List<Certificate> { val certificatesChainLength = readTripleByteLength() var certificateBase = 0 val result = ArrayList<Certificate>() val factory = CertificateFactory.getInstance("X.509")!! while (certificateBase < certificatesChainLength) { val certificateLength = readTripleByteLength() if (certificateLength > (certificatesChainLength - certificateBase)) { throw TLSException("Certificate length is too big") } if (certificateLength > remaining) throw TLSException("Certificate length is too big") val certificate = ByteArray(certificateLength) readFully(certificate) certificateBase += certificateLength + 3 val x509 = factory.generateCertificate(certificate.inputStream()) result.add(x509) } return result } internal fun ByteReadPacket.readECPoint(fieldSize: Int): ECPoint { val pointSize = readByte().toInt() and 0xff val tag = readByte() if (tag != 4.toByte()) throw TLSException("Point should be uncompressed") val componentLength = (pointSize - 1) / 2 if ((fieldSize + 7) ushr 3 != componentLength) throw TLSException("Invalid point component length") return ECPoint( BigInteger(1, readBytes(componentLength)), BigInteger(1, readBytes(componentLength)) ) } private suspend fun ByteReadChannel.readTLSVersion() = TLSVersion.byCode(readShortCompatible() and 0xffff) private fun ByteReadPacket.readTLSVersion() = TLSVersion.byCode(readShort().toInt() and 0xffff) internal fun ByteReadPacket.readTripleByteLength(): Int = (readByte().toInt() and 0xff shl 16) or (readShort().toInt() and 0xffff) internal suspend fun ByteReadChannel.readShortCompatible(): Int { val first = readByte().toInt() and 0xff val second = readByte().toInt() and 0xff return (first shl 8) + second }
apache-2.0
296b4f0ec9dade9d7db306a3a95a0cae
32.940397
119
0.701659
4.414298
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpRedirect.kt
1
4166
/* * 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.client.plugins import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.events.* import io.ktor.http.* import io.ktor.util.* import kotlin.native.concurrent.* private val ALLOWED_FOR_REDIRECT: Set<HttpMethod> = setOf(HttpMethod.Get, HttpMethod.Head) /** * An [HttpClient] plugin that handles HTTP redirects */ public class HttpRedirect private constructor( private val checkHttpMethod: Boolean, private val allowHttpsDowngrade: Boolean ) { @KtorDsl public class Config { /** * Checks whether the HTTP method is allowed for the redirect. * Only [HttpMethod.Get] and [HttpMethod.Head] are allowed for implicit redirection. * * Please note: changing this flag could lead to security issues, consider changing the request URL instead. */ public var checkHttpMethod: Boolean = true /** * `true` allows a client to make a redirect with downgrading from HTTPS to plain HTTP. */ public var allowHttpsDowngrade: Boolean = false } public companion object Plugin : HttpClientPlugin<Config, HttpRedirect> { override val key: AttributeKey<HttpRedirect> = AttributeKey("HttpRedirect") /** * Occurs when receiving a response with a redirect message. */ public val HttpResponseRedirect: EventDefinition<HttpResponse> = EventDefinition() override fun prepare(block: Config.() -> Unit): HttpRedirect { val config = Config().apply(block) return HttpRedirect( checkHttpMethod = config.checkHttpMethod, allowHttpsDowngrade = config.allowHttpsDowngrade ) } override fun install(plugin: HttpRedirect, scope: HttpClient) { scope.plugin(HttpSend).intercept { context -> val origin = execute(context) if (plugin.checkHttpMethod && origin.request.method !in ALLOWED_FOR_REDIRECT) { return@intercept origin } handleCall(context, origin, plugin.allowHttpsDowngrade, scope) } } @OptIn(InternalAPI::class) private suspend fun Sender.handleCall( context: HttpRequestBuilder, origin: HttpClientCall, allowHttpsDowngrade: Boolean, client: HttpClient ): HttpClientCall { if (!origin.response.status.isRedirect()) return origin var call = origin var requestBuilder = context val originProtocol = origin.request.url.protocol val originAuthority = origin.request.url.authority while (true) { client.monitor.raise(HttpResponseRedirect, call.response) val location = call.response.headers[HttpHeaders.Location] requestBuilder = HttpRequestBuilder().apply { takeFromWithExecutionContext(requestBuilder) url.parameters.clear() location?.let { url.takeFrom(it) } /** * Disallow redirect with a security downgrade. */ if (!allowHttpsDowngrade && originProtocol.isSecure() && !url.protocol.isSecure()) { return call } if (originAuthority != url.authority) { headers.remove(HttpHeaders.Authorization) } } call = execute(requestBuilder) if (!call.response.status.isRedirect()) return call } } } } private fun HttpStatusCode.isRedirect(): Boolean = when (value) { HttpStatusCode.MovedPermanently.value, HttpStatusCode.Found.value, HttpStatusCode.TemporaryRedirect.value, HttpStatusCode.PermanentRedirect.value, HttpStatusCode.SeeOther.value -> true else -> false }
apache-2.0
1ea90a1ff23fe2964398f827c3d39fde
33.429752
118
0.611378
5.130542
false
true
false
false
Doctoror/ParticleConstellationsLiveWallpaper
app/src/main/java/com/doctoror/particleswallpaper/userprefs/bgimage/BackgroundImageModuleProvider.kt
1
1881
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particleswallpaper.userprefs.bgimage import com.doctoror.particleswallpaper.framework.file.BackgroundImageManager import com.doctoror.particleswallpaper.framework.file.BackgroundImageManagerImpl import com.doctoror.particleswallpaper.framework.file.FileSaver import com.doctoror.particleswallpaper.framework.file.FileUriResolver import org.koin.dsl.module.module private const val PARAM_VIEW = 0 fun provideModuleBackgroundImage() = module { factory<BackgroundImageManager> { BackgroundImageManagerImpl( context = get(), fileSaver = FileSaver(get()), fileUriResolver = FileUriResolver(get()) ) } factory { PickImageGetContentUseCase() } factory { PickImageDocumentUseCase(get()) } /* * Parameter at 0 should be BackgroundImagePreferenceView. */ factory { BackgroundImagePreferencePresenter( backgroundImageManager = get(), context = get(), defaults = get(), glide = get(), pickImageGetContentUseCase = get(), pickImageDocumentUseCase = get(), schedulers = get(), settings = get(), view = it[PARAM_VIEW] ) } }
apache-2.0
fdf0e41abdebfb50b41233357ca78bda
30.35
80
0.678894
4.762025
false
false
false
false
neva-dev/javarel-framework
foundation/src/main/kotlin/com/neva/javarel/foundation/impl/scanning/BundleWatcherDelegate.kt
1
1302
package com.neva.javarel.foundation.impl.scanning import com.google.common.collect.Sets import com.neva.javarel.foundation.api.scanning.BundleWatcher import org.apache.felix.scr.annotations.* import org.osgi.framework.BundleContext import org.osgi.framework.BundleEvent import org.osgi.framework.BundleListener @Component(immediate = true) @Service(BundleWatcherDelegate::class) class BundleWatcherDelegate : BundleListener { @Reference( referenceInterface = BundleWatcher::class, cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, policy = ReferencePolicy.DYNAMIC ) private var watchers = Sets.newConcurrentHashSet<BundleWatcher>() private var context: BundleContext? = null @Activate protected fun start(context: BundleContext) { this.context = context context.addBundleListener(this) } @Deactivate protected fun stop() { context?.removeBundleListener(this) } override fun bundleChanged(event: BundleEvent) { for (watcher in watchers) { watcher.watch(event) } } private fun bindWatchers(watcher: BundleWatcher) { watchers.add(watcher) } private fun unbindWatchers(watcher: BundleWatcher) { watchers.remove(watcher) } }
apache-2.0
0e2059855a4af441fbcaa9a5e3e09ca6
25.591837
69
0.707373
4.474227
false
false
false
false
bozaro/git-lfs-java
gitlfs-common/src/main/kotlin/ru/bozaro/gitlfs/common/data/Error.kt
1
471
package ru.bozaro.gitlfs.common.data import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty /** * LFS error description. * * @author Artem V. Navrotskiy */ class Error @JsonCreator constructor( @field:JsonProperty(value = "code", required = true) @param:JsonProperty(value = "code") val code: Int, @field:JsonProperty(value = "message") @param:JsonProperty(value = "message") val message: String? )
lgpl-3.0
333012997d44e580df4eca17f64f2c12
32.642857
111
0.732484
3.892562
false
false
false
false
iSoron/uhabits
uhabits-android/src/androidTest/java/org/isoron/uhabits/HabitFixtures.kt
1
6117
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker 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. * * Loop Habit Tracker 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 org.isoron.uhabits import org.isoron.uhabits.core.models.Entry import org.isoron.uhabits.core.models.Entry.Companion.YES_MANUAL import org.isoron.uhabits.core.models.Frequency import org.isoron.uhabits.core.models.Frequency.Companion.DAILY import org.isoron.uhabits.core.models.Habit import org.isoron.uhabits.core.models.HabitList import org.isoron.uhabits.core.models.HabitType import org.isoron.uhabits.core.models.ModelFactory import org.isoron.uhabits.core.models.NumericalHabitType import org.isoron.uhabits.core.models.PaletteColor import org.isoron.uhabits.core.models.Timestamp import org.isoron.uhabits.core.utils.DateUtils.Companion.getToday class HabitFixtures(private val modelFactory: ModelFactory, private val habitList: HabitList) { var LONG_HABIT_ENTRIES = booleanArrayOf( true, false, false, true, true, true, false, false, true, true ) var LONG_NUMERICAL_HABIT_ENTRIES = intArrayOf( 200000, 0, 150000, 137000, 0, 0, 500000, 30000, 100000, 0, 300000, 100000, 0, 100000 ) fun createEmptyHabit(): Habit { val habit = modelFactory.buildHabit() habit.name = "Meditate" habit.question = "Did you meditate this morning?" habit.description = "This is a test description" habit.color = PaletteColor(5) habit.frequency = DAILY habitList.add(habit) return habit } fun createLongHabit(): Habit { val habit = createEmptyHabit() habit.frequency = Frequency(3, 7) habit.color = PaletteColor(7) val today: Timestamp = getToday() val marks = intArrayOf( 0, 1, 3, 5, 7, 8, 9, 10, 12, 14, 15, 17, 19, 20, 26, 27, 28, 50, 51, 52, 53, 54, 58, 60, 63, 65, 70, 71, 72, 73, 74, 75, 80, 81, 83, 89, 90, 91, 95, 102, 103, 108, 109, 120 ) for (mark in marks) habit.originalEntries.add(Entry(today.minus(mark), YES_MANUAL)) habit.recompute() return habit } fun createVeryLongHabit(): Habit { val habit = createEmptyHabit() habit.frequency = Frequency(1, 2) habit.color = PaletteColor(11) val today: Timestamp = getToday() val marks = intArrayOf( 0, 3, 5, 6, 7, 10, 13, 14, 15, 18, 21, 22, 23, 24, 27, 28, 30, 31, 34, 37, 39, 42, 43, 46, 47, 48, 51, 52, 54, 55, 57, 59, 62, 65, 68, 71, 73, 76, 79, 80, 81, 83, 85, 86, 89, 90, 91, 94, 96, 98, 100, 103, 104, 106, 109, 111, 112, 113, 115, 117, 120, 123, 126, 129, 132, 134, 136, 139, 141, 142, 145, 148, 149, 151, 152, 154, 156, 157, 159, 161, 162, 163, 164, 166, 168, 170, 172, 173, 174, 175, 176, 178, 180, 181, 184, 185, 188, 189, 190, 191, 194, 195, 197, 198, 199, 200, 202, 205, 208, 211, 213, 215, 216, 218, 220, 222, 223, 225, 227, 228, 230, 231, 232, 234, 235, 238, 241, 242, 244, 247, 250, 251, 253, 254, 257, 260, 261, 263, 264, 266, 269, 272, 273, 276, 279, 281, 284, 285, 288, 291, 292, 294, 296, 297, 299, 300, 301, 303, 306, 307, 308, 309, 310, 313, 316, 319, 322, 324, 326, 329, 330, 332, 334, 335, 337, 338, 341, 344, 345, 346, 347, 350, 352, 355, 358, 360, 361, 362, 363, 365, 368, 371, 373, 374, 376, 379, 380, 382, 384, 385, 387, 389, 390, 392, 393, 395, 396, 399, 401, 404, 407, 410, 411, 413, 414, 416, 417, 419, 420, 423, 424, 427, 429, 431, 433, 436, 439, 440, 442, 445, 447, 450, 453, 454, 456, 459, 460, 461, 464, 466, 468, 470, 473, 474, 475, 477, 479, 481, 482, 483, 486, 489, 491, 493, 495, 497, 498, 500, 503, 504, 507, 510, 511, 512, 515, 518, 519, 521, 522, 525, 528, 531, 532, 534, 537, 539, 541, 543, 544, 547, 550, 551, 554, 556, 557, 560, 561, 564, 567, 568, 569, 570, 572, 575, 576, 579, 582, 583, 584, 586, 589 ) for (mark in marks) habit.originalEntries.add(Entry(today.minus(mark), YES_MANUAL)) habit.recompute() return habit } fun createLongNumericalHabit(): Habit { val habit = modelFactory.buildHabit().apply { name = "Read" question = "How many pages did you walk today?" type = HabitType.NUMERICAL targetType = NumericalHabitType.AT_LEAST targetValue = 200.0 unit = "pages" } habitList.add(habit) var timestamp: Timestamp = getToday() for (value in LONG_NUMERICAL_HABIT_ENTRIES) { habit.originalEntries.add(Entry(timestamp, value)) timestamp = timestamp.minus(1) } habit.recompute() return habit } fun createShortHabit(): Habit { val habit = modelFactory.buildHabit().apply { name = "Wake up early" question = "Did you wake up before 6am?" frequency = Frequency(2, 3) } habitList.add(habit) var timestamp: Timestamp = getToday() for (c in LONG_HABIT_ENTRIES) { if (c) habit.originalEntries.add(Entry(timestamp, YES_MANUAL)) timestamp = timestamp.minus(1) } habit.recompute() return habit } @Synchronized fun purgeHabits(habitList: HabitList) { habitList.removeAll() } }
gpl-3.0
4134b58ae4d9e69624add5a4819fc4e9
42.685714
95
0.608731
3.566181
false
false
false
false
yabqiu/sqlshell
src/main/kotlin/cc.unmi/sqlshell/connector.kt
1
1461
import cc.unmi.sqlshell.Database import com.bethecoder.ascii_table.ASCIITable import com.bethecoder.ascii_table.ASCIITableHeader import java.sql.* fun createConnection(database: Database): Connection { return DriverManager.getConnection(database.url, database.user, database.password) } fun showDatabaseMeta(connection: Connection) { val metaData = connection.metaData println("Connected to ${metaData.databaseProductName}, ${metaData.databaseProductVersion}") } fun getTableHeader(rsMetaData: ResultSetMetaData): List<ASCIITableHeader> { val columnCount = rsMetaData.columnCount return (1..columnCount).map { index -> makeHeader(rsMetaData.getColumnLabel(index), rsMetaData.getColumnType(index)) }.toList() } fun getRecords(resultSet: ResultSet): Array<Array<String>> { val columnCount = resultSet.metaData.columnCount val rows = mutableListOf<Array<String>>() while (resultSet.next()) { val columns = (1..columnCount).map { index -> resultSet.getString(index) ?: "NULL" }.toTypedArray() rows.add(columns) } return rows.toTypedArray() } private fun makeHeader(label: String, type: Int): ASCIITableHeader { val isNumeric = arrayOf(Types.BIT, Types.TINYINT, Types.SMALLINT, Types.INTEGER, Types.BIGINT, Types.FLOAT, Types.REAL, Types.DOUBLE, Types.NUMERIC).contains(type) return ASCIITableHeader(label, if(isNumeric) ASCIITable.ALIGN_RIGHT else ASCIITable.ALIGN_LEFT) }
mit
c8abe49d90136b15c70ebc17f6929383
36.487179
111
0.74538
4.013736
false
false
false
false
alexxxdev/kGen
src/ru/alexxxdev/kGen/KotlinFile.kt
1
4895
package ru.alexxxdev.kGen import ru.alexxxdev.kGen.ClassSpec.Kind import ru.alexxxdev.kGen.FieldSpec.PropertyType import ru.alexxxdev.kGen.FieldSpec.PropertyType.READONLY import ru.alexxxdev.kGen.FieldSpec.ValueType import ru.alexxxdev.kGen.FieldSpec.ValueType.NOTNULL import java.io.File import java.io.OutputStreamWriter import java.nio.file.Files import java.nio.file.Path import javax.lang.model.SourceVersion /** * Created by alexxxdev on 28.02.17. */ class KotlinFile(val packageName: String, val fileName: String? = null) : IAppendable { private var imports = mutableListOf<TypeName>() private var classes = mutableListOf<ClassSpec>() private var fields = mutableListOf<FieldSpec>() private var methods = mutableListOf<MethodSpec>() var indent = "\t" operator fun ClassName.unaryPlus() { imports.add(this) } fun kotlinClass(className: String, init: ClassSpec.() -> Unit) = addClass(ClassSpec(Kind.CLASS, className), init) fun kotlinInterface(className: String, init: ClassSpec.() -> Unit) = addClass(ClassSpec(Kind.INTERFACE, className), init) fun kotlinObject(className: String, init: ClassSpec.() -> Unit) = addClass(ClassSpec(Kind.OBJECT, className), init) fun field(name: String, propertyType: PropertyType = READONLY, valueType: ValueType = NOTNULL, init: FieldSpec.() -> String) = addField(FieldSpec(name, propertyType, valueType), init) fun method(name: String, vararg mods: Modifier, init: MethodSpec.() -> Unit) = addMethod(MethodSpec(name), *mods, init = init) private fun addClass(classSpec: ClassSpec, init: ClassSpec.() -> Unit): ClassSpec { classSpec.init() classSpec.build() classes.add(classSpec) return classSpec } private fun addField(fieldSpec: FieldSpec, init: FieldSpec.() -> String): FieldSpec { fieldSpec.initializer = fieldSpec.init() fieldSpec.build() fields.add(fieldSpec) return fieldSpec } private fun addMethod(methodSpec: MethodSpec, vararg mods: Modifier, init: MethodSpec.() -> Unit): MethodSpec { methodSpec.init() mods.forEach { methodSpec.addModificator(it) } methodSpec.build() methods.add(methodSpec) return methodSpec } fun build() { classes.forEach { imports.addAll(it.listImports) } methods.forEach { imports.addAll(it.listImports) } fields.forEach { imports.addAll(it.listImports) } } override fun writeTo(codeWriter: CodeWriter) { codeWriter.out("package $packageName") codeWriter.out("\n\n") //TODO add aliases imports.map { it as ClassName } .distinctBy { it.canonicalName } .sortedBy { it.canonicalName } .forEach { check(SourceVersion.isName(it.canonicalName), "not a valid name: %s", it.canonicalName) codeWriter.out("import ${it.canonicalName}\n") } codeWriter.out("\n") fields.sortedBy { it.name } .forEach { codeWriter.out("\n") it.writeTo(codeWriter) } classes.forEach { codeWriter.out("\n\n") it.writeTo(codeWriter) } methods.sortedBy { it.name } .forEach { codeWriter.out("\n\n") it.writeTo(codeWriter) } } fun writeTo(out: Appendable?) { val codeWriter = CodeWriter(out, indent) writeTo(codeWriter) } fun writeTo(directory: File) { writeTo(directory.toPath()) } fun writeTo(directory: Path) { var outputDirectory = directory if (!packageName.isEmpty()) { for (packageComponent in packageName.split("\\.".toRegex()).dropLastWhile(String::isEmpty).toTypedArray()) { outputDirectory = outputDirectory.resolve(packageComponent) } Files.createDirectories(outputDirectory) } if (fileName != null) { check(fileName.isNotBlank(), "not a valid empty file name") check(SourceVersion.isName(fileName), "not a valid name: %s", fileName) val outputPath = outputDirectory.resolve("$fileName.kt") OutputStreamWriter(Files.newOutputStream(outputPath), Charsets.UTF_8).use({ writer -> writeTo(out = writer) }) } else { check(classes.isNotEmpty(), "No classes or file name found") check(SourceVersion.isName(classes[0].name), "not a valid name: %s", classes[0].name) val outputPath = outputDirectory.resolve("${classes[0].name}.kt") OutputStreamWriter(Files.newOutputStream(outputPath), Charsets.UTF_8).use({ writer -> writeTo(out = writer) }) } } }
apache-2.0
5ebc12d8b0f4a83954eaa6626536e803
33.478873
187
0.621655
4.532407
false
false
false
false
android/privacy-codelab
PhotoLog_End/src/main/java/com/example/photolog_end/Log.kt
1
1553
/* * Copyright (C) 2022 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. */ package com.example.photolog_end import java.io.File import java.text.SimpleDateFormat import java.util.Locale data class Log( val date: String, val place: String, val photos: List<File> ) { val timeInMillis = SimpleDateFormat("yyyy-MM-dd", Locale.US).parse(date)!!.time fun toLogEntry(): LogEntry { return LogEntry( date = date, place = place, photo1 = photos[0].name, photo2 = photos.getOrNull(1)?.name, photo3 = photos.getOrNull(2)?.name ) } companion object { fun fromLogEntry(logEntry: LogEntry, photoFolder: File): Log { return Log( date = logEntry.date, place = logEntry.place, photos = listOfNotNull(logEntry.photo1, logEntry.photo2, logEntry.photo3).map { File(photoFolder, it) } ) } } }
apache-2.0
84e4c9282eb48d245341d855224d7157
29.470588
95
0.629749
4.254795
false
false
false
false
vladmm/intellij-community
platform/script-debugger/backend/src/org/jetbrains/debugger/values/ObjectValueBase.kt
1
3325
/* * Copyright 2000-2015 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. */ package org.jetbrains.debugger.values import com.intellij.util.SmartList import org.jetbrains.concurrency.Obsolescent import org.jetbrains.concurrency.ObsolescentAsyncFunction import org.jetbrains.concurrency.Promise import org.jetbrains.debugger.EvaluateContext import org.jetbrains.debugger.Variable import org.jetbrains.debugger.VariablesHost import org.jetbrains.debugger.Vm import java.util.* abstract class ObjectValueBase<VALUE_LOADER : ValueManager<out Vm>>(type: ValueType) : ValueBase(type), ObjectValue { protected abstract val childrenManager: VariablesHost<VALUE_LOADER> override val properties: Promise<List<Variable>> get() = childrenManager.get() internal abstract inner class MyObsolescentAsyncFunction<PARAM, RESULT>(private val obsolescent: Obsolescent) : ObsolescentAsyncFunction<PARAM, RESULT> { override fun isObsolete() = obsolescent.isObsolete || childrenManager.valueManager.isObsolete } override fun getProperties(names: List<String>, evaluateContext: EvaluateContext, obsolescent: Obsolescent) = properties .then(object : MyObsolescentAsyncFunction<List<Variable>, List<Variable>>(obsolescent) { override fun `fun`(variables: List<Variable>) = getSpecifiedProperties(variables, names, evaluateContext) }) override val valueString: String? = null override fun getIndexedProperties(from: Int, to: Int, bucketThreshold: Int, consumer: IndexedVariablesConsumer, componentType: ValueType?): Promise<*> = Promise.REJECTED @Suppress("CAST_NEVER_SUCCEEDS") override val variablesHost: VariablesHost<ValueManager<Vm>> get() = childrenManager as VariablesHost<ValueManager<Vm>> } fun getSpecifiedProperties(variables: List<Variable>, names: List<String>, evaluateContext: EvaluateContext): Promise<List<Variable>> { val properties = SmartList<Variable>() var getterCount = 0 for (property in variables) { if (!property.isReadable || !names.contains(property.name)) { continue } if (!properties.isEmpty()) { Collections.sort(properties, object : Comparator<Variable> { override fun compare(o1: Variable, o2: Variable) = names.indexOf(o1.name) - names.indexOf(o2.name) }) } properties.add(property) if (property.value == null) { getterCount++ } } if (getterCount == 0) { return Promise.resolve(properties) } else { val promises = SmartList<Promise<*>>() for (variable in properties) { if (variable.value == null) { val valueModifier = variable.valueModifier assert(valueModifier != null) promises.add(valueModifier!!.evaluateGet(variable, evaluateContext)) } } return Promise.all<List<Variable>>(promises, properties) } }
apache-2.0
cd8c4ca9442161fce7940ac50161c0ea
37.674419
171
0.742556
4.415671
false
false
false
false
apollographql/apollo-android
apollo-mockserver/src/appleMain/kotlin/com/apollographql/apollo3/mockserver/FileDescriptorSource.kt
1
1519
package com.apollographql.apollo3.mockserver import kotlinx.cinterop.ByteVar import kotlinx.cinterop.allocArray import kotlinx.cinterop.convert import kotlinx.cinterop.memScoped import kotlinx.cinterop.readBytes import okio.Buffer import okio.IOException import okio.Source import okio.Timeout import platform.posix.errno // TODO: add Cursor implementation class FileDescriptorSource(val fd: Int) : Source { private var closed = false private var exhausted = false override fun read( sink: Buffer, byteCount: Long, ): Long { require(byteCount >= 0L) { "byteCount < 0: $byteCount" } check(!closed) { "closed" } if (exhausted) { return -1L } return memScoped { val bufSize = 8192 val buf = allocArray<ByteVar>(bufSize) var read = 0L while (read < byteCount) { val toRead = minOf(bufSize.toLong(), byteCount - read) val len: Long = platform.posix.read(fd, buf, toRead.convert()).convert() if (len < 0) { throw IOException("Cannot read $fd (errno = $errno)") } if (len == 0L) { exhausted = true return@memScoped read } read += len sink.write(buf.readBytes(len.convert())) if (len < toRead) { // come back later return@memScoped read } } read } } override fun timeout(): Timeout = Timeout.NONE override fun close() { if (closed) return closed = true platform.posix.close(fd) } }
mit
8ffb549c9dcefac58fc5aac30624175e
22.734375
80
0.624753
4.184573
false
false
false
false
vhromada/Catalog
core/src/main/kotlin/com/github/vhromada/catalog/facade/impl/PictureFacadeImpl.kt
1
2090
package com.github.vhromada.catalog.facade.impl import com.github.vhromada.catalog.common.entity.Page import com.github.vhromada.catalog.common.filter.PagingFilter import com.github.vhromada.catalog.entity.ChangePictureRequest import com.github.vhromada.catalog.entity.Picture import com.github.vhromada.catalog.facade.PictureFacade import com.github.vhromada.catalog.mapper.PictureMapper import com.github.vhromada.catalog.service.PictureService import com.github.vhromada.catalog.validator.PictureValidator import org.springframework.data.domain.Sort import org.springframework.stereotype.Component /** * A class represents implementation of facade for pictures. * * @author Vladimir Hromada */ @Component("pictureFacade") class PictureFacadeImpl( /** * Service for pictures */ private val service: PictureService, /** * Mapper for pictures */ private val mapper: PictureMapper, /** * Validator for pictures */ private val validator: PictureValidator ) : PictureFacade { override fun search(filter: PagingFilter): Page<String> { val pictures = service.search(pageable = filter.toPageable(sort = Sort.by("id"))) return Page(data = mapper.mapPictures(source = pictures.content), page = pictures) } override fun get(uuid: String): Picture { return mapper.mapPicture(source = service.getByUuid(uuid = uuid)) } override fun add(request: ChangePictureRequest): Picture { validator.validateRequest(request = request) return mapper.mapPicture(source = service.store(picture = mapper.mapRequest(source = request))) } override fun update(uuid: String, request: ChangePictureRequest): Picture { validator.validateRequest(request = request) val picture = service.getByUuid(uuid = uuid) picture.merge(picture = mapper.mapRequest(source = request)) return mapper.mapPicture(source = service.store(picture = picture)) } override fun remove(uuid: String) { service.remove(picture = service.getByUuid(uuid = uuid)) } }
mit
558ea411c9b0ff95be879b022e43ad69
33.833333
103
0.72823
4.318182
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/screen/info/InfoScreen.kt
2
17587
package io.github.chrislo27.rhre3.screen.info import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input import com.badlogic.gdx.Preferences import com.badlogic.gdx.audio.Sound import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.Colors import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.graphics.glutils.ShapeRenderer import com.badlogic.gdx.utils.Align import io.github.chrislo27.rhre3.PreferenceKeys import io.github.chrislo27.rhre3.RHRE3 import io.github.chrislo27.rhre3.RHRE3Application import io.github.chrislo27.rhre3.VersionHistory import io.github.chrislo27.rhre3.analytics.AnalyticsHandler import io.github.chrislo27.rhre3.credits.CreditsGame import io.github.chrislo27.rhre3.discord.DiscordHelper import io.github.chrislo27.rhre3.discord.PresenceState import io.github.chrislo27.rhre3.editor.CameraBehaviour import io.github.chrislo27.rhre3.editor.Editor import io.github.chrislo27.rhre3.screen.* import io.github.chrislo27.rhre3.sfxdb.GameMetadata import io.github.chrislo27.rhre3.sfxdb.SFXDatabase import io.github.chrislo27.rhre3.soundsystem.BeadsSoundSystem import io.github.chrislo27.rhre3.soundsystem.SoundCache import io.github.chrislo27.rhre3.soundsystem.SoundStretch import io.github.chrislo27.rhre3.stage.FalseCheckbox import io.github.chrislo27.rhre3.stage.GenericStage import io.github.chrislo27.rhre3.stage.LoadingIcon import io.github.chrislo27.rhre3.stage.TrueCheckbox import io.github.chrislo27.rhre3.stage.bg.Background import io.github.chrislo27.rhre3.util.FadeIn import io.github.chrislo27.rhre3.util.FadeOut import io.github.chrislo27.rhre3.util.Semitones import io.github.chrislo27.toolboks.Toolboks import io.github.chrislo27.toolboks.ToolboksScreen import io.github.chrislo27.toolboks.i18n.Localization import io.github.chrislo27.toolboks.registry.AssetRegistry import io.github.chrislo27.toolboks.registry.ScreenRegistry import io.github.chrislo27.toolboks.transition.TransitionScreen import io.github.chrislo27.toolboks.ui.* import io.github.chrislo27.toolboks.util.MathHelper import io.github.chrislo27.toolboks.util.gdxutils.isAltDown import io.github.chrislo27.toolboks.util.gdxutils.isControlDown import io.github.chrislo27.toolboks.util.gdxutils.isShiftDown import io.github.chrislo27.toolboks.version.Version class InfoScreen(main: RHRE3Application) : ToolboksScreen<RHRE3Application, InfoScreen>(main), HidesVersionText { companion object { const val DEFAULT_AUTOSAVE_TIME = 5 val autosaveTimers = listOf(0, 1, 2, 3, 4, 5, 10, 15) var shouldSeePartners: Boolean = true private set var glowButtonInEditor: Boolean = true private set } enum class Page(val heading: String) { INFO("screen.info.info"), SETTINGS("screen.info.settings"), EXTRAS("screen.info.extras"); companion object { val VALUES = values().toList() } } val preferences: Preferences get() = main.preferences val editor: Editor get() = ScreenRegistry.getNonNullAsType<EditorScreen>("editor").editor private var backgroundOnly = false private var currentPage: Page = Page.SETTINGS set(value) { field = value pageStages.forEach { it.visible = false } when (value) { Page.INFO -> { infoStage.visible = true } Page.SETTINGS -> { settingsStage.visible = true } Page.EXTRAS -> { extrasStage.visible = true } } headingLabel.text = value.heading leftPageButton.visible = false rightPageButton.visible = false val index = Page.VALUES.indexOf(value) if (index > 0) { leftPageButton.run { visible = true targetPage = Page.VALUES[index - 1] label.text = targetPage.heading } } if (index < Page.VALUES.size - 1) { rightPageButton.run { visible = true targetPage = Page.VALUES[index + 1] label.text = targetPage.heading } } } override val hidesVersionText: Boolean get() = currentPage == Page.INFO override val stage: GenericStage<InfoScreen> = GenericStage(main.uiPalette, null, main.defaultCamera) private val settingsStage: SettingsStage private val infoStage: InfoStage private val extrasStage: ExtrasStage private val pageStages: List<Stage<InfoScreen>> private val leftPageButton: PageChangeButton private val rightPageButton: PageChangeButton private val headingLabel: TextLabel<InfoScreen> private val onlineLabel: TextLabel<InfoScreen> private val menuBgButton: Button<InfoScreen> init { val palette = stage.palette stage.titleIcon.apply { this.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_info")) } stage.titleLabel.apply { this.text = "editor.info" } stage.backButton.visible = true stage.onBackButtonClick = { main.screen = ScreenRegistry.getNonNull("editor") } stage.bottomStage.elements += object : Button<InfoScreen>(palette, stage.bottomStage, stage.bottomStage) { override fun onLeftClick(xPercent: Float, yPercent: Float) { super.onLeftClick(xPercent, yPercent) Gdx.net.openURI(RHRE3.GITHUB) } }.apply { this.addLabel(TextLabel(palette, this, this.stage).apply { fun updateText() { this.text = Localization["screen.info.github", RHRE3.GITHUB] } this.isLocalizationKey = false this.textWrapping = false updateText() this.fontScaleMultiplier = 0.9f Localization.addListener { updateText() } }) this.location.set(screenX = 0.175f, screenWidth = 0.65f) } menuBgButton = object : Button<InfoScreen>(palette, stage.bottomStage, stage.bottomStage) { val numberLabel = TextLabel(palette.copy(ftfont = main.defaultBorderedFontFTF), this, this.stage).apply { this.textAlign = Align.center this.isLocalizationKey = false this.fontScaleMultiplier = 1f this.textWrapping = false this.location.set(screenX = 0.5f - 0.03f, screenWidth = 0.5f + 0.03f, screenY = 0.3f, screenHeight = 0.7f, pixelWidth = -1f) } val nameLabel = TextLabel(palette.copy(ftfont = main.defaultBorderedFontFTF), this, this.stage).apply { this.textAlign = Align.center this.isLocalizationKey = false this.fontScaleMultiplier = 0.6f this.textWrapping = false this.location.set(screenY = 0.05f, screenHeight = 0.25f, pixelX = 1f, pixelWidth = -2f) } override fun onLeftClick(xPercent: Float, yPercent: Float) { super.onLeftClick(xPercent, yPercent) cycle(1) hoverTime = 0f } override fun onRightClick(xPercent: Float, yPercent: Float) { super.onRightClick(xPercent, yPercent) cycle(-1) hoverTime = 0f } fun cycle(dir: Int) { val values = Background.backgrounds if (dir > 0) { val index = values.indexOf(GenericStage.backgroundImpl) + 1 GenericStage.backgroundImpl = if (index >= values.size) { values.first() } else { values[index] } } else if (dir < 0) { val index = values.indexOf(GenericStage.backgroundImpl) - 1 GenericStage.backgroundImpl = if (index < 0) { values.last() } else { values[index] } } numberLabel.text = "${values.indexOf(GenericStage.backgroundImpl) + 1}/${values.size}" nameLabel.text = "${Background.backgroundMapByBg[GenericStage.backgroundImpl]?.name}" main.preferences.putString(PreferenceKeys.BACKGROUND, GenericStage.backgroundImpl.id).flush() } }.apply { this.addLabel(ImageLabel(palette, this, this.stage).apply { this.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_palette")) this.renderType = ImageLabel.ImageRendering.ASPECT_RATIO this.location.set(screenY = 0.3f, screenHeight = 0.7f, screenWidth = 0.5f) }) this.addLabel(numberLabel) this.addLabel(nameLabel) this.cycle(0) this.location.set(screenX = 0.85f, screenWidth = 1f - 0.85f) } stage.bottomStage.elements += menuBgButton onlineLabel = object : TextLabel<InfoScreen>(palette, stage.bottomStage, stage.bottomStage) { var last = Int.MIN_VALUE init { Localization.addListener { last = Int.MIN_VALUE } } override fun render(screen: InfoScreen, batch: SpriteBatch, shapeRenderer: ShapeRenderer) { val current = main.liveUsers if (last != current) { last = current this.text = if (current > 0) Localization["screen.info.online", current] else "" } super.render(screen, batch, shapeRenderer) } }.apply { this.isLocalizationKey = false this.textAlign = Align.right this.fontScaleMultiplier = 0.5f this.alignment = Align.bottomRight this.location.set(screenHeight = 1f / 3, screenWidth = this.stage.percentageOfWidth(this.stage.location.realHeight)) this.location.set(screenX = this.location.screenWidth + 0.025f * 1.25f, screenY = -0.75f + 1f / 3) } stage.bottomStage.elements += onlineLabel stage.bottomStage.elements += object : Button<InfoScreen>(palette, stage.bottomStage, stage.bottomStage) { override var visible: Boolean = true get() = field && main.liveUsers > 0 && !RHRE3.noOnlineCounter override fun onLeftClick(xPercent: Float, yPercent: Float) { super.onLeftClick(xPercent, yPercent) if (!visible) return main.screen = OnlineCounterScreen(main, onlineLabel.text) } }.apply { this.addLabel(ImageLabel(palette, this, this.stage).apply { this.renderType = ImageLabel.ImageRendering.ASPECT_RATIO this.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_history")) }) this.alignment = Align.bottomRight this.location.set(screenHeight = onlineLabel.location.screenHeight, screenY = onlineLabel.location.screenY) this.location.set(screenX = 0.025f, screenWidth = 0.025f) } infoStage = InfoStage(stage.centreStage, stage.camera, this) settingsStage = SettingsStage(stage.centreStage, stage.camera, this) extrasStage = ExtrasStage(stage.centreStage, stage.camera, this) val padding = 0.025f val buttonHeight = 0.1f val fontScale = 0.75f stage.centreStage.also { centre -> val buttonWidth = 0.35f headingLabel = TextLabel(palette, centre, centre).apply { val width = 1f - (buttonWidth * 1.85f) this.location.set(screenX = 0.5f - width / 2f, screenY = 1f - (padding + buttonHeight * 0.8f), screenWidth = width, screenHeight = buttonHeight) this.isLocalizationKey = true this.text = "screen.info.settings" } centre.elements += headingLabel leftPageButton = PageChangeButton(palette, centre, centre, false).apply { this.location.set(0f, 1f - (padding + buttonHeight * 0.8f), buttonWidth * 0.75f, buttonHeight) } centre.elements += leftPageButton rightPageButton = PageChangeButton(palette, centre, centre, true).apply { this.location.set(1f - (buttonWidth * 0.75f), 1f - (padding + buttonHeight * 0.8f), buttonWidth * 0.75f, buttonHeight) } centre.elements += rightPageButton } pageStages = listOf(infoStage, settingsStage, extrasStage).onEach { stage.centreStage.elements += it } stage.updatePositions() currentPage = currentPage // force update updateSeePartners() } private fun updateSeePartners() { shouldSeePartners = main.preferences.getInteger(PreferenceKeys.VIEWED_PARTNERS_VERSION, 0) < PartnersScreen.PARTNERS_VERSION } override fun render(delta: Float) { super.render(delta) if (backgroundOnly || menuBgButton.hoverTime >= 1.5f) { val batch = main.batch batch.begin() GenericStage.backgroundImpl.render(main.defaultCamera, batch, main.shapeRenderer, 0f) batch.end() } } override fun renderUpdate() { super.renderUpdate() if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE) && stage.backButton.visible && stage.backButton.enabled) { stage.onBackButtonClick() } else if (!Gdx.input.isShiftDown() && !Gdx.input.isAltDown()) { if (Gdx.input.isControlDown()) { if (Gdx.input.isKeyJustPressed(Input.Keys.A)) { main.screen = ScreenRegistry.getNonNull("advancedOptions") } } else { if (Gdx.input.isKeyJustPressed(Input.Keys.A) || Gdx.input.isKeyJustPressed(Input.Keys.LEFT)) { if (leftPageButton.visible) leftPageButton.onLeftClick(0f, 0f) } if (Gdx.input.isKeyJustPressed(Input.Keys.D) || Gdx.input.isKeyJustPressed(Input.Keys.RIGHT)) { if (rightPageButton.visible) rightPageButton.onLeftClick(0f, 0f) } } } else if (Gdx.input.isKeyJustPressed(Input.Keys.Q) && Gdx.input.isKeyPressed(Toolboks.DEBUG_KEY)) { backgroundOnly = !backgroundOnly } } override fun show() { super.show() infoStage.show() extrasStage.show() settingsStage.show() DiscordHelper.updatePresence(PresenceState.InSettings) updateSeePartners() } override fun hide() { super.hide() settingsStage.hide() // Analytics if (settingsStage.didChangeSettings) { val map: Map<String, *> = preferences.get() AnalyticsHandler.track("Exit Info and Settings", mapOf( "settings" to PreferenceKeys.allSettingsKeys.associate { it.replace("settings_", "") to (map[it] ?: "null") } + mapOf("background" to map[PreferenceKeys.BACKGROUND], "defaultMixer" to BeadsSoundSystem.getDefaultMixer().mixerInfo.name) )) } settingsStage.didChangeSettings = false } override fun getDebugString(): String? { return "CTRL+A - Open Advanced Options\n${Input.Keys.toString(Toolboks.DEBUG_KEY)}+Q - Render background on top" } override fun tickUpdate() { } override fun dispose() { } inner class PageChangeButton(palette: UIPalette, parent: UIElement<InfoScreen>, stage: Stage<InfoScreen>, right: Boolean) : Button<InfoScreen>(palette, parent, stage) { var targetPage: Page = Page.INFO val label: TextLabel<InfoScreen> = TextLabel(palette, this, this.stage).apply { this.location.set(screenX = 0.15f, screenWidth = 0.85f) this.isLocalizationKey = true this.textAlign = if (right) Align.right else Align.left this.fontScaleMultiplier = 0.75f this.text = "screen.info.settings" } init { addLabel(label) if (right) { label.location.screenX = 0f addLabel(TextLabel(palette, this, this.stage).apply { this.location.set(screenX = 0.85f, screenWidth = 0.15f) this.isLocalizationKey = false this.text = "\uE14A" }) } else { addLabel(TextLabel(palette, this, this.stage).apply { this.location.set(screenX = 0f, screenWidth = 0.15f) this.isLocalizationKey = false this.text = "\uE149" }) } leftClickAction = { _, _ -> currentPage = targetPage } } } }
gpl-3.0
29206b18072ecb3fe7a2ea28eb84c0c4
40.677725
169
0.595156
4.525733
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-result/src/main/kotlin/slatekit/results/builders/Outcomes.kt
1
1360
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A Kotlin Tool-Kit for Server + Android * </slate_header> */ package slatekit.results.builders import slatekit.results.* /** * Builds [Result] with [Failure] error type of [Err] */ interface OutcomeBuilder : Builder<Err> { override fun errorFromEx(ex: Throwable, defaultStatus: Status): Err = Err.ex(ex) override fun errorFromStr(msg: String?, defaultStatus: Status): Err = Err.of(msg ?: defaultStatus.desc) override fun errorFromErr(err: Err, defaultStatus: Status): Err = err } /** * Builds [Result] with [Failure] error type of [Err] */ object Outcomes : OutcomeBuilder { /** * Build a Outcome<T> ( type alias ) for Result<T,Err> using the supplied function */ @JvmStatic inline fun <T> of(f: () -> T): Outcome<T> = build(f, { ex -> Err.ex(ex) }) /** * Build a Result<T,E> using the supplied callback and error handler */ @JvmStatic inline fun <T> build(f: () -> T, onError: (Throwable) -> Err): Outcome<T> = try { val data = f() Success(data) } catch (e: Throwable) { Failure(onError(e)) } }
apache-2.0
ce56c0765d88a0f9a05c320fb7b69fac
27.333333
107
0.626471
3.523316
false
false
false
false
code-helix/slatekit
src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_Info.kt
1
2360
/** <slate_header> author: Kishore Reddy url: www.github.com/code-helix/slatekit copyright: 2015 Kishore Reddy license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md desc: A tool-kit, utility library and server-backend usage: Please refer to license on github for more info. </slate_header> */ package slatekit.examples //<doc:import_required> import slatekit.common.info.About import slatekit.common.info.Host import slatekit.common.info.Lang //</doc:import_required> //<doc:import_examples> import slatekit.results.Try import slatekit.results.Success //</doc:import_examples> class Example_Info : Command("info") { override fun execute(request: CommandRequest) : Try<Any> { //<doc:examples> // CASE 1: Get the host info val host = Host.local() host.each { name, value -> println( "$name : $value" ) } println() // CASE 2: Get the Lang runtime info ( java version, kotlin version etc ) val lang = Lang.kotlin() lang.each { name, value -> println( "$name : $value" ) } println() // CASE 3: Set up info about your application. val app = About( area = "product1", name = "My sample app", desc = "Sample app using Slate Kit", company = "slatekit", region = "usa.ny", tags = "api,slate,app", url = "http://products.myapp.com", contact = "[email protected]", examples = "myapp.exe -env=dev -level=info" ) app.log( { name, value -> println( "${name} : ${value}" ) } ) //</doc:examples> return Success("") } } /* //<doc:output> {{< highlight kotlin >}} // HOST INFO api : KRPC1 ip : Windows 10 origin : local arch : amd64 version : 10.0 ext1 : C:/Users/kv/AppData/Local/Temp/ // LANGUAGE INFO api : kotlin home : C:/Tools/Java/jdk1.8.0_91/jre versionNum : 2.11.7 version : 1.8.0_91 origin : local ext1 : // STARTUP INFO args : Some([Ljava.lang.String;11c20519) log : {app}-{env}-{date}.log config : {app}.config env : qa // APP INFO api : My sample app desc : Sample app using Slate Kit group : product division region : usa.ny url : "http://products.myapp.com" contact : [email protected] version : 1.0.1.3 tags : api,slate,app examples : myapp.exe -env=dev -level=info {{< /highlight >}} //</doc:output> * */
apache-2.0
38c1a3f46013ac7d1316dea869625d55
22.366337
77
0.627966
3.323944
false
false
false
false
leafclick/intellij-community
xml/impl/src/com/intellij/ide/browsers/BrowserLauncherImpl.kt
1
3073
// 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.ide.browsers import com.intellij.ide.IdeBundle import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.Disposable import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.showOkNoDialog import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.registry.Registry import com.intellij.util.Urls import org.jetbrains.ide.BuiltInServerManager class BrowserLauncherImpl : BrowserLauncherAppless() { override fun getEffectiveBrowser(browser: WebBrowser?): WebBrowser? { var effectiveBrowser = browser if (browser == null) { // https://youtrack.jetbrains.com/issue/WEB-26547 val browserManager = WebBrowserManager.getInstance() if (browserManager.getDefaultBrowserPolicy() == DefaultBrowserPolicy.FIRST) { effectiveBrowser = browserManager.firstActiveBrowser } } return effectiveBrowser } override fun signUrl(url: String): String { @Suppress("NAME_SHADOWING") var url = url @Suppress("NAME_SHADOWING") val serverManager = BuiltInServerManager.getInstance() val parsedUrl = Urls.parse(url, false) if (parsedUrl != null && serverManager.isOnBuiltInWebServer(parsedUrl)) { if (Registry.`is`("ide.built.in.web.server.activatable", false)) { PropertiesComponent.getInstance().setValue("ide.built.in.web.server.active", true) } url = serverManager.addAuthToken(parsedUrl).toExternalForm() } return url } override fun openWithExplicitBrowser(url: String, browserPath: String?, project: Project?) { val browserManager = WebBrowserManager.getInstance() if (browserManager.getDefaultBrowserPolicy() == DefaultBrowserPolicy.FIRST) { browserManager.firstActiveBrowser?.let { browse(url, it, project) return } } else if (SystemInfo.isMac && "open" == browserPath) { browserManager.firstActiveBrowser?.let { browseUsingPath(url, null, it, project) return } } super.openWithExplicitBrowser(url, browserPath, project) } override fun showError(error: String?, browser: WebBrowser?, project: Project?, title: String?, fix: (() -> Unit)?) { AppUIExecutor.onUiThread().expireWith(project ?: Disposable {}).submit { if (showOkNoDialog(title ?: IdeBundle.message("browser.error"), error ?: IdeBundle.message("unknown.error"), project, okText = IdeBundle.message("button.fix"), noText = Messages.getOkButton())) { val browserSettings = BrowserSettings() if (ShowSettingsUtil.getInstance().editConfigurable(project, browserSettings, browser?.let { Runnable { browserSettings.selectBrowser(it) } })) { fix?.invoke() } } } } }
apache-2.0
c16908172a366b1a2bb0ba0acb88f24c
39.447368
153
0.711032
4.447178
false
false
false
false
JuliusKunze/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/optimizations/DataFlowIR.kt
1
22704
/* * Copyright 2010-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. */ package org.jetbrains.kotlin.backend.konan.optimizations import org.jetbrains.kotlin.backend.common.descriptors.allParameters import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.backend.konan.descriptors.externalOrIntrinsic import org.jetbrains.kotlin.backend.konan.descriptors.isAbstract import org.jetbrains.kotlin.backend.konan.descriptors.isInterface import org.jetbrains.kotlin.backend.konan.isObjCClass import org.jetbrains.kotlin.backend.konan.llvm.functionName import org.jetbrains.kotlin.backend.konan.llvm.isExported import org.jetbrains.kotlin.backend.konan.llvm.localHash import org.jetbrains.kotlin.backend.konan.llvm.symbolName import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.declarations.IrClass import org.jetbrains.kotlin.ir.declarations.IrField import org.jetbrains.kotlin.ir.declarations.IrFunction import org.jetbrains.kotlin.ir.declarations.IrModuleFragment import org.jetbrains.kotlin.ir.expressions.IrCall import org.jetbrains.kotlin.ir.expressions.IrFunctionAccessExpression import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.constants.ConstantValue import org.jetbrains.kotlin.resolve.constants.IntValue import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.immediateSupertypes internal object DataFlowIR { abstract class Type { // Special marker type forbidding devirtualization on its instances. object Virtual : Declared(false, true) class External(val hash: Long, val name: String? = null) : Type() { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is External) return false return hash == other.hash } override fun hashCode(): Int { return hash.hashCode() } override fun toString(): String { return "ExternalType(hash='$hash', name='$name')" } } abstract class Declared(val isFinal: Boolean, val isAbstract: Boolean) : Type() { val superTypes = mutableListOf<Type>() val vtable = mutableListOf<FunctionSymbol>() val itable = mutableMapOf<Long, FunctionSymbol>() } class Public(val hash: Long, isFinal: Boolean, isAbstract: Boolean, val name: String? = null) : Declared(isFinal, isAbstract) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Public) return false return hash == other.hash } override fun hashCode(): Int { return hash.hashCode() } override fun toString(): String { return "PublicType(hash='$hash', name='$name')" } } class Private(val index: Int, isFinal: Boolean, isAbstract: Boolean, val name: String? = null) : Declared(isFinal, isAbstract) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Private) return false return index == other.index } override fun hashCode(): Int { return index } override fun toString(): String { return "PrivateType(index=$index, name='$name')" } } } class Module(val descriptor: ModuleDescriptor) { var numberOfFunctions = 0 } abstract class FunctionSymbol(val numberOfParameters: Int, val name: String?) { class External(val hash: Long, numberOfParameters: Int, val escapes: Int?, val pointsTo: IntArray?, name: String? = null) : FunctionSymbol(numberOfParameters, name) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is External) return false return hash == other.hash } override fun hashCode(): Int { return hash.hashCode() } override fun toString(): String { return "ExternalFunction(hash='$hash', name='$name', escapes='$escapes', pointsTo='${pointsTo?.contentToString()}')" } } abstract class Declared(numberOfParameters: Int, val module: Module, val symbolTableIndex: Int, name: String?) : FunctionSymbol(numberOfParameters, name) class Public(val hash: Long, numberOfParameters: Int, module: Module, symbolTableIndex: Int, name: String? = null) : Declared(numberOfParameters, module, symbolTableIndex, name) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Public) return false return hash == other.hash } override fun hashCode(): Int { return hash.hashCode() } override fun toString(): String { return "PublicFunction(hash='$hash', name='$name')" } } class Private(val index: Int, numberOfParameters: Int, module: Module, symbolTableIndex: Int, name: String? = null) : Declared(numberOfParameters, module, symbolTableIndex, name) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Private) return false return index == other.index } override fun hashCode(): Int { return index } override fun toString(): String { return "PrivateFunction(index=$index, name='$name')" } } } data class Field(val type: Type?, val hash: Long, val name: String? = null) class Edge(val castToType: Type?) { lateinit var node: Node constructor(node: Node, castToType: Type?) : this(castToType) { this.node = node } } sealed class Node { class Parameter(val index: Int) : Node() class Const(val type: Type) : Node() open class Call(val callee: FunctionSymbol, val arguments: List<Edge>, val returnType: Type, open val callSite: IrFunctionAccessExpression?) : Node() class StaticCall(callee: FunctionSymbol, arguments: List<Edge>, returnType: Type, val receiverType: Type?, callSite: IrFunctionAccessExpression?) : Call(callee, arguments, returnType, callSite) class NewObject(constructor: FunctionSymbol, arguments: List<Edge>, type: Type, override val callSite: IrCall?) : Call(constructor, arguments, type, callSite) open class VirtualCall(callee: FunctionSymbol, arguments: List<Edge>, returnType: Type, val receiverType: Type, override val callSite: IrCall?) : Call(callee, arguments, returnType, callSite) class VtableCall(callee: FunctionSymbol, receiverType: Type, val calleeVtableIndex: Int, arguments: List<Edge>, returnType: Type, callSite: IrCall?) : VirtualCall(callee, arguments, returnType, receiverType, callSite) class ItableCall(callee: FunctionSymbol, receiverType: Type, val calleeHash: Long, arguments: List<Edge>, returnType: Type, callSite: IrCall?) : VirtualCall(callee, arguments, returnType, receiverType, callSite) class Singleton(val type: Type, val constructor: FunctionSymbol?) : Node() class FieldRead(val receiver: Edge?, val field: Field) : Node() class FieldWrite(val receiver: Edge?, val field: Field, val value: Edge) : Node() class Variable(values: List<Edge>, val temp: Boolean) : Node() { val values = mutableListOf<Edge>().also { it += values } } } class FunctionBody(val nodes: List<Node>, val returns: Node.Variable, val throws: Node.Variable) class Function(val symbol: FunctionSymbol, val isGlobalInitializer: Boolean, val numberOfParameters: Int, val body: FunctionBody) { fun debugOutput() { println("FUNCTION $symbol") println("Params: $numberOfParameters") val ids = body.nodes.withIndex().associateBy({ it.value }, { it.index }) body.nodes.forEach { println(" NODE #${ids[it]!!}") printNode(it, ids) } println(" RETURNS") printNode(body.returns, ids) } companion object { fun printNode(node: Node, ids: Map<Node, Int>) = print(nodeToString(node, ids)) fun nodeToString(node: Node, ids: Map<Node, Int>) = when (node) { is Node.Const -> " CONST ${node.type}\n" is Node.Parameter -> " PARAM ${node.index}\n" is Node.Singleton -> " SINGLETON ${node.type}\n" is Node.StaticCall -> { val result = StringBuilder() result.appendln(" STATIC CALL ${node.callee}") node.arguments.forEach { result.append(" ARG #${ids[it.node]!!}") if (it.castToType == null) result.appendln() else result.appendln(" CASTED TO ${it.castToType}") } result.toString() } is Node.VtableCall -> { val result = StringBuilder() result.appendln(" VIRTUAL CALL ${node.callee}") result.appendln(" RECEIVER: ${node.receiverType}") result.appendln(" VTABLE INDEX: ${node.calleeVtableIndex}") node.arguments.forEach { result.append(" ARG #${ids[it.node]!!}") if (it.castToType == null) result.appendln() else result.appendln(" CASTED TO ${it.castToType}") } result.toString() } is Node.ItableCall -> { val result = StringBuilder() result.appendln(" INTERFACE CALL ${node.callee}") result.appendln(" RECEIVER: ${node.receiverType}") result.appendln(" METHOD HASH: ${node.calleeHash}") node.arguments.forEach { result.append(" ARG #${ids[it.node]!!}") if (it.castToType == null) result.appendln() else result.appendln(" CASTED TO ${it.castToType}") } result.toString() } is Node.NewObject -> { val result = StringBuilder() result.appendln(" NEW OBJECT ${node.callee}") result.appendln(" TYPE ${node.returnType}") node.arguments.forEach { result.append(" ARG #${ids[it.node]!!}") if (it.castToType == null) result.appendln() else result.appendln(" CASTED TO ${it.castToType}") } result.toString() } is Node.FieldRead -> { val result = StringBuilder() result.appendln(" FIELD READ ${node.field}") result.append(" RECEIVER #${node.receiver?.node?.let { ids[it]!! } ?: "null"}") if (node.receiver?.castToType == null) result.appendln() else result.appendln(" CASTED TO ${node.receiver.castToType}") result.toString() } is Node.FieldWrite -> { val result = StringBuilder() result.appendln(" FIELD WRITE ${node.field}") result.append(" RECEIVER #${node.receiver?.node?.let { ids[it]!! } ?: "null"}") if (node.receiver?.castToType == null) result.appendln() else result.appendln(" CASTED TO ${node.receiver.castToType}") print(" VALUE #${ids[node.value.node]!!}") if (node.value.castToType == null) result.appendln() else result.appendln(" CASTED TO ${node.value.castToType}") result.toString() } is Node.Variable -> { val result = StringBuilder() result.appendln(" ${if (node.temp) "TEMP VAR" else "VARIABLE"} ") node.values.forEach { result.append(" VAL #${ids[it.node]!!}") if (it.castToType == null) result.appendln() else result.appendln(" CASTED TO ${it.castToType}") } result.toString() } else -> { " UNKNOWN: ${node::class.java}\n" } } } } class SymbolTable(val context: Context, val irModule: IrModuleFragment, val module: Module) { private val TAKE_NAMES = false // Take fqNames for all functions and types (for debug purposes). private inline fun takeName(block: () -> String) = if (TAKE_NAMES) block() else null val classMap = mutableMapOf<ClassDescriptor, Type>() val functionMap = mutableMapOf<CallableDescriptor, FunctionSymbol>() private val NAME_ESCAPES = Name.identifier("Escapes") private val NAME_POINTS_TO = Name.identifier("PointsTo") private val FQ_NAME_KONAN = FqName.fromSegments(listOf("konan")) private val FQ_NAME_ESCAPES = FQ_NAME_KONAN.child(NAME_ESCAPES) private val FQ_NAME_POINTS_TO = FQ_NAME_KONAN.child(NAME_POINTS_TO) private val konanPackage = context.builtIns.builtInsModule.getPackage(FQ_NAME_KONAN).memberScope private val escapesAnnotationDescriptor = konanPackage.getContributedClassifier( NAME_ESCAPES, NoLookupLocation.FROM_BACKEND) as ClassDescriptor private val escapesWhoDescriptor = escapesAnnotationDescriptor.unsubstitutedPrimaryConstructor!!.valueParameters.single() private val pointsToAnnotationDescriptor = konanPackage.getContributedClassifier( NAME_POINTS_TO, NoLookupLocation.FROM_BACKEND) as ClassDescriptor private val pointsToOnWhomDescriptor = pointsToAnnotationDescriptor.unsubstitutedPrimaryConstructor!!.valueParameters.single() var privateTypeIndex = 0 var privateFunIndex = 0 var couldBeCalledVirtuallyIndex = 0 init { irModule.accept(object : IrElementVisitorVoid { override fun visitElement(element: IrElement) { element.acceptChildrenVoid(this) } override fun visitFunction(declaration: IrFunction) { declaration.body?.let { mapFunction(declaration.descriptor) } } override fun visitField(declaration: IrField) { declaration.initializer?.let { mapFunction(declaration.descriptor) } } override fun visitClass(declaration: IrClass) { declaration.acceptChildrenVoid(this) mapClass(declaration.descriptor) } }, data = null) } private fun ClassDescriptor.isFinal() = modality == Modality.FINAL && kind != ClassKind.ENUM_CLASS fun mapClass(descriptor: ClassDescriptor): Type { // Do not try to devirtualize ObjC classes. if (descriptor.module.name == Name.special("<forward declarations>") || descriptor.isObjCClass()) return Type.Virtual val name = descriptor.fqNameSafe.asString() if (descriptor.module != irModule.descriptor) return classMap.getOrPut(descriptor) { Type.External(name.localHash.value, takeName { name }) } classMap[descriptor]?.let { return it } val isFinal = descriptor.isFinal() val isAbstract = descriptor.isAbstract() val type = if (descriptor.isExported()) Type.Public(name.localHash.value, isFinal, isAbstract, takeName { name }) else Type.Private(privateTypeIndex++, isFinal, isAbstract, takeName { name }) if (!descriptor.isInterface) { val vtableBuilder = context.getVtableBuilder(descriptor) type.vtable += vtableBuilder.vtableEntries.map { mapFunction(it.getImplementation(context)) } if (!isAbstract) { vtableBuilder.methodTableEntries.forEach { type.itable.put( it.overriddenDescriptor.functionName.localHash.value, mapFunction(it.getImplementation(context)) ) } } } classMap.put(descriptor, type) type.superTypes += descriptor.defaultType.immediateSupertypes().map { mapType(it) } return type } fun mapType(type: KotlinType) = mapClass(type.erasure().single().constructor.declarationDescriptor as ClassDescriptor) // TODO: use from LlvmDeclarations. private fun getFqName(descriptor: DeclarationDescriptor): FqName { if (descriptor is PackageFragmentDescriptor) { return descriptor.fqName } val containingDeclaration = descriptor.containingDeclaration val parent = if (containingDeclaration != null) { getFqName(containingDeclaration) } else { FqName.ROOT } val localName = descriptor.name return parent.child(localName) } private val FunctionDescriptor.internalName get() = getFqName(this).asString() + "#internal" fun mapFunction(descriptor: CallableDescriptor) = descriptor.original.let { functionMap.getOrPut(it) { when (it) { is PropertyDescriptor -> FunctionSymbol.Private(privateFunIndex++, 0, module, -1, takeName { "${it.symbolName}_init" }) is FunctionDescriptor -> { val name = if (it.isExported()) it.symbolName else it.internalName val numberOfParameters = it.allParameters.size + if (it.isSuspend) 1 else 0 if (it.module != irModule.descriptor || it.externalOrIntrinsic()) { val escapesAnnotation = it.annotations.findAnnotation(FQ_NAME_ESCAPES) val pointsToAnnotation = it.annotations.findAnnotation(FQ_NAME_POINTS_TO) @Suppress("UNCHECKED_CAST") val escapesBitMask = (escapesAnnotation?.allValueArguments?.get(escapesWhoDescriptor.name) as? ConstantValue<Int>)?.value @Suppress("UNCHECKED_CAST") val pointsToBitMask = (pointsToAnnotation?.allValueArguments?.get(pointsToOnWhomDescriptor.name) as? ConstantValue<List<IntValue>>)?.value FunctionSymbol.External(name.localHash.value, numberOfParameters, escapesBitMask, pointsToBitMask?.let { it.map { it.value }.toIntArray() }, takeName { name }) } else { val isAbstract = it.modality == Modality.ABSTRACT val classDescriptor = it.containingDeclaration as? ClassDescriptor val placeToFunctionsTable = !isAbstract && it !is ConstructorDescriptor && classDescriptor != null && classDescriptor.kind != ClassKind.ANNOTATION_CLASS && (it.isOverridableOrOverrides || it.name.asString().contains("<bridge-") || !classDescriptor.isFinal()) if (placeToFunctionsTable) ++module.numberOfFunctions val symbolTableIndex = if (!placeToFunctionsTable) -1 else couldBeCalledVirtuallyIndex++ if (it.isExported()) FunctionSymbol.Public(name.localHash.value, numberOfParameters, module, symbolTableIndex, takeName { name }) else FunctionSymbol.Private(privateFunIndex++, numberOfParameters, module, symbolTableIndex, takeName { name }) } } else -> error("Unknown descriptor: $it") } } } } }
apache-2.0
ac485d4dcad5c3ec58d667a82284fbe4
43.607073
166
0.559109
5.423794
false
false
false
false
room-15/ChatSE
app/src/main/java/com/tristanwiley/chatse/login/LoginActivity.kt
1
3292
package com.tristanwiley.chatse.login import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.inputmethod.EditorInfo import android.widget.Toast import com.tristanwiley.chatse.R import com.tristanwiley.chatse.chat.ChatActivity import com.tristanwiley.chatse.extensions.showIf import kotlinx.android.synthetic.main.activity_login.* class LoginActivity : AppCompatActivity(), LoginView { private lateinit var presenter: LoginPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) presenter = LoginPresenter() beta_text.setOnClickListener { presenter.onBetaClicked() } fab_submit.setOnClickListener { val email = login_email.text.toString() val password = login_password.text.toString() presenter.onLoginClicked(email, password) } login_password.setOnEditorActionListener { _, actionId, _ -> when (actionId) { EditorInfo.IME_ACTION_DONE -> { val email = login_email.text.toString() val password = login_password.text.toString() presenter.onFormFilledOut(email, password) false } else -> false } } presenter.attachView(this) } override fun setVersionText(text: String) { login_tv_version.text = text } override fun setEmailText(text: String) { login_email.setText(text) } override fun navigateToGithubPage() { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/room-15/ChatSE/"))) } override fun setLoginEnabled(isEnabled: Boolean) { fab_submit.isClickable = isEnabled } override fun showEmailEmptyError() { login_email.error = getString(R.string.err_blank_email) } override fun showEmailInvalidError() { login_email.error = getString(R.string.err_invalid_email) } override fun showPasswordError() { login_password.error = getString(R.string.err_blank_password) } override fun hideFormErrors() { login_email.error = null login_password.error = null } override fun navigateToChat() { val intent = Intent(this@LoginActivity, ChatActivity::class.java) startActivity(intent) finish() } override fun showLogInError() { Toast.makeText(this@LoginActivity, "Failed to log in, try again!", Toast.LENGTH_LONG).show() } override fun setLoginInProgressVisibility(isVisible: Boolean) { progress_bar_logging_in.showIf { isVisible } } override fun onDestroy() { presenter.detachView() super.onDestroy() } } interface LoginView { fun setVersionText(text: String) fun setEmailText(text: String) fun navigateToGithubPage() fun setLoginEnabled(isEnabled: Boolean) fun showEmailEmptyError() fun showEmailInvalidError() fun showPasswordError() fun hideFormErrors() fun setLoginInProgressVisibility(isVisible: Boolean) fun showLogInError() fun navigateToChat() }
apache-2.0
6a4837fed241571733e1066206fe6bb8
28.392857
100
0.664338
4.578581
false
false
false
false
jotomo/AndroidAPS
app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_RefillTest.kt
1
879
package info.nightscout.androidaps.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) class DanaRS_Packet_History_RefillTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { if (it is DanaRS_Packet) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } if (it is DanaRS_Packet_History_Refill) { it.rxBus = rxBus } } } @Test fun runTest() { val packet = DanaRS_Packet_History_Refill(packetInjector, System.currentTimeMillis()) Assert.assertEquals("REVIEW__REFILL", packet.friendlyName) } }
agpl-3.0
174d273aebed4900598f210b8252eea8
29.344828
93
0.67008
4.725806
false
true
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/controller/usecases/Debug.kt
1
2356
package com.cout970.modeler.controller.usecases import com.cout970.modeler.Debugger import com.cout970.modeler.controller.tasks.ITask import com.cout970.modeler.controller.tasks.ModifyGui import com.cout970.modeler.gui.CSSTheme import com.cout970.modeler.gui.leguicomp.ProfilerDiagram import com.cout970.modeler.gui.leguicomp.key import com.cout970.modeler.render.RenderManager /** * Created by cout970 on 2017/07/20. */ @UseCase("debug") private fun onDebug(): ITask = ModifyGui { Debugger.debug { //reload gui CSSTheme.loadCss() gui.root.reRender() gui.resources.reload(resourceLoader) gui.root.loadResources(gui.resources) // pushNotification("Debug", "This is a debug message that is supposed to be long enough to force an overflow in the event box, even when there will never be messages that long in the program") // Test import system // val properties = ImportProperties( // "path/to/file//small_steam_engine.tbl", // ImportFormat.TBL, // flipUV = false, // append = false // ) // taskHistory.processTask(TaskImportModel(projectManager.model, properties)) // Test export system // val properties = GltfExportProperties("debug/test.gltf") // taskHistory.processTask(TaskExportModel(projectManager.model, properties)) } } @UseCase("debug.toggle.dynamic") private fun toggleDynamicDebug(rm: RenderManager): ITask = ModifyGui { Debugger.DYNAMIC_DEBUG = !Debugger.DYNAMIC_DEBUG rm.guiRenderer.context.isDebugEnabled = Debugger.DYNAMIC_DEBUG } @UseCase("debug.show.profiling") private fun showDebugProfiling(): ITask = ModifyGui { Debugger.showProfiling = !Debugger.showProfiling } @UseCase("debug.changeColors") private fun changeDebugColors(): ITask = ModifyGui { ProfilerDiagram.ProfilerDiagramRenderer.colors = ProfilerDiagram.ProfilerDiagramRenderer.generateColors() } @UseCase("debug.gc") private fun forceGC(): ITask = ModifyGui { System.gc() } @UseCase("debug.print.focused") private fun printFocusedComp(): ITask = ModifyGui { Debugger.debug { val ctx = renderManager.guiRenderer.context ctx.focusedGui?.let { gui -> println("${gui::class.java.simpleName}(${gui.key})") println(gui) } } }
gpl-3.0
71297c93f0443e790de76ce995c02f97
31.287671
200
0.697793
3.973019
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewHolders/ShopItemViewHolder.kt
1
4430
package com.habitrpg.android.habitica.ui.viewHolders import android.content.Context import android.graphics.drawable.BitmapDrawable import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.facebook.drawee.view.SimpleDraweeView import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.models.shops.ShopItem import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils import com.habitrpg.android.habitica.ui.helpers.bindView import com.habitrpg.android.habitica.ui.views.CurrencyView import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import com.habitrpg.android.habitica.ui.views.shops.PurchaseDialog class ShopItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener { private val imageView: SimpleDraweeView by bindView(itemView, R.id.imageView) private val buyButton: View by bindView(itemView, R.id.buyButton) private val priceLabel: CurrencyView by bindView(itemView, R.id.priceLabel) private val unlockLabel: TextView by bindView(itemView, R.id.unlockLabel) private val itemDetailIndicator: TextView by bindView(itemView, R.id.item_detail_indicator) private val pinIndicator: ImageView by bindView(itemView, R.id.pin_indicator) var shopIdentifier: String? = null private var item: ShopItem? = null private var context: Context = itemView.context private var lockedDrawable = BitmapDrawable(context.resources, HabiticaIconsHelper.imageOfItemIndicatorLocked()) private var limitedDrawable = BitmapDrawable(context.resources, HabiticaIconsHelper.imageOfItemIndicatorLimited()) private var countDrawable = BitmapDrawable(context.resources, HabiticaIconsHelper.imageOfItemIndicatorNumber()) var purchaseCardAction: ((ShopItem) -> Unit)? = null var itemCount = 0 set(value) { field = value if (value > 0) { itemDetailIndicator.text = value.toString() itemDetailIndicator.background = countDrawable itemDetailIndicator.visibility = View.VISIBLE } } var isPinned = false set(value) { field =value pinIndicator.visibility = if (isPinned) View.VISIBLE else View.GONE } init { itemView.setOnClickListener(this) itemView.isClickable = true pinIndicator.setImageBitmap(HabiticaIconsHelper.imageOfPinnedItem()) } fun bind(item: ShopItem, canBuy: Boolean) { this.item = item buyButton.visibility = View.VISIBLE DataBindingUtils.loadImage(this.imageView, item.imageName?.replace("_locked", "")) itemDetailIndicator.text = null itemDetailIndicator.visibility = View.GONE val lockedReason = item.shortLockedReason(context) if (!item.locked || lockedReason == null) { priceLabel.text = item.value.toString() priceLabel.currency = item.currency if (item.currency == null) { buyButton.visibility = View.GONE } priceLabel.visibility = View.VISIBLE unlockLabel.visibility = View.GONE if (item.locked) { itemDetailIndicator.background = lockedDrawable itemDetailIndicator.visibility = View.VISIBLE } } else { unlockLabel.text = lockedReason priceLabel.visibility = View.GONE unlockLabel.visibility = View.VISIBLE itemDetailIndicator.background = lockedDrawable itemDetailIndicator.visibility = View.VISIBLE } if (item.isLimited) { itemDetailIndicator.background = limitedDrawable itemDetailIndicator.visibility = View.VISIBLE } priceLabel.isLocked = item.locked || !canBuy } override fun onClick(view: View) { val item = item if (item != null && item.isValid) { val dialog = PurchaseDialog(context, HabiticaBaseApplication.userComponent, item) dialog.shopIdentifier = shopIdentifier dialog.isPinned = isPinned dialog.purchaseCardAction = { purchaseCardAction?.invoke(it) } dialog.show() } } fun hidePinIndicator() { pinIndicator.visibility = View.GONE } }
gpl-3.0
940cd5254f5b2e24798d663effb5b4dd
37.521739
118
0.696163
4.794372
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt
1
6980
package info.nightscout.androidaps.plugins.general.xdripStatusline import android.content.Context import android.content.Intent import android.os.Bundle import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.events.* import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import javax.inject.Inject import javax.inject.Singleton @Singleton class StatusLinePlugin @Inject constructor( injector: HasAndroidInjector, private val sp: SP, private val profileFunction: ProfileFunction, resourceHelper: ResourceHelper, private val context: Context, private val fabricPrivacy: FabricPrivacy, private val activePlugin: ActivePluginProvider, private val loopPlugin: LoopPlugin, private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, private val rxBus: RxBusWrapper, aapsLogger: AAPSLogger ) : PluginBase( PluginDescription() .mainType(PluginType.GENERAL) .pluginIcon((R.drawable.ic_blooddrop_48)) .pluginName(R.string.xdripstatus) .shortName(R.string.xdripstatus_shortname) .neverVisible(true) .preferencesId(R.xml.pref_xdripstatus) .description(R.string.description_xdrip_status_line), aapsLogger, resourceHelper, injector ) { private val disposable = CompositeDisposable() private var lastLoopStatus = false companion object { //broadcast related constants @Suppress("SpellCheckingInspection") private const val EXTRA_STATUSLINE = "com.eveningoutpost.dexdrip.Extras.Statusline" @Suppress("SpellCheckingInspection") private const val ACTION_NEW_EXTERNAL_STATUSLINE = "com.eveningoutpost.dexdrip.ExternalStatusline" @Suppress("SpellCheckingInspection", "unused") private const val RECEIVER_PERMISSION = "com.eveningoutpost.dexdrip.permissions.RECEIVE_EXTERNAL_STATUSLINE" } override fun onStart() { super.onStart() disposable += rxBus.toObservable(EventRefreshOverview::class.java) .observeOn(Schedulers.io()) .subscribe({ if (lastLoopStatus != loopPlugin.isEnabled(PluginType.LOOP)) sendStatus() }) { fabricPrivacy.logException(it) } disposable += rxBus.toObservable(EventExtendedBolusChange::class.java) .observeOn(Schedulers.io()) .subscribe({ sendStatus() }) { fabricPrivacy.logException(it) } disposable += rxBus.toObservable(EventTempBasalChange::class.java) .observeOn(Schedulers.io()) .subscribe({ sendStatus() }) { fabricPrivacy.logException(it) } disposable += rxBus.toObservable(EventTreatmentChange::class.java) .observeOn(Schedulers.io()) .subscribe({ sendStatus() }) { fabricPrivacy.logException(it) } disposable += rxBus.toObservable(EventConfigBuilderChange::class.java) .observeOn(Schedulers.io()) .subscribe({ sendStatus() }) { fabricPrivacy.logException(it) } disposable += rxBus.toObservable(EventAutosensCalculationFinished::class.java) .observeOn(Schedulers.io()) .subscribe({ sendStatus() }) { fabricPrivacy.logException(it) } disposable += rxBus.toObservable(EventPreferenceChange::class.java) .observeOn(Schedulers.io()) .subscribe({ sendStatus() }) { fabricPrivacy.logException(it) } disposable += rxBus.toObservable(EventAppInitialized::class.java) .observeOn(Schedulers.io()) .subscribe({ sendStatus() }) { fabricPrivacy.logException(it) } } override fun onStop() { super.onStop() disposable.clear() sendStatus() } private fun sendStatus() { var status = "" // sent once on disable val profile = profileFunction.getProfile() if (isEnabled(PluginType.GENERAL) && profile != null) { status = buildStatusString(profile) } //sendData val bundle = Bundle() bundle.putString(EXTRA_STATUSLINE, status) val intent = Intent(ACTION_NEW_EXTERNAL_STATUSLINE) intent.putExtras(bundle) intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) context.sendBroadcast(intent, null) } private fun buildStatusString(profile: Profile): String { var status = "" if (!loopPlugin.isEnabled(PluginType.LOOP)) { status += resourceHelper.gs(R.string.disabledloop) + "\n" lastLoopStatus = false } else if (loopPlugin.isEnabled(PluginType.LOOP)) { lastLoopStatus = true } //Temp basal val activeTemp = activePlugin.activeTreatments.getTempBasalFromHistory(System.currentTimeMillis()) if (activeTemp != null) { status += activeTemp.toStringShort() + " " } //IOB activePlugin.activeTreatments.updateTotalIOBTreatments() val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round() activePlugin.activeTreatments.updateTotalIOBTempBasals() val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round() status += DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U" if (sp.getBoolean(R.string.key_xdripstatus_detailediob, true)) { status += ("(" + DecimalFormatter.to2Decimal(bolusIob.iob) + "|" + DecimalFormatter.to2Decimal(basalIob.basaliob) + ")") } if (sp.getBoolean(R.string.key_xdripstatus_showbgi, true)) { val bgi = -(bolusIob.activity + basalIob.activity) * 5 * Profile.fromMgdlToUnits(profile.isfMgdl, profileFunction.getUnits()) status += " " + (if (bgi >= 0) "+" else "") + DecimalFormatter.to2Decimal(bgi) } // COB status += " " + iobCobCalculatorPlugin.getCobInfo(false, "StatusLinePlugin").generateCOBString() return status } }
agpl-3.0
d412f6787a083566aa623dcf0661b0fc
45.231788
137
0.708166
4.728997
false
false
false
false
alibaba/p3c
idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/ToggleProjectInspectionAction.kt
2
2366
/* * Copyright 1999-2017 Alibaba Group. * * 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.alibaba.p3c.idea.action import com.alibaba.p3c.idea.compatible.inspection.InspectionProfileService import com.alibaba.p3c.idea.compatible.inspection.Inspections import com.alibaba.p3c.idea.config.SmartFoxProjectConfig import com.alibaba.p3c.idea.i18n.P3cBundle import com.alibaba.p3c.idea.inspection.AliBaseInspection import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.components.ServiceManager import icons.P3cIcons /** * * Open or close inspections * @author caikang * @date 2017/03/14 4 */ class ToggleProjectInspectionAction : AnAction() { val textKey = "com.alibaba.p3c.idea.action.ToggleProjectInspectionAction.text" override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val smartFoxConfig = ServiceManager.getService(project, SmartFoxProjectConfig::class.java) val tools = Inspections.aliInspections(project) { it.tool is AliBaseInspection } InspectionProfileService.toggleInspection(project, tools, smartFoxConfig.projectInspectionClosed) smartFoxConfig.projectInspectionClosed = !smartFoxConfig.projectInspectionClosed } override fun update(e: AnActionEvent) { val project = e.project ?: return val smartFoxConfig = ServiceManager.getService(project, SmartFoxProjectConfig::class.java) e.presentation.text = if (smartFoxConfig.projectInspectionClosed) { e.presentation.icon = P3cIcons.PROJECT_INSPECTION_ON P3cBundle.getMessage("$textKey.open") } else { e.presentation.icon = P3cIcons.PROJECT_INSPECTION_OFF P3cBundle.getMessage("$textKey.close") } } }
apache-2.0
703b0b49c635d3a9a2040da000b58663
39.101695
105
0.744294
4.129145
false
true
false
false
mdaniel/intellij-community
plugins/kotlin/k2-fe10-bindings/src/org/jetbrains/kotlin/idea/fir/fe10/binding/ToDescriptorBindingContextValueProviders.kt
1
6050
// 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.fe10.binding import com.intellij.psi.PsiElement import org.jetbrains.kotlin.analysis.api.KtSymbolBasedReference import org.jetbrains.kotlin.analysis.api.symbols.KtConstructorSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionLikeSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtNamedClassOrObjectSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtValueParameterSymbol import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.fir.fe10.* import org.jetbrains.kotlin.idea.references.FE10_BINDING_RESOLVE_TO_DESCRIPTORS import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.util.slicedMap.ReadOnlySlice import org.jetbrains.kotlin.utils.addToStdlib.safeAs internal class ToDescriptorBindingContextValueProviders(bindingContext: KtSymbolBasedBindingContext) { private val context = bindingContext.context private val declarationToDescriptorGetters = mutableListOf<(PsiElement) -> DeclarationDescriptor?>() private inline fun <reified K : PsiElement, V : DeclarationDescriptor> KtSymbolBasedBindingContext.registerDeclarationToDescriptorByKey( slice: ReadOnlySlice<K, V>, crossinline getter: (K) -> V? ) { declarationToDescriptorGetters.add { if (it is K) getter(it) else null } registerGetterByKey(slice, { getter(it) }) } init { bindingContext.registerDeclarationToDescriptorByKey(BindingContext.CLASS, this::getClass) bindingContext.registerDeclarationToDescriptorByKey(BindingContext.TYPE_PARAMETER, this::getTypeParameter) bindingContext.registerDeclarationToDescriptorByKey(BindingContext.FUNCTION, this::getFunction) bindingContext.registerDeclarationToDescriptorByKey(BindingContext.CONSTRUCTOR, this::getConstructor) bindingContext.registerDeclarationToDescriptorByKey(BindingContext.VARIABLE, this::getVariable) bindingContext.registerDeclarationToDescriptorByKey(BindingContext.VALUE_PARAMETER, this::getValueParameter) bindingContext.registerDeclarationToDescriptorByKey(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, this::getPrimaryConstructorParameter) bindingContext.registerGetterByKey(FE10_BINDING_RESOLVE_TO_DESCRIPTORS, this::resolveToDescriptors) bindingContext.registerGetterByKey(BindingContext.DECLARATION_TO_DESCRIPTOR, this::getDeclarationToDescriptor) } private inline fun <reified T : Any> PsiElement.getKtSymbolOfTypeOrNull(): T? = this@ToDescriptorBindingContextValueProviders.context.withAnalysisSession { [email protected]<KtDeclaration>()?.getSymbol().safeAs<T>() } private fun getClass(key: PsiElement): ClassDescriptor? { val ktClassSymbol = key.getKtSymbolOfTypeOrNull<KtNamedClassOrObjectSymbol>() ?: return null return KtSymbolBasedClassDescriptor(ktClassSymbol, context) } private fun getTypeParameter(key: KtTypeParameter): TypeParameterDescriptor { val ktTypeParameterSymbol = context.withAnalysisSession { key.getTypeParameterSymbol() } return KtSymbolBasedTypeParameterDescriptor(ktTypeParameterSymbol, context) } private fun getFunction(key: PsiElement): SimpleFunctionDescriptor? { val ktFunctionLikeSymbol = key.getKtSymbolOfTypeOrNull<KtFunctionLikeSymbol>() ?: return null return ktFunctionLikeSymbol.toDeclarationDescriptor(context) as? SimpleFunctionDescriptor } private fun getConstructor(key: PsiElement): ConstructorDescriptor? { val ktConstructorSymbol = key.getKtSymbolOfTypeOrNull<KtConstructorSymbol>() ?: return null val containerClass = context.withAnalysisSession { ktConstructorSymbol.getContainingSymbol() } check(containerClass is KtNamedClassOrObjectSymbol) { "Unexpected contained for Constructor symbol: $containerClass, ktConstructorSymbol = $ktConstructorSymbol" } return KtSymbolBasedConstructorDescriptor(ktConstructorSymbol, KtSymbolBasedClassDescriptor(containerClass, context)) } private fun getVariable(key: PsiElement): VariableDescriptor? { if (key !is KtVariableDeclaration) return null if (key is KtProperty) { val symbol = context.withAnalysisSession { key.getVariableSymbol() } return symbol.toDeclarationDescriptor(context) } else { context.implementationPostponed("Destruction declaration is not supported yet: $key") } } private fun getValueParameter(key: KtParameter): VariableDescriptor? { val symbol = context.withAnalysisSession { key.getParameterSymbol() }.safeAs<KtValueParameterSymbol>() ?: return null return symbol.toDeclarationDescriptor(context) } private fun getPrimaryConstructorParameter(key: PsiElement): PropertyDescriptor? { val parameter = key.safeAs<KtParameter>() ?: return null val parameterSymbol = context.withAnalysisSession { parameter.getParameterSymbol() } val propertySymbol = parameterSymbol.safeAs<KtValueParameterSymbol>()?.generatedPrimaryConstructorProperty ?: return null return KtSymbolBasedPropertyDescriptor(propertySymbol, context) } private fun getDeclarationToDescriptor(key: PsiElement): DeclarationDescriptor? { for (getter in declarationToDescriptorGetters) { getter(key)?.let { return it } } return null } private fun resolveToDescriptors(ktReference: KtReference): Collection<DeclarationDescriptor>? { if (ktReference !is KtSymbolBasedReference) return null val symbols = context.withAnalysisSession { ktReference.resolveToSymbols() } return symbols.map { it.toDeclarationDescriptor(context) } } }
apache-2.0
d3e397a82f47deeaef005d42a1c7d6d0
52.070175
158
0.769421
5.879495
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KtControlFlowBuilder.kt
1
56286
// 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.dfa import com.intellij.codeInsight.Nullability import com.intellij.codeInspection.dataFlow.TypeConstraint import com.intellij.codeInspection.dataFlow.TypeConstraints import com.intellij.codeInspection.dataFlow.interpreter.DataFlowInterpreter import com.intellij.codeInspection.dataFlow.java.inst.* import com.intellij.codeInspection.dataFlow.jvm.SpecialField import com.intellij.codeInspection.dataFlow.jvm.TrapTracker import com.intellij.codeInspection.dataFlow.jvm.transfer.* import com.intellij.codeInspection.dataFlow.jvm.transfer.TryCatchTrap.CatchClauseDescriptor import com.intellij.codeInspection.dataFlow.lang.ir.* import com.intellij.codeInspection.dataFlow.lang.ir.DeferredOffset import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState import com.intellij.codeInspection.dataFlow.rangeSet.LongRangeBinOp import com.intellij.codeInspection.dataFlow.rangeSet.LongRangeSet import com.intellij.codeInspection.dataFlow.types.* import com.intellij.codeInspection.dataFlow.value.* import com.intellij.codeInspection.dataFlow.value.DfaControlTransferValue.TransferTarget import com.intellij.codeInspection.dataFlow.value.DfaControlTransferValue.Trap import com.intellij.openapi.diagnostic.logger import com.intellij.psi.CommonClassNames import com.intellij.psi.PsiElement import com.intellij.psi.PsiPrimitiveType import com.intellij.psi.PsiType import com.intellij.psi.tree.TokenSet import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.FList import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.inspections.dfa.KotlinAnchor.* import org.jetbrains.kotlin.idea.inspections.dfa.KotlinProblem.* import org.jetbrains.kotlin.idea.intentions.loopToCallChain.targetLoop import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.refactoring.move.moveMethod.type import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicInteger class KtControlFlowBuilder(val factory: DfaValueFactory, val context: KtExpression) { private val flow = ControlFlow(factory, context) private var broken: Boolean = false private val trapTracker = TrapTracker(factory, context) private val stringType = PsiType.getJavaLangString(context.manager, context.resolveScope) fun buildFlow(): ControlFlow? { processExpression(context) if (LOG.isDebugEnabled) { val total = totalCount.incrementAndGet() val success = if (!broken) successCount.incrementAndGet() else successCount.get() if (total % 100 == 0) { LOG.info("Analyzed: "+success+" of "+total + " ("+success*100/total + "%)") } } if (broken) return null addInstruction(PopInstruction()) // return value flow.finish() return flow } private fun processExpression(expr: KtExpression?) { when (expr) { null -> pushUnknown() is KtBlockExpression -> processBlock(expr) is KtParenthesizedExpression -> processExpression(expr.expression) is KtBinaryExpression -> processBinaryExpression(expr) is KtBinaryExpressionWithTypeRHS -> processAsExpression(expr) is KtPrefixExpression -> processPrefixExpression(expr) is KtPostfixExpression -> processPostfixExpression(expr) is KtIsExpression -> processIsExpression(expr) is KtCallExpression -> processCallExpression(expr) is KtConstantExpression -> processConstantExpression(expr) is KtSimpleNameExpression -> processReferenceExpression(expr) is KtDotQualifiedExpression -> processQualifiedReferenceExpression(expr) is KtSafeQualifiedExpression -> processQualifiedReferenceExpression(expr) is KtReturnExpression -> processReturnExpression(expr) is KtContinueExpression -> processLabeledJumpExpression(expr) is KtBreakExpression -> processLabeledJumpExpression(expr) is KtThrowExpression -> processThrowExpression(expr) is KtIfExpression -> processIfExpression(expr) is KtWhenExpression -> processWhenExpression(expr) is KtWhileExpression -> processWhileExpression(expr) is KtDoWhileExpression -> processDoWhileExpression(expr) is KtForExpression -> processForExpression(expr) is KtProperty -> processDeclaration(expr) is KtLambdaExpression -> processLambda(expr) is KtStringTemplateExpression -> processStringTemplate(expr) is KtArrayAccessExpression -> processArrayAccess(expr) is KtAnnotatedExpression -> processExpression(expr.baseExpression) is KtClassLiteralExpression -> processClassLiteralExpression(expr) is KtLabeledExpression -> processExpression(expr.baseExpression) is KtThisExpression -> processThisExpression(expr) is KtSuperExpression -> pushUnknown() is KtCallableReferenceExpression -> processCallableReference(expr) is KtTryExpression -> processTryExpression(expr) is KtDestructuringDeclaration -> processDestructuringDeclaration(expr) // KtObjectLiteralExpression, KtNamedFunction, KtClass else -> { // unsupported construct if (LOG.isDebugEnabled) { val className = expr.javaClass.name if (unsupported.add(className)) { LOG.debug("Unsupported expression in control flow: $className") } } broken = true } } flow.finishElement(expr) } private fun processDestructuringDeclaration(expr: KtDestructuringDeclaration) { processExpression(expr.initializer) } data class KotlinCatchClauseDescriptor(val clause : KtCatchClause): CatchClauseDescriptor { override fun parameter(): VariableDescriptor? { val parameter = clause.catchParameter ?: return null return KtVariableDescriptor(parameter) } override fun constraints(): MutableList<TypeConstraint> { val parameter = clause.catchParameter ?: return mutableListOf() return mutableListOf(TypeConstraint.fromDfType(parameter.type().toDfType(clause))) } } private fun processTryExpression(statement: KtTryExpression) { val tryBlock = statement.tryBlock val finallyBlock = statement.finallyBlock val finallyStart = DeferredOffset() val finallyDescriptor = if (finallyBlock != null) EnterFinallyTrap(finallyBlock, finallyStart) else null finallyDescriptor?.let { trapTracker.pushTrap(it) } val tempVar = flow.createTempVariable(DfType.TOP) val sections = statement.catchClauses val clauses = LinkedHashMap<CatchClauseDescriptor, DeferredOffset>() if (sections.isNotEmpty()) { for (section in sections) { val catchBlock = section.catchBody if (catchBlock != null) { clauses[KotlinCatchClauseDescriptor(section)] = DeferredOffset() } } trapTracker.pushTrap(TryCatchTrap(statement, clauses)) } processExpression(tryBlock) addInstruction(SimpleAssignmentInstruction(null, tempVar)) val gotoEnd = createTransfer(statement, tryBlock, tempVar) val singleFinally = FList.createFromReversed<Trap>(ContainerUtil.createMaybeSingletonList(finallyDescriptor)) controlTransfer(gotoEnd, singleFinally) if (sections.isNotEmpty()) { trapTracker.popTrap(TryCatchTrap::class.java) } for (section in sections) { val offset = clauses[KotlinCatchClauseDescriptor(section)] if (offset == null) continue setOffset(offset) val catchBlock = section.catchBody processExpression(catchBlock) addInstruction(SimpleAssignmentInstruction(null, tempVar)) controlTransfer(gotoEnd, singleFinally) } if (finallyBlock != null) { setOffset(finallyStart) trapTracker.popTrap(EnterFinallyTrap::class.java) trapTracker.pushTrap(InsideFinallyTrap(finallyBlock)) processExpression(finallyBlock.finalExpression) addInstruction(PopInstruction()) controlTransfer(ExitFinallyTransfer(finallyDescriptor!!), FList.emptyList()) trapTracker.popTrap(InsideFinallyTrap::class.java) } } private fun processCallableReference(expr: KtCallableReferenceExpression) { processExpression(expr.receiverExpression) addInstruction(PopInstruction()) val dfType = expr.getKotlinType().toDfType(expr) addInstruction(PushValueInstruction(dfType, KotlinExpressionAnchor(expr))) } private fun processThisExpression(expr: KtThisExpression) { val dfType = expr.getKotlinType().toDfType(expr) val descriptor = expr.analyze(BodyResolveMode.FULL)[BindingContext.REFERENCE_TARGET, expr.instanceReference] if (descriptor != null) { val varDesc = KtThisDescriptor(descriptor, dfType) addInstruction(PushInstruction(factory.varFactory.createVariableValue(varDesc), KotlinExpressionAnchor(expr))) } else { addInstruction(PushValueInstruction(dfType, KotlinExpressionAnchor(expr))) } } private fun processClassLiteralExpression(expr: KtClassLiteralExpression) { val kotlinType = expr.getKotlinType() val receiver = expr.receiverExpression if (kotlinType != null) { if (receiver is KtSimpleNameExpression && receiver.mainReference.resolve() is KtClass) { val arguments = kotlinType.arguments if (arguments.size == 1) { val kType = arguments[0].type val kClassPsiType = kotlinType.toPsiType(expr) if (kClassPsiType != null) { val kClassConstant: DfType = DfTypes.referenceConstant(kType, kClassPsiType) addInstruction(PushValueInstruction(kClassConstant, KotlinExpressionAnchor(expr))) return } } } } processExpression(receiver) addInstruction(PopInstruction()) addInstruction(PushValueInstruction(kotlinType.toDfType(expr))) // TODO: support kotlin-class as a variable; link to TypeConstraint } private fun processAsExpression(expr: KtBinaryExpressionWithTypeRHS) { val operand = expr.left val typeReference = expr.right val type = getTypeCheckDfType(typeReference) val ref = expr.operationReference if (ref.text != "as?" && ref.text != "as") { broken = true return } processExpression(operand) val operandType = operand.getKotlinType() if (operandType.toDfType(expr) is DfPrimitiveType) { addInstruction(WrapDerivedVariableInstruction(DfTypes.NOT_NULL_OBJECT, SpecialField.UNBOX)) } if (ref.text == "as?") { val tempVariable: DfaVariableValue = flow.createTempVariable(DfTypes.OBJECT_OR_NULL) addInstruction(SimpleAssignmentInstruction(null, tempVariable)) addInstruction(PushValueInstruction(type, null)) addInstruction(InstanceofInstruction(null, false)) val offset = DeferredOffset() addInstruction(ConditionalGotoInstruction(offset, DfTypes.FALSE)) val anchor = KotlinExpressionAnchor(expr) addInstruction(PushInstruction(tempVariable, anchor)) val endOffset = DeferredOffset() addInstruction(GotoInstruction(endOffset)) setOffset(offset) addInstruction(PushValueInstruction(DfTypes.NULL, anchor)) setOffset(endOffset) } else { val transfer = trapTracker.maybeTransferValue("java.lang.ClassCastException") addInstruction(EnsureInstruction(KotlinCastProblem(operand, expr), RelationType.IS, type, transfer)) if (typeReference != null) { val castType = typeReference.getAbbreviatedTypeOrType(typeReference.analyze(BodyResolveMode.FULL)) if (castType.toDfType(typeReference) is DfPrimitiveType) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } } } } private fun processArrayAccess(expr: KtArrayAccessExpression) { val arrayExpression = expr.arrayExpression processExpression(arrayExpression) val kotlinType = arrayExpression?.getKotlinType() var curType = kotlinType val indexes = expr.indexExpressions for (idx in indexes) { processExpression(idx) val anchor = if (idx == indexes.last()) KotlinExpressionAnchor(expr) else null val indexType = idx.getKotlinType() if (indexType == null || !indexType.fqNameEquals("kotlin.Int")) { addInstruction(EvalUnknownInstruction(anchor, 2)) addInstruction(FlushFieldsInstruction()) continue } if (curType != null && KotlinBuiltIns.isArrayOrPrimitiveArray(curType)) { if (indexType.canBeNull()) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } val transfer = trapTracker.maybeTransferValue("java.lang.ArrayIndexOutOfBoundsException") addInstruction(ArrayAccessInstruction(transfer, anchor, KotlinArrayIndexProblem(SpecialField.ARRAY_LENGTH, idx), null)) curType = expr.builtIns.getArrayElementType(curType) } else { if (KotlinBuiltIns.isString(kotlinType)) { if (indexType.canBeNull()) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } val transfer = trapTracker.maybeTransferValue("java.lang.StringIndexOutOfBoundsException") addInstruction(EnsureIndexInBoundsInstruction(KotlinArrayIndexProblem(SpecialField.STRING_LENGTH, idx), transfer)) addInstruction(PushValueInstruction(DfTypes.typedObject(PsiType.CHAR, Nullability.UNKNOWN), anchor)) } else if (kotlinType != null && (KotlinBuiltIns.isListOrNullableList(kotlinType) || kotlinType.supertypes().any { type -> KotlinBuiltIns.isListOrNullableList(type) })) { if (indexType.canBeNull()) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } val transfer = trapTracker.maybeTransferValue("java.lang.IndexOutOfBoundsException") addInstruction(EnsureIndexInBoundsInstruction(KotlinArrayIndexProblem(SpecialField.COLLECTION_SIZE, idx), transfer)) pushUnknown() } else { addInstruction(EvalUnknownInstruction(anchor, 2)) addInstruction(FlushFieldsInstruction()) } } } } private fun processIsExpression(expr: KtIsExpression) { processExpression(expr.leftHandSide) val type = getTypeCheckDfType(expr.typeReference) if (type == DfType.TOP) { pushUnknown() } else { addInstruction(PushValueInstruction(type)) if (expr.isNegated) { addInstruction(InstanceofInstruction(null, false)) addInstruction(NotInstruction(KotlinExpressionAnchor(expr))) } else { addInstruction(InstanceofInstruction(KotlinExpressionAnchor(expr), false)) } } } private fun processStringTemplate(expr: KtStringTemplateExpression) { var first = true val entries = expr.entries if (entries.isEmpty()) { addInstruction(PushValueInstruction(DfTypes.constant("", stringType))) return } val lastEntry = entries.last() for (entry in entries) { when (entry) { is KtEscapeStringTemplateEntry -> addInstruction(PushValueInstruction(DfTypes.constant(entry.unescapedValue, stringType))) is KtLiteralStringTemplateEntry -> addInstruction(PushValueInstruction(DfTypes.constant(entry.text, stringType))) is KtStringTemplateEntryWithExpression -> processExpression(entry.expression) else -> pushUnknown() } if (!first) { val anchor = if (entry == lastEntry) KotlinExpressionAnchor(expr) else null addInstruction(StringConcatInstruction(anchor, stringType)) } first = false } if (entries.size == 1) { // Implicit toString conversion for "$myVar" string addInstruction(PushValueInstruction(DfTypes.constant("", stringType))) addInstruction(StringConcatInstruction(KotlinExpressionAnchor(expr), stringType)) } } private fun processLambda(expr: KtLambdaExpression) { val element = expr.bodyExpression if (element != null) { addInstruction(ClosureInstruction(listOf(element))) } pushUnknown() } private fun processCallExpression(expr: KtCallExpression) { // TODO: recognize constructors, set the exact type for the result val args = expr.valueArgumentList?.arguments var argCount = 0 if (args != null) { for (arg: KtValueArgument in args) { val argExpr = arg.getArgumentExpression() if (argExpr != null) { processExpression(argExpr) argCount++ } } } // TODO: inline cross-inline lambdas for(lambdaArg in expr.lambdaArguments) { processExpression(lambdaArg.getLambdaExpression()) argCount++ } addUnknownCall(expr, argCount) // TODO: support pure calls, some known methods, probably Java contracts, etc. } private fun addUnknownCall(expr: KtExpression, args: Int) { if (args > 0) { addInstruction(if (args > 1) SpliceInstruction(args) else PopInstruction()) } addInstruction(PushValueInstruction(expr.getKotlinType().toDfType(expr), KotlinExpressionAnchor(expr))) addInstruction(FlushFieldsInstruction()) val transfer = trapTracker.maybeTransferValue(CommonClassNames.JAVA_LANG_THROWABLE) if (transfer != null) { addInstruction(EnsureInstruction(null, RelationType.EQ, DfType.TOP, transfer)) } } private fun processQualifiedReferenceExpression(expr: KtQualifiedExpression) { val receiver = expr.receiverExpression processExpression(receiver) val offset = DeferredOffset() if (expr is KtSafeQualifiedExpression) { addInstruction(DupInstruction()) addInstruction(ConditionalGotoInstruction(offset, DfTypes.NULL)) } val selector = expr.selectorExpression if (!pushJavaClassField(receiver, selector, expr)) { val specialField = findSpecialField(expr) if (specialField != null) { addInstruction(UnwrapDerivedVariableInstruction(specialField)) if (expr is KtSafeQualifiedExpression) { addInstruction(WrapDerivedVariableInstruction(expr.getKotlinType().toDfType(expr), SpecialField.UNBOX)) } } else { addInstruction(PopInstruction()) processExpression(selector) } addInstruction(ResultOfInstruction(KotlinExpressionAnchor(expr))) } if (expr is KtSafeQualifiedExpression) { val endOffset = DeferredOffset() addInstruction(GotoInstruction(endOffset)) setOffset(offset) addInstruction(PopInstruction()) addInstruction(PushValueInstruction(DfTypes.NULL, KotlinExpressionAnchor(expr))) setOffset(endOffset) } } private fun pushJavaClassField(receiver: KtExpression, selector: KtExpression?, expr: KtQualifiedExpression): Boolean { if (selector == null || !selector.textMatches("java")) return false if (!receiver.getKotlinType().fqNameEquals("kotlin.reflect.KClass")) return false val kotlinType = expr.getKotlinType() ?: return false val classPsiType = kotlinType.toPsiType(expr) ?: return false if (!classPsiType.equalsToText(CommonClassNames.JAVA_LANG_CLASS)) return false addInstruction(KotlinClassToJavaClassInstruction(KotlinExpressionAnchor(expr), classPsiType)) return true } private fun findSpecialField(type: KotlinType?): SpecialField? { type ?: return null return when { KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type) -> { return SpecialField.ARRAY_LENGTH } KotlinBuiltIns.isCollectionOrNullableCollection(type) || KotlinBuiltIns.isMapOrNullableMap(type) || type.supertypes().any { st -> KotlinBuiltIns.isCollectionOrNullableCollection(st) || KotlinBuiltIns.isMapOrNullableMap(st)} -> { return SpecialField.COLLECTION_SIZE } KotlinBuiltIns.isStringOrNullableString(type) -> SpecialField.STRING_LENGTH else -> null } } private fun findSpecialField(expr: KtQualifiedExpression): SpecialField? { val selector = expr.selectorExpression ?: return null val receiver = expr.receiverExpression val selectorText = selector.text if (selectorText != "size" && selectorText != "length") return null val field = findSpecialField(receiver.getKotlinType()) ?: return null if ((selectorText == "length") != (field == SpecialField.STRING_LENGTH)) return null return field } private fun processPrefixExpression(expr: KtPrefixExpression) { val operand = expr.baseExpression processExpression(operand) val anchor = KotlinExpressionAnchor(expr) if (operand != null) { val dfType = operand.getKotlinType().toDfType(expr) val dfVar = KtVariableDescriptor.createFromQualified(factory, operand) val ref = expr.operationReference.text if (dfType is DfIntegralType) { when (ref) { "++", "--" -> { if (dfVar != null) { addInstruction(PushValueInstruction(dfType.meetRange(LongRangeSet.point(1)))) addInstruction(NumericBinaryInstruction(if (ref == "++") LongRangeBinOp.PLUS else LongRangeBinOp.MINUS, null)) addInstruction(SimpleAssignmentInstruction(anchor, dfVar)) return } } "+" -> { return } "-" -> { addInstruction(PushValueInstruction(dfType.meetRange(LongRangeSet.point(0)))) addInstruction(SwapInstruction()) addInstruction(NumericBinaryInstruction(LongRangeBinOp.MINUS, anchor)) return } } } if (dfType is DfBooleanType && ref == "!") { addInstruction(NotInstruction(anchor)) return } if (dfVar != null && (ref == "++" || ref == "--")) { // Custom inc/dec may update the variable addInstruction(FlushVariableInstruction(dfVar)) } } addInstruction(EvalUnknownInstruction(anchor, 1)) } private fun processPostfixExpression(expr: KtPostfixExpression) { val operand = expr.baseExpression processExpression(operand) val anchor = KotlinExpressionAnchor(expr) val ref = expr.operationReference.text if (ref == "++" || ref == "--") { if (operand != null) { val dfType = operand.getKotlinType().toDfType(expr) val dfVar = KtVariableDescriptor.createFromQualified(factory, operand) if (dfVar != null) { if (dfType is DfIntegralType) { addInstruction(DupInstruction()) addInstruction(PushValueInstruction(dfType.meetRange(LongRangeSet.point(1)))) addInstruction(NumericBinaryInstruction(if (ref == "++") LongRangeBinOp.PLUS else LongRangeBinOp.MINUS, null)) addInstruction(SimpleAssignmentInstruction(anchor, dfVar)) addInstruction(PopInstruction()) } else { // Custom inc/dec may update the variable addInstruction(FlushVariableInstruction(dfVar)) } } else { // Unknown value updated addInstruction(FlushFieldsInstruction()) } } } else if (ref == "!!") { val transfer: DfaControlTransferValue? = trapTracker.maybeTransferValue("java.lang.NullPointerException") addInstruction(EnsureInstruction(KotlinNullCheckProblem(expr), RelationType.NE, DfTypes.NULL, transfer)) // Probably unbox addImplicitConversion(expr, operand?.getKotlinType(), expr.getKotlinType()) } else { addInstruction(EvalUnknownInstruction(anchor, 1)) } } private fun processDoWhileExpression(expr: KtDoWhileExpression) { val offset = FixedOffset(flow.instructionCount) processExpression(expr.body) addInstruction(PopInstruction()) processExpression(expr.condition) addInstruction(ConditionalGotoInstruction(offset, DfTypes.TRUE)) flow.finishElement(expr) pushUnknown() addInstruction(FinishElementInstruction(expr)) } private fun processWhileExpression(expr: KtWhileExpression) { val startOffset = FixedOffset(flow.instructionCount) val condition = expr.condition processExpression(condition) val endOffset = DeferredOffset() addInstruction(ConditionalGotoInstruction(endOffset, DfTypes.FALSE, condition)) processExpression(expr.body) addInstruction(PopInstruction()) addInstruction(GotoInstruction(startOffset)) setOffset(endOffset) flow.finishElement(expr) pushUnknown() addInstruction(FinishElementInstruction(expr)) } private fun processForExpression(expr: KtForExpression) { val parameter = expr.loopParameter if (parameter == null) { // TODO: support destructuring declarations broken = true return } val parameterVar = factory.varFactory.createVariableValue(KtVariableDescriptor(parameter)) val parameterType = parameter.type() val pushLoopCondition = processForRange(expr, parameterVar, parameterType) val startOffset = FixedOffset(flow.instructionCount) val endOffset = DeferredOffset() addInstruction(FlushVariableInstruction(parameterVar)) pushLoopCondition() addInstruction(ConditionalGotoInstruction(endOffset, DfTypes.FALSE)) processExpression(expr.body) addInstruction(PopInstruction()) addInstruction(GotoInstruction(startOffset)) setOffset(endOffset) flow.finishElement(expr) pushUnknown() addInstruction(FinishElementInstruction(expr)) } private fun processForRange(expr: KtForExpression, parameterVar: DfaVariableValue, parameterType: KotlinType?): () -> Unit { val range = expr.loopRange if (parameterVar.dfType is DfIntegralType) { if (range is KtBinaryExpression) { val ref = range.operationReference.text val (leftRelation, rightRelation) = when(ref) { ".." -> RelationType.GE to RelationType.LE "until" -> RelationType.GE to RelationType.LT "downTo" -> RelationType.LE to RelationType.GE else -> null to null } if (leftRelation != null && rightRelation != null) { val left = range.left val right = range.right val leftType = left?.getKotlinType() val rightType = right?.getKotlinType() if (leftType.toDfType(range) is DfIntegralType && rightType.toDfType(range) is DfIntegralType) { processExpression(left) val leftVar = flow.createTempVariable(parameterVar.dfType) addImplicitConversion(left, parameterType) addInstruction(SimpleAssignmentInstruction(null, leftVar)) addInstruction(PopInstruction()) processExpression(right) val rightVar = flow.createTempVariable(parameterVar.dfType) addImplicitConversion(right, parameterType) addInstruction(SimpleAssignmentInstruction(null, rightVar)) addInstruction(PopInstruction()) return { val forAnchor = KotlinForVisitedAnchor(expr) addInstruction(PushInstruction(parameterVar, null)) addInstruction(PushInstruction(leftVar, null)) addInstruction(BooleanBinaryInstruction(leftRelation, false, null)) val offset = DeferredOffset() addInstruction(ConditionalGotoInstruction(offset, DfTypes.FALSE)) addInstruction(PushInstruction(parameterVar, null)) addInstruction(PushInstruction(rightVar, null)) addInstruction(BooleanBinaryInstruction(rightRelation, false, forAnchor)) val finalOffset = DeferredOffset() addInstruction(GotoInstruction(finalOffset)) setOffset(offset) addInstruction(PushValueInstruction(DfTypes.FALSE, forAnchor)) setOffset(finalOffset) } } } } } processExpression(range) if (range != null) { val kotlinType = range.getKotlinType() val lengthField = findSpecialField(kotlinType) if (lengthField != null) { val collectionVar = flow.createTempVariable(kotlinType.toDfType(range)) addInstruction(SimpleAssignmentInstruction(null, collectionVar)) addInstruction(PopInstruction()) return { addInstruction(PushInstruction(lengthField.createValue(factory, collectionVar), null)) addInstruction(PushValueInstruction(DfTypes.intValue(0))) addInstruction(BooleanBinaryInstruction(RelationType.GT, false, null)) pushUnknown() addInstruction(BooleanAndOrInstruction(false, KotlinForVisitedAnchor(expr))) } } } addInstruction(PopInstruction()) return { pushUnknown() } } private fun processBlock(expr: KtBlockExpression) { val statements = expr.statements if (statements.isEmpty()) { pushUnknown() } else { for (child in statements) { processExpression(child) if (child != statements.last()) { addInstruction(PopInstruction()) } if (broken) return } addInstruction(FinishElementInstruction(expr)) } } private fun processDeclaration(variable: KtProperty) { val initializer = variable.initializer if (initializer == null) { pushUnknown() return } val dfaVariable = factory.varFactory.createVariableValue(KtVariableDescriptor(variable)) processExpression(initializer) addImplicitConversion(initializer, variable.type()) addInstruction(SimpleAssignmentInstruction(KotlinExpressionAnchor(variable), dfaVariable)) } private fun processReturnExpression(expr: KtReturnExpression) { val returnedExpression = expr.returnedExpression processExpression(returnedExpression) if (expr.labeledExpression != null) { val targetFunction = expr.getTargetFunction(expr.analyze(BodyResolveMode.FULL)) if (targetFunction != null && PsiTreeUtil.isAncestor(context, targetFunction, true)) { if (returnedExpression != null) { val retVar = flow.createTempVariable(returnedExpression.getKotlinType().toDfType(expr)) addInstruction(SimpleAssignmentInstruction(null, retVar)) createTransfer(targetFunction, targetFunction, retVar) } else { createTransfer(targetFunction, targetFunction, factory.unknown) } } } addInstruction(ReturnInstruction(factory, trapTracker.trapStack(), expr)) } private fun controlTransfer(target: TransferTarget, traps: FList<Trap>) { addInstruction(ControlTransferInstruction(factory.controlTransfer(target, traps))) } private fun createTransfer(exitedStatement: PsiElement, blockToFlush: PsiElement, resultValue: DfaValue): InstructionTransfer { val varsToFlush = PsiTreeUtil.findChildrenOfType( blockToFlush, KtProperty::class.java ).map { property -> KtVariableDescriptor(property) } return object : InstructionTransfer(flow.getEndOffset(exitedStatement), varsToFlush) { override fun dispatch(state: DfaMemoryState, interpreter: DataFlowInterpreter): MutableList<DfaInstructionState> { state.push(resultValue) return super.dispatch(state, interpreter) } } } private fun processLabeledJumpExpression(expr: KtExpressionWithLabel) { val targetLoop = expr.targetLoop() if (targetLoop == null || !PsiTreeUtil.isAncestor(context, targetLoop, false)) { addInstruction(ControlTransferInstruction(trapTracker.transferValue(DfaControlTransferValue.RETURN_TRANSFER))) } else { val body = if (expr is KtBreakExpression) targetLoop else targetLoop.body!! val transfer = factory.controlTransfer(createTransfer(body, body, factory.unknown), trapTracker.getTrapsInsideElement(body)) addInstruction(ControlTransferInstruction(transfer)) } } private fun processThrowExpression(expr: KtThrowExpression) { val exception = expr.thrownExpression processExpression(exception) addInstruction(PopInstruction()) if (exception != null) { val psiType = exception.getKotlinType()?.toPsiType(expr) if (psiType != null) { val kind = ExceptionTransfer(TypeConstraints.instanceOf(psiType)) addInstruction(ThrowInstruction(trapTracker.transferValue(kind), expr)) return } } pushUnknown() } private fun processReferenceExpression(expr: KtSimpleNameExpression) { val dfVar = KtVariableDescriptor.createFromSimpleName(factory, expr) if (dfVar != null) { addInstruction(JvmPushInstruction(dfVar, KotlinExpressionAnchor(expr))) var realExpr : KtExpression = expr while (true) { val parent = realExpr.parent if (parent is KtQualifiedExpression && parent.selectorExpression == realExpr) { realExpr = parent } else break } val exprType = realExpr.getKotlinType() val declaredType = (dfVar.descriptor as? KtVariableDescriptor)?.variable?.type() addImplicitConversion(expr, declaredType, exprType) return } addUnknownCall(expr, 0) } private fun processConstantExpression(expr: KtConstantExpression) { addInstruction(PushValueInstruction(getConstant(expr), KotlinExpressionAnchor(expr))) } private fun pushUnknown() { addInstruction(PushValueInstruction(DfType.TOP)) } private fun processBinaryExpression(expr: KtBinaryExpression) { val token = expr.operationToken val relation = relationFromToken(token) if (relation != null) { processBinaryRelationExpression(expr, relation, token == KtTokens.EXCLEQ || token == KtTokens.EQEQ) return } val leftKtType = expr.left?.getKotlinType() if (token === KtTokens.PLUS && (KotlinBuiltIns.isString(leftKtType) || KotlinBuiltIns.isString(expr.right?.getKotlinType()))) { processExpression(expr.left) processExpression(expr.right) addInstruction(StringConcatInstruction(KotlinExpressionAnchor(expr), stringType)) return } if (leftKtType?.toDfType(expr) is DfIntegralType) { val mathOp = mathOpFromToken(expr.operationReference) if (mathOp != null) { processMathExpression(expr, mathOp) return } } if (token === KtTokens.ANDAND || token === KtTokens.OROR) { processShortCircuitExpression(expr, token === KtTokens.ANDAND) return } if (ASSIGNMENT_TOKENS.contains(token)) { processAssignmentExpression(expr) return } if (token === KtTokens.ELVIS) { processNullSafeOperator(expr) return } if (token === KtTokens.IN_KEYWORD) { val left = expr.left processExpression(left) processInCheck(left?.getKotlinType(), expr.right, KotlinExpressionAnchor(expr), false) return } if (token === KtTokens.NOT_IN) { val left = expr.left processExpression(left) processInCheck(left?.getKotlinType(), expr.right, KotlinExpressionAnchor(expr), true) return } // TODO: support other operators processExpression(expr.left) processExpression(expr.right) addUnknownCall(expr, 2) } private fun processInCheck(kotlinType: KotlinType?, range: KtExpression?, anchor: KotlinAnchor, negated: Boolean) { if (kotlinType != null && (kotlinType.isInt() || kotlinType.isLong())) { if (range is KtBinaryExpression) { val ref = range.operationReference.text if (ref == ".." || ref == "until") { val left = range.left val right = range.right val leftType = left?.getKotlinType() val rightType = right?.getKotlinType() if (leftType.toDfType(range) is DfIntegralType && rightType.toDfType(range) is DfIntegralType) { processExpression(left) addImplicitConversion(left, kotlinType) processExpression(right) addImplicitConversion(right, kotlinType) addInstruction(SpliceInstruction(3, 2, 0, 2, 1)) addInstruction(BooleanBinaryInstruction(RelationType.GE, false, null)) val offset = DeferredOffset() addInstruction(ConditionalGotoInstruction(offset, DfTypes.FALSE)) var relationType = if (ref == "until") RelationType.LT else RelationType.LE if (negated) { relationType = relationType.negated } addInstruction(BooleanBinaryInstruction(relationType, false, anchor)) val finalOffset = DeferredOffset() addInstruction(GotoInstruction(finalOffset)) setOffset(offset) addInstruction(SpliceInstruction(2)) addInstruction(PushValueInstruction(if (negated) DfTypes.TRUE else DfTypes.FALSE, anchor)) setOffset(finalOffset) return } } } } processExpression(range) addInstruction(EvalUnknownInstruction(anchor, 2)) addInstruction(FlushFieldsInstruction()) } private fun processNullSafeOperator(expr: KtBinaryExpression) { val left = expr.left processExpression(left) addInstruction(DupInstruction()) val offset = DeferredOffset() addInstruction(ConditionalGotoInstruction(offset, DfTypes.NULL)) val endOffset = DeferredOffset() addImplicitConversion(expr, left?.getKotlinType(), expr.getKotlinType()) addInstruction(GotoInstruction(endOffset)) setOffset(offset) addInstruction(PopInstruction()) processExpression(expr.right) setOffset(endOffset) addInstruction(ResultOfInstruction(KotlinExpressionAnchor(expr))) } private fun processAssignmentExpression(expr: KtBinaryExpression) { val left = expr.left val right = expr.right val dfVar = KtVariableDescriptor.createFromQualified(factory, left) val leftType = left?.getKotlinType() val rightType = right?.getKotlinType() if (dfVar == null) { processExpression(left) addInstruction(PopInstruction()) processExpression(right) addImplicitConversion(right, leftType) // TODO: support safe-qualified assignments // TODO: support array stores addInstruction(FlushFieldsInstruction()) return } val token = expr.operationToken val mathOp = mathOpFromAssignmentToken(token) if (mathOp != null) { val resultType = balanceType(leftType, rightType) processExpression(left) addImplicitConversion(left, resultType) processExpression(right) addImplicitConversion(right, resultType) addInstruction(NumericBinaryInstruction(mathOp, KotlinExpressionAnchor(expr))) addImplicitConversion(right, resultType, leftType) } else { processExpression(right) addImplicitConversion(right, leftType) } // TODO: support overloaded assignment addInstruction(SimpleAssignmentInstruction(KotlinExpressionAnchor(expr), dfVar)) addInstruction(FinishElementInstruction(expr)) } private fun processShortCircuitExpression(expr: KtBinaryExpression, and: Boolean) { val left = expr.left val right = expr.right val endOffset = DeferredOffset() processExpression(left) val nextOffset = DeferredOffset() addInstruction(ConditionalGotoInstruction(nextOffset, DfTypes.booleanValue(and), left)) val anchor = KotlinExpressionAnchor(expr) addInstruction(PushValueInstruction(DfTypes.booleanValue(!and), anchor)) addInstruction(GotoInstruction(endOffset)) setOffset(nextOffset) addInstruction(FinishElementInstruction(null)) processExpression(right) setOffset(endOffset) addInstruction(ResultOfInstruction(anchor)) } private fun processMathExpression(expr: KtBinaryExpression, mathOp: LongRangeBinOp) { val left = expr.left val right = expr.right val resultType = expr.getKotlinType() processExpression(left) addImplicitConversion(left, resultType) processExpression(right) if (mathOp == LongRangeBinOp.DIV || mathOp == LongRangeBinOp.MOD) { val transfer: DfaControlTransferValue? = trapTracker.maybeTransferValue("java.lang.ArithmeticException") val zero = if (resultType?.isLong() == true) DfTypes.longValue(0) else DfTypes.intValue(0) addInstruction(EnsureInstruction(null, RelationType.NE, zero, transfer, true)) } if (!mathOp.isShift) { addImplicitConversion(right, resultType) } addInstruction(NumericBinaryInstruction(mathOp, KotlinExpressionAnchor(expr))) } private fun addImplicitConversion(expression: KtExpression?, expectedType: KotlinType?) { addImplicitConversion(expression, expression?.getKotlinType(), expectedType) } private fun addImplicitConversion(expression: KtExpression?, actualType: KotlinType?, expectedType: KotlinType?) { expression ?: return actualType ?: return expectedType ?: return if (actualType == expectedType) return val actualPsiType = actualType.toPsiType(expression) val expectedPsiType = expectedType.toPsiType(expression) if (actualPsiType !is PsiPrimitiveType && expectedPsiType is PsiPrimitiveType) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } else if (expectedPsiType !is PsiPrimitiveType && actualPsiType is PsiPrimitiveType) { val boxedType = actualPsiType.getBoxedType(expression) val dfType = if (boxedType != null) DfTypes.typedObject(boxedType, Nullability.NOT_NULL) else DfTypes.NOT_NULL_OBJECT addInstruction(WrapDerivedVariableInstruction(expectedType.toDfType(expression).meet(dfType), SpecialField.UNBOX)) } if (actualPsiType is PsiPrimitiveType && expectedPsiType is PsiPrimitiveType) { addInstruction(PrimitiveConversionInstruction(expectedPsiType, null)) } } private fun processBinaryRelationExpression( expr: KtBinaryExpression, relation: RelationType, forceEqualityByContent: Boolean ) { val left = expr.left val right = expr.right val leftType = left?.getKotlinType() val rightType = right?.getKotlinType() processExpression(left) if ((relation == RelationType.EQ || relation == RelationType.NE) || (leftType.toDfType(expr) is DfPrimitiveType && rightType.toDfType(expr) is DfPrimitiveType)) { val balancedType: KotlinType? = balanceType(leftType, rightType, forceEqualityByContent) addImplicitConversion(left, balancedType) processExpression(right) addImplicitConversion(right, balancedType) // TODO: avoid equals-comparison of unknown object types // but probably keep it for some types like enum, class, array addInstruction(BooleanBinaryInstruction(relation, forceEqualityByContent, KotlinExpressionAnchor(expr))) } else { // TODO: support >/>=/</<= for String and enum // Overloaded >/>=/</<=: do not evaluate processExpression(right) addUnknownCall(expr, 2) } } private fun balanceType(leftType: KotlinType?, rightType: KotlinType?, forceEqualityByContent: Boolean): KotlinType? = when { leftType == null || rightType == null -> null !forceEqualityByContent -> balanceType(leftType, rightType) leftType.isSubtypeOf(rightType) -> rightType rightType.isSubtypeOf(leftType) -> leftType else -> null } private fun balanceType(left: KotlinType?, right: KotlinType?): KotlinType? { if (left == null || right == null) return null if (left == right) return left if (left.canBeNull() && !right.canBeNull()) { return balanceType(left.makeNotNullable(), right) } if (!left.canBeNull() && right.canBeNull()) { return balanceType(left, right.makeNotNullable()) } if (left.isDouble()) return left if (right.isDouble()) return right if (left.isFloat()) return left if (right.isFloat()) return right if (left.isLong()) return left if (right.isLong()) return right // The 'null' means no balancing is necessary return null } private fun addInstruction(inst: Instruction) { flow.addInstruction(inst) } private fun setOffset(offset: DeferredOffset) { offset.setOffset(flow.instructionCount) } private fun processWhenExpression(expr: KtWhenExpression) { val subjectExpression = expr.subjectExpression val dfVar: DfaVariableValue? val kotlinType: KotlinType? if (subjectExpression == null) { dfVar = null kotlinType = null } else { processExpression(subjectExpression) val subjectVariable = expr.subjectVariable if (subjectVariable != null) { kotlinType = subjectVariable.type() dfVar = factory.varFactory.createVariableValue(KtVariableDescriptor(subjectVariable)) } else { kotlinType = subjectExpression.getKotlinType() dfVar = flow.createTempVariable(kotlinType.toDfType(expr)) } addInstruction(SimpleAssignmentInstruction(null, dfVar)) addInstruction(PopInstruction()) } val endOffset = DeferredOffset() for (entry in expr.entries) { if (entry.isElse) { processExpression(entry.expression) addInstruction(GotoInstruction(endOffset)) } else { val branchStart = DeferredOffset() for (condition in entry.conditions) { processWhenCondition(dfVar, kotlinType, condition) addInstruction(ConditionalGotoInstruction(branchStart, DfTypes.TRUE)) } val skipBranch = DeferredOffset() addInstruction(GotoInstruction(skipBranch)) setOffset(branchStart) processExpression(entry.expression) addInstruction(GotoInstruction(endOffset)) setOffset(skipBranch) } } pushUnknown() setOffset(endOffset) addInstruction(FinishElementInstruction(expr)) } private fun processWhenCondition(dfVar: DfaVariableValue?, dfVarType: KotlinType?, condition: KtWhenCondition) { when (condition) { is KtWhenConditionWithExpression -> { val expr = condition.expression processExpression(expr) val exprType = expr?.getKotlinType() if (dfVar != null) { val balancedType = balanceType(exprType, dfVarType, true) addImplicitConversion(expr, exprType, balancedType) addInstruction(PushInstruction(dfVar, null)) addImplicitConversion(null, dfVarType, balancedType) addInstruction(BooleanBinaryInstruction(RelationType.EQ, true, KotlinWhenConditionAnchor(condition))) } else if (exprType?.canBeNull() == true) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } } is KtWhenConditionIsPattern -> { if (dfVar != null) { addInstruction(PushInstruction(dfVar, null)) val type = getTypeCheckDfType(condition.typeReference) if (type == DfType.TOP) { pushUnknown() } else { addInstruction(PushValueInstruction(type)) if (condition.isNegated) { addInstruction(InstanceofInstruction(null, false)) addInstruction(NotInstruction(KotlinWhenConditionAnchor(condition))) } else { addInstruction(InstanceofInstruction(KotlinWhenConditionAnchor(condition), false)) } } } else { pushUnknown() } } is KtWhenConditionInRange -> { if (dfVar != null) { addInstruction(PushInstruction(dfVar, null)) } else { pushUnknown() } processInCheck(dfVarType, condition.rangeExpression, KotlinWhenConditionAnchor(condition), condition.isNegated) } else -> broken = true } } private fun getTypeCheckDfType(typeReference: KtTypeReference?): DfType { if (typeReference == null) return DfType.TOP val kotlinType = typeReference.getAbbreviatedTypeOrType(typeReference.analyze(BodyResolveMode.FULL)) val type = kotlinType.toDfType(typeReference) return if (type is DfPrimitiveType) { val boxedType = (kotlinType?.toPsiType(typeReference) as? PsiPrimitiveType)?.getBoxedType(typeReference) if (boxedType != null) { DfTypes.typedObject(boxedType, Nullability.NOT_NULL) } else { DfType.TOP } } else type } private fun processIfExpression(ifExpression: KtIfExpression) { val condition = ifExpression.condition processExpression(condition) if (condition?.getKotlinType()?.canBeNull() == true) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } val skipThenOffset = DeferredOffset() val thenStatement = ifExpression.then val elseStatement = ifExpression.`else` val exprType = ifExpression.getKotlinType() addInstruction(ConditionalGotoInstruction(skipThenOffset, DfTypes.FALSE, condition)) addInstruction(FinishElementInstruction(null)) processExpression(thenStatement) addImplicitConversion(thenStatement, exprType) val skipElseOffset = DeferredOffset() addInstruction(GotoInstruction(skipElseOffset)) setOffset(skipThenOffset) addInstruction(FinishElementInstruction(null)) processExpression(elseStatement) addImplicitConversion(elseStatement, exprType) setOffset(skipElseOffset) addInstruction(FinishElementInstruction(ifExpression)) } companion object { private val LOG = logger<KtControlFlowBuilder>() private val ASSIGNMENT_TOKENS = TokenSet.create(KtTokens.EQ, KtTokens.PLUSEQ, KtTokens.MINUSEQ, KtTokens.MULTEQ, KtTokens.DIVEQ, KtTokens.PERCEQ) private val totalCount = AtomicInteger() private val successCount = AtomicInteger() private val unsupported = ConcurrentHashMap.newKeySet<String>() } }
apache-2.0
43b27fc6de3326476223c64beae23358
46.499578
158
0.632804
6.05356
false
false
false
false
siosio/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHPRDetailsComponent.kt
1
4326
// 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 org.jetbrains.plugins.github.pullrequest.ui.toolwindow import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.ui.IdeBorderFactory import com.intellij.ui.PopupHandler import com.intellij.ui.SideBorder import com.intellij.ui.components.ActionLink import com.intellij.ui.components.panels.Wrapper import com.intellij.util.ui.JBUI import com.intellij.util.ui.UI import com.intellij.util.ui.UIUtil import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.action.GHPRReloadStateAction import org.jetbrains.plugins.github.pullrequest.data.service.GHPRSecurityService import org.jetbrains.plugins.github.pullrequest.ui.details.* import org.jetbrains.plugins.github.pullrequest.ui.timeline.GHPRTitleComponent import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider import org.jetbrains.plugins.github.ui.util.HtmlEditorPane import javax.swing.BorderFactory import javax.swing.JComponent import javax.swing.JPanel internal object GHPRDetailsComponent { fun create(securityService: GHPRSecurityService, avatarIconsProvider: GHAvatarIconsProvider, branchesModel: GHPRBranchesModel, detailsModel: GHPRDetailsModel, metadataModel: GHPRMetadataModel, stateModel: GHPRStateModel): JComponent { val actionManager = ActionManager.getInstance() val branches = GHPRBranchesPanel.create(branchesModel) val title = GHPRTitleComponent.create(detailsModel) val description = HtmlEditorPane().apply { detailsModel.addAndInvokeDetailsChangedListener { setBody(detailsModel.description) } } val timelineLink = ActionLink(GithubBundle.message("pull.request.view.conversations.action")) { val action = ActionManager.getInstance().getAction("Github.PullRequest.Timeline.Show") ?: return@ActionLink ActionUtil.invokeAction(action, it.source as ActionLink, ActionPlaces.UNKNOWN, null, null) } val metadata = GHPRMetadataPanelFactory(metadataModel, avatarIconsProvider).create() val state = GHPRStatePanel(securityService, stateModel).also { detailsModel.addAndInvokeDetailsChangedListener { it.select(detailsModel.state, true) } PopupHandler.installPopupMenu(it, DefaultActionGroup(GHPRReloadStateAction()), "GHPRStatePanelPopup") } metadata.border = BorderFactory.createCompoundBorder(IdeBorderFactory.createBorder(SideBorder.TOP), JBUI.Borders.empty(8)) state.border = BorderFactory.createCompoundBorder(IdeBorderFactory.createBorder(SideBorder.TOP), JBUI.Borders.empty(8)) val detailsSection = JPanel(MigLayout(LC().insets("0", "0", "0", "0") .gridGap("0", "0") .fill().flowY())).apply { isOpaque = false border = JBUI.Borders.empty(8) add(branches, CC().gapBottom("${UI.scale(8)}")) add(title, CC().gapBottom("${UI.scale(8)}")) add(description, CC().grow().push().minHeight("0")) add(timelineLink, CC().gapBottom("push")) } val groupId = "Github.PullRequest.Details.Popup" PopupHandler.installPopupMenu(detailsSection, groupId, groupId) PopupHandler.installPopupMenu(description, groupId, groupId) PopupHandler.installPopupMenu(metadata, groupId, groupId) return JPanel(MigLayout(LC().insets("0", "0", "0", "0") .gridGap("0", "0") .fill().flowY())).apply { isOpaque = false add(detailsSection, CC().grow().push().minHeight("0")) add(metadata, CC().growX().pushX()) add(Wrapper(state).apply { isOpaque = true background = UIUtil.getPanelBackground() }, CC().growX().pushX().minHeight("pref")) } } }
apache-2.0
ddcf4639b66a470bac94a61ec7516ee2
44.547368
140
0.70712
4.681818
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/structuralsearch/binaryExpression/binaryDiv.kt
4
126
val a = <warning descr="SSR">1 / 2</warning> val b = <warning descr="SSR">1.div(2)</warning> val c = 1 / 3 val d = 1.div(3)
apache-2.0
d4c9ab762e26a42b28c94b6684166c94
17.142857
47
0.587302
2.377358
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/mapMinOrNull.kt
2
380
// API_VERSION: 1.4 // WITH_RUNTIME data class OrderItem(val name: String, val price: Double, val count: Int) fun main() { val order = listOf<OrderItem>( OrderItem("Cake", price = 10.0, count = 1), OrderItem("Coffee", price = 2.5, count = 3), OrderItem("Tea", price = 1.5, count = 2) ) val min = order.map<caret> { it.price }.minOrNull()!! }
apache-2.0
8fbeaff7b5980c0fd3265df491540b8f
26.214286
73
0.589474
3.275862
false
false
false
false
hugh114/HPaste
app/src/main/java/com/hugh/paste/app/Application.kt
1
1531
package com.hugh.paste.app import android.app.ActivityManager import android.app.Application import android.content.Context import android.text.TextUtils import com.hugh.paste.utils.HPrefs /** * Created by hugh on 2017/9/29. */ class Application : Application() { override fun onCreate() { super.onCreate() if (inMainProcess()) { HPrefs.init(this) } } /** * 是否在主进程 * * @return */ private fun inMainProcess(): Boolean { val packageName = packageName val processName = getProcessName(this) return packageName == processName } /** * 获取当前进程名称 * * @param context * @return */ private fun getProcessName(context: Context): String? { var processName: String? = null // ActivityManager val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager while (true) { for (info in am.runningAppProcesses) { if (info.pid == android.os.Process.myPid()) { processName = info.processName break } } // go home if (!TextUtils.isEmpty(processName)) { return processName } // take a rest and again try { Thread.sleep(100L) } catch (ex: InterruptedException) { ex.printStackTrace() } } } }
gpl-3.0
b3300f7b58f5133f55d5c4c9e07fc8f0
21.117647
86
0.536261
4.667702
false
false
false
false
iceboundrock/nextday-for-android
app/src/main/kotlin/li/ruoshi/nextday/views/DaysAdapter.kt
1
3522
package li.ruoshi.nextday.views import android.content.Context import android.support.v4.view.PagerAdapter import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import li.ruoshi.nextday.R import li.ruoshi.nextday.models.DailyInfo import java.lang.ref.WeakReference import java.util.* import java.util.concurrent.ArrayBlockingQueue /** * Created by ruoshili on 1/10/16. */ class DaysAdapter(val context: Context) : PagerAdapter() { companion object { const val TAG = "DaysAdapter" } private val mDestroyedViewHolders: Queue<WeakReference<DayViewHolder>> = ArrayBlockingQueue(8) private val mViewHoldersCache: MutableList<DayViewHolder> = ArrayList(8) override fun isViewFromObject(view: View?, obj: Any?): Boolean { return (obj is DayViewHolder) && view == obj.view } override fun destroyItem(container: ViewGroup?, position: Int, obj: Any?) { Log.d(TAG, "destroyItem, pos: $position, obj: ${obj?.javaClass}") if (obj is DayViewHolder) { container?.removeView(obj.view) mDestroyedViewHolders.offer(WeakReference(obj)) } Log.d(TAG, "destroyItem, end, mDestroyedViewHolders size: ${mDestroyedViewHolders.size}") } private var createViewTimes = 0 private fun createViewHolder(container: ViewGroup?): DayViewHolder { Log.d(TAG, "createViewHolder, times: ${++createViewTimes}") val inflater = LayoutInflater.from(context); val layout = inflater.inflate(R.layout.day_view, container, false); return DayViewHolder(context, layout) } override fun instantiateItem(container: ViewGroup?, position: Int): Any? { Log.d(TAG, "instantiateItem, pos: $position") if (position < 3) { // TODO: 加载 } var viewHolder: DayViewHolder? = null while (!mDestroyedViewHolders.isEmpty()) { val r = mDestroyedViewHolders.poll() if (r.get() == null) { Log.d(TAG, "weak ref has no value") continue } else { viewHolder = r.get() break } } if (viewHolder == null) { Log.d(TAG, "mDestroyedViewHolders is empty, create new view holder") viewHolder = createViewHolder(container) } viewHolder.setData(list!![position]) container?.addView(viewHolder.view) updateCache(viewHolder) return viewHolder } private fun updateCache(viewHolder: DayViewHolder) { if (mViewHoldersCache.size > 0) { for (i in 0..(mViewHoldersCache.size - 1)) { if (mViewHoldersCache[i] == viewHolder) { return } } } mViewHoldersCache.add(viewHolder) Log.d(TAG, "added a new view holder to cache, current cache size: ${mViewHoldersCache.size}") } fun getViewHolderAt(pos: Int): DayViewHolder? { if (pos < 0 || pos >= count) { return null } val data = list!![pos] return mViewHoldersCache.filter { it.getData() == data }.firstOrNull() } override fun getCount(): Int { if (list == null) { return 0 } return list!!.count() } var list: List<DailyInfo>? = null fun setDailyInfo(list: List<DailyInfo>) { this.list = list notifyDataSetChanged() } }
apache-2.0
4810504b61c2e7d73ecd1990e1daa5d6
28.325
101
0.6083
4.441919
false
false
false
false
androidx/androidx
compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/snapshots/SnapshotStateMap.kt
3
13610
/* * 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.compose.runtime.snapshots import androidx.compose.runtime.Stable import androidx.compose.runtime.external.kotlinx.collections.immutable.PersistentMap import androidx.compose.runtime.external.kotlinx.collections.immutable.persistentHashMapOf import androidx.compose.runtime.synchronized import kotlin.jvm.JvmName /** * An implementation of [MutableMap] that can be observed and snapshot. This is the result type * created by [androidx.compose.runtime.mutableStateMapOf]. * * This class closely implements the same semantics as [HashMap]. * * @see androidx.compose.runtime.mutableStateMapOf */ @Stable class SnapshotStateMap<K, V> : MutableMap<K, V>, StateObject { override var firstStateRecord: StateRecord = StateMapStateRecord<K, V>(persistentHashMapOf()) private set override fun prependStateRecord(value: StateRecord) { @Suppress("UNCHECKED_CAST") firstStateRecord = value as StateMapStateRecord<K, V> } /** * Returns an immutable map containing all key-value pairs from the original map. * * The content of the map returned will not change even if the content of the map is changed in * the same snapshot. It also will be the same instance until the content is changed. It is not, * however, guaranteed to be the same instance for the same content as adding and removing the * same item from the this map might produce a different instance with the same content. * * This operation is O(1) and does not involve a physically copying the map. It instead * returns the underlying immutable map used internally to store the content of the map. * * It is recommended to use [toMap] when using returning the value of this map from * [androidx.compose.runtime.snapshotFlow]. */ fun toMap(): Map<K, V> = readable.map override val size get() = readable.map.size override fun containsKey(key: K) = readable.map.containsKey(key) override fun containsValue(value: V) = readable.map.containsValue(value) override fun get(key: K) = readable.map[key] override fun isEmpty() = readable.map.isEmpty() override val entries: MutableSet<MutableMap.MutableEntry<K, V>> = SnapshotMapEntrySet(this) override val keys: MutableSet<K> = SnapshotMapKeySet(this) override val values: MutableCollection<V> = SnapshotMapValueSet(this) override fun clear() = update { persistentHashMapOf() } override fun put(key: K, value: V): V? = mutate { it.put(key, value) } override fun putAll(from: Map<out K, V>) = mutate { it.putAll(from) } override fun remove(key: K): V? = mutate { it.remove(key) } internal val modification get() = readable.modification internal fun removeValue(value: V) = entries.firstOrNull { it.value == value }?.let { remove(it.key); true } == true @Suppress("UNCHECKED_CAST") internal val readable: StateMapStateRecord<K, V> get() = (firstStateRecord as StateMapStateRecord<K, V>).readable(this) internal inline fun removeIf(predicate: (MutableMap.MutableEntry<K, V>) -> Boolean): Boolean { var removed = false mutate { for (entry in this.entries) { if (predicate(entry)) { it.remove(entry.key) removed = true } } } return removed } internal inline fun any(predicate: (Map.Entry<K, V>) -> Boolean): Boolean { for (entry in readable.map.entries) { if (predicate(entry)) return true } return false } internal inline fun all(predicate: (Map.Entry<K, V>) -> Boolean): Boolean { for (entry in readable.map.entries) { if (!predicate(entry)) return false } return true } /** * An internal function used by the debugger to display the value of the current value of the * mutable state object without triggering read observers. */ @Suppress("unused") internal val debuggerDisplayValue: Map<K, V> @JvmName("getDebuggerDisplayValue") get() = withCurrent { map } private inline fun <R> withCurrent(block: StateMapStateRecord<K, V>.() -> R): R = @Suppress("UNCHECKED_CAST") (firstStateRecord as StateMapStateRecord<K, V>).withCurrent(block) private inline fun <R> writable(block: StateMapStateRecord<K, V>.() -> R): R = @Suppress("UNCHECKED_CAST") (firstStateRecord as StateMapStateRecord<K, V>).writable(this, block) private inline fun <R> mutate(block: (MutableMap<K, V>) -> R): R { var result: R while (true) { var oldMap: PersistentMap<K, V>? = null var currentModification = 0 synchronized(sync) { val current = withCurrent { this } oldMap = current.map currentModification = current.modification } val builder = oldMap!!.builder() result = block(builder) val newMap = builder.build() if (newMap == oldMap || synchronized(sync) { writable { if (modification == currentModification) { map = newMap modification++ true } else false } } ) break } return result } private inline fun update(block: (PersistentMap<K, V>) -> PersistentMap<K, V>) = withCurrent { val newMap = block(map) if (newMap !== map) synchronized(sync) { writable { map = newMap modification++ } } } /** * Implementation class of [SnapshotStateMap]. Do not use. */ internal class StateMapStateRecord<K, V> internal constructor( internal var map: PersistentMap<K, V> ) : StateRecord() { internal var modification = 0 override fun assign(value: StateRecord) { @Suppress("UNCHECKED_CAST") val other = (value as StateMapStateRecord<K, V>) synchronized(sync) { map = other.map modification = other.modification } } override fun create(): StateRecord = StateMapStateRecord(map) } } private abstract class SnapshotMapSet<K, V, E>( val map: SnapshotStateMap<K, V> ) : MutableSet<E> { override val size: Int get() = map.size override fun clear() = map.clear() override fun isEmpty() = map.isEmpty() } private class SnapshotMapEntrySet<K, V>( map: SnapshotStateMap<K, V> ) : SnapshotMapSet<K, V, MutableMap.MutableEntry<K, V>>(map) { override fun add(element: MutableMap.MutableEntry<K, V>) = unsupported() override fun addAll(elements: Collection<MutableMap.MutableEntry<K, V>>) = unsupported() override fun iterator(): MutableIterator<MutableMap.MutableEntry<K, V>> = StateMapMutableEntriesIterator(map, map.readable.map.entries.iterator()) override fun remove(element: MutableMap.MutableEntry<K, V>) = map.remove(element.key) != null override fun removeAll(elements: Collection<MutableMap.MutableEntry<K, V>>): Boolean { var removed = false for (element in elements) { removed = map.remove(element.key) != null || removed } return removed } override fun retainAll(elements: Collection<MutableMap.MutableEntry<K, V>>): Boolean { val entries = elements.associate { it.key to it.value } return map.removeIf { !entries.containsKey(it.key) || entries[it.key] != it.value } } override fun contains(element: MutableMap.MutableEntry<K, V>): Boolean { return map[element.key] == element.value } override fun containsAll(elements: Collection<MutableMap.MutableEntry<K, V>>): Boolean { return elements.all { contains(it) } } } private class SnapshotMapKeySet<K, V>(map: SnapshotStateMap<K, V>) : SnapshotMapSet<K, V, K>(map) { override fun add(element: K) = unsupported() override fun addAll(elements: Collection<K>) = unsupported() override fun iterator() = StateMapMutableKeysIterator(map, map.readable.map.entries.iterator()) override fun remove(element: K): Boolean = map.remove(element) != null override fun removeAll(elements: Collection<K>): Boolean { var removed = false elements.forEach { removed = map.remove(it) != null || removed } return removed } override fun retainAll(elements: Collection<K>): Boolean { val set = elements.toSet() return map.removeIf { it.key !in set } } override fun contains(element: K) = map.contains(element) override fun containsAll(elements: Collection<K>): Boolean = elements.all { map.contains(it) } } private class SnapshotMapValueSet<K, V>( map: SnapshotStateMap<K, V> ) : SnapshotMapSet<K, V, V>(map) { override fun add(element: V) = unsupported() override fun addAll(elements: Collection<V>) = unsupported() override fun iterator() = StateMapMutableValuesIterator(map, map.readable.map.entries.iterator()) override fun remove(element: V): Boolean = map.removeValue(element) override fun removeAll(elements: Collection<V>): Boolean { val set = elements.toSet() return map.removeIf { it.value in set } } override fun retainAll(elements: Collection<V>): Boolean { val set = elements.toSet() return map.removeIf { it.value !in set } } override fun contains(element: V) = map.containsValue(element) override fun containsAll(elements: Collection<V>): Boolean { return elements.all { map.containsValue(it) } } } /** * This lock is used to ensure that the value of modification and the map in the state record, * when used together, are atomically read and written. * * A global sync object is used to avoid having to allocate a sync object and initialize a monitor * for each instance the map. This avoids additional allocations but introduces some contention * between maps. As there is already contention on the global snapshot lock to write so the * additional contention introduced by this lock is nominal. * * In code the requires this lock and calls `writable` (or other operation that acquires the * snapshot global lock), this lock *MUST* be acquired first to avoid deadlocks. */ private val sync = Any() private abstract class StateMapMutableIterator<K, V>( val map: SnapshotStateMap<K, V>, val iterator: Iterator<Map.Entry<K, V>> ) { protected var modification = map.modification protected var current: Map.Entry<K, V>? = null protected var next: Map.Entry<K, V>? = null init { advance() } fun remove() = modify { val value = current if (value != null) { map.remove(value.key) current = null } else { throw IllegalStateException() } } fun hasNext() = next != null protected fun advance() { current = next next = if (iterator.hasNext()) iterator.next() else null } protected inline fun <T> modify(block: () -> T): T { if (map.modification != modification) { throw ConcurrentModificationException() } return block().also { modification = map.modification } } } private class StateMapMutableEntriesIterator<K, V>( map: SnapshotStateMap<K, V>, iterator: Iterator<Map.Entry<K, V>> ) : StateMapMutableIterator<K, V>(map, iterator), MutableIterator<MutableMap.MutableEntry<K, V>> { override fun next(): MutableMap.MutableEntry<K, V> { advance() if (current != null) { return object : MutableMap.MutableEntry<K, V> { override val key = current!!.key override var value = current!!.value override fun setValue(newValue: V): V = modify { val result = value map[key] = newValue value = newValue return result } } } else { throw IllegalStateException() } } } private class StateMapMutableKeysIterator<K, V>( map: SnapshotStateMap<K, V>, iterator: Iterator<Map.Entry<K, V>> ) : StateMapMutableIterator<K, V>(map, iterator), MutableIterator<K> { override fun next(): K { val result = next ?: throw IllegalStateException() advance() return result.key } } private class StateMapMutableValuesIterator<K, V>( map: SnapshotStateMap<K, V>, iterator: Iterator<Map.Entry<K, V>> ) : StateMapMutableIterator<K, V>(map, iterator), MutableIterator<V> { override fun next(): V { val result = next ?: throw IllegalStateException() advance() return result.value } } internal fun unsupported(): Nothing { throw UnsupportedOperationException() }
apache-2.0
0d3628351338d718a38e9b9e707dbf55
36.910864
100
0.640485
4.373393
false
false
false
false
androidx/androidx
annotation/annotation-experimental-lint/src/main/java/androidx/annotation/experimental/lint/ExperimentalDetector.kt
3
35499
/* * Copyright 2019 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. */ @file:Suppress("UnstableApiUsage", "SyntheticAccessor") package androidx.annotation.experimental.lint import com.android.tools.lint.client.api.JavaEvaluator import com.android.tools.lint.detector.api.AnnotationUsageType import com.android.tools.lint.detector.api.AnnotationUsageType.FIELD_REFERENCE import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.LintFix import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.SourceCodeScanner import com.android.tools.lint.detector.api.isKotlin import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElement import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import com.intellij.psi.PsiModifier import com.intellij.psi.PsiModifierListOwner import com.intellij.psi.PsiPackage import com.intellij.psi.impl.source.PsiClassReferenceType import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiTypesUtil import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeAsciiOnly import org.jetbrains.kotlin.util.capitalizeDecapitalize.toLowerCaseAsciiOnly import org.jetbrains.uast.UAnnotated import org.jetbrains.uast.UAnnotation import org.jetbrains.uast.UAnonymousClass import org.jetbrains.uast.UArrayAccessExpression import org.jetbrains.uast.UBinaryExpression import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UCallableReferenceExpression import org.jetbrains.uast.UClass import org.jetbrains.uast.UClassLiteralExpression import org.jetbrains.uast.UDeclaration import org.jetbrains.uast.UElement import org.jetbrains.uast.UEnumConstant import org.jetbrains.uast.UExpression import org.jetbrains.uast.ULambdaExpression import org.jetbrains.uast.UMethod import org.jetbrains.uast.UReferenceExpression import org.jetbrains.uast.USimpleNameReferenceExpression import org.jetbrains.uast.UVariable import org.jetbrains.uast.UastFacade import org.jetbrains.uast.getContainingUClass import org.jetbrains.uast.getContainingUMethod import org.jetbrains.uast.java.JavaUAnnotation import org.jetbrains.uast.toUElement import org.jetbrains.uast.tryResolve class ExperimentalDetector : Detector(), SourceCodeScanner { private val visitedUsages: MutableMap<UElement, MutableSet<String>> = mutableMapOf() override fun applicableAnnotations(): List<String> = listOf( JAVA_EXPERIMENTAL_ANNOTATION, KOTLIN_EXPERIMENTAL_ANNOTATION, JAVA_REQUIRES_OPT_IN_ANNOTATION, KOTLIN_REQUIRES_OPT_IN_ANNOTATION ) override fun applicableSuperClasses(): List<String> = listOf( "java.lang.Object" ) override fun visitClass( context: JavaContext, lambda: ULambdaExpression, ) { // Infer the overridden method by taking the first (and only) abstract method from the // functional interface being implemented. val superClass = (lambda.functionalInterfaceType as? PsiClassReferenceType)?.resolve() val superMethod = superClass?.allMethods ?.first { method -> method.isAbstract() } ?.toUElement() if (superMethod is UMethod) { checkMethodOverride(context, lambda, superMethod) } } override fun visitClass( context: JavaContext, declaration: UClass, ) { declaration.methods.forEach { method -> val eval = context.evaluator if (eval.isOverride(method, true)) { method.findSuperMethods().forEach { superMethod -> checkMethodOverride(context, method, superMethod) } } } } /** * Extract the relevant annotations from the method override and run the checks * on the annotations. * * Based on Lint's `AnnotationHandler.checkCall)()`. */ private fun checkMethodOverride( context: JavaContext, usage: UElement, superMethod: PsiMethod, ) { val evaluator = context.evaluator val allAnnotations = evaluator.getAllAnnotations(superMethod, inHierarchy = true) val methodAnnotations = filterRelevantAnnotations(evaluator, allAnnotations) // Look for annotations on the class as well: these trickle // down to all the methods in the class val containingClass: PsiClass? = superMethod.containingClass val (classAnnotations, pkgAnnotations) = getClassAndPkgAnnotations( containingClass, evaluator ) doCheckMethodOverride( context, superMethod, methodAnnotations, classAnnotations, pkgAnnotations, usage, containingClass, ) } /** * Do the checks of a method override based on the method, class, and package * annotations given. * * Based on Lint's `AnnotationHandler.doCheckCall()`. */ private fun doCheckMethodOverride( context: JavaContext, superMethod: PsiMethod?, methodAnnotations: List<UAnnotation>, classAnnotations: List<UAnnotation>, pkgAnnotations: List<UAnnotation>, usage: UElement, containingClass: PsiClass?, ) { if (methodAnnotations.isNotEmpty()) { checkAnnotations( context, argument = usage, type = AnnotationUsageType.METHOD_CALL, method = superMethod, referenced = superMethod, annotations = methodAnnotations, allMethodAnnotations = methodAnnotations, allClassAnnotations = classAnnotations, packageAnnotations = pkgAnnotations, annotated = superMethod, ) } if (containingClass != null && classAnnotations.isNotEmpty()) { checkAnnotations( context, argument = usage, type = AnnotationUsageType.METHOD_CALL_CLASS, method = superMethod, referenced = superMethod, annotations = classAnnotations, allMethodAnnotations = methodAnnotations, allClassAnnotations = classAnnotations, packageAnnotations = pkgAnnotations, annotated = containingClass, ) } if (pkgAnnotations.isNotEmpty()) { checkAnnotations( context, argument = usage, type = AnnotationUsageType.METHOD_CALL_PACKAGE, method = superMethod, referenced = superMethod, annotations = pkgAnnotations, allMethodAnnotations = methodAnnotations, allClassAnnotations = classAnnotations, packageAnnotations = pkgAnnotations, annotated = null, ) } } /** * Copied from Lint's `AnnotationHandler.checkAnnotations()` with modifications to operate on * this detector only, rather than a list of scanners. */ private fun checkAnnotations( context: JavaContext, argument: UElement, type: AnnotationUsageType, method: PsiMethod?, referenced: PsiElement?, annotations: List<UAnnotation>, allMethodAnnotations: List<UAnnotation> = emptyList(), allClassAnnotations: List<UAnnotation> = emptyList(), packageAnnotations: List<UAnnotation> = emptyList(), annotated: PsiElement? ) { for (annotation in annotations) { val signature = annotation.qualifiedName ?: continue var uAnnotations: List<UAnnotation>? = null var psiAnnotations: Array<out PsiAnnotation>? = null // Modification: Removed loop over uastScanners list. if (isApplicableAnnotationUsage(type)) { // Some annotations should not be treated as inherited though // the hierarchy: if that's the case for this annotation in // this scanner, check whether it's inherited and if so, skip it if (annotated != null && !inheritAnnotation(signature)) { // First try to look by directly checking the owner element of // the annotation. val annotationOwner = (annotation.sourcePsi as? PsiAnnotation)?.owner val owner = if (annotationOwner is PsiElement) { PsiTreeUtil.getParentOfType( annotationOwner, PsiModifierListOwner::class.java ) } else { null } if (owner != null) { val annotatedPsi = (annotated as? UElement)?.sourcePsi ?: annotated if (owner != annotatedPsi) { continue } } else { // Figure out if this is an inherited annotation: it would be // if it's not annotated on the element if (annotated is UAnnotated) { var found = false for ( uAnnotation in uAnnotations ?: run { val list = context.evaluator.getAllAnnotations( annotated, inHierarchy = false ) uAnnotations = list list } ) { val qualifiedName = uAnnotation.qualifiedName if (qualifiedName == signature) { found = true break } } if (!found) { continue } } if (annotated is PsiModifierListOwner) { var found = false for ( psiAnnotation in psiAnnotations ?: run { val array = context.evaluator.getAllAnnotations(annotated, false) psiAnnotations = array array } ) { val qualifiedName = psiAnnotation.qualifiedName if (qualifiedName == signature) { found = true break } } if (!found) { continue } } } } visitAnnotationUsage( context, argument, type, annotation, signature, method, referenced, annotations, allMethodAnnotations, allClassAnnotations, packageAnnotations ) } } } /** * Copied from Lint's `AnnotationHandler`. */ private fun getClassAndPkgAnnotations( containingClass: PsiClass?, evaluator: JavaEvaluator, ): Pair<List<UAnnotation>, List<UAnnotation>> { // Yes, returning a pair is ugly. But we are initializing two lists, and splitting this // into two methods takes more lines of code then it saves over copying this block into // two methods. // Plus, destructuring assignment makes using the results less verbose. val classAnnotations: List<UAnnotation> val pkgAnnotations: List<UAnnotation> if (containingClass != null) { val annotations = evaluator.getAllAnnotations(containingClass, inHierarchy = true) classAnnotations = filterRelevantAnnotations(evaluator, annotations) val pkg = evaluator.getPackage(containingClass) pkgAnnotations = if (pkg != null) { val annotations2 = evaluator.getAllAnnotations(pkg, inHierarchy = false) filterRelevantAnnotations(evaluator, annotations2) } else { emptyList() } } else { classAnnotations = emptyList() pkgAnnotations = emptyList() } return Pair(classAnnotations, pkgAnnotations) } /** * Copied from Lint's `AnnotationHandler`. */ private fun filterRelevantAnnotations( evaluator: JavaEvaluator, annotations: Array<PsiAnnotation>, ): List<UAnnotation> { var result: MutableList<UAnnotation>? = null val length = annotations.size if (length == 0) { return emptyList() } for (annotation in annotations) { val signature = annotation.qualifiedName if (signature == null || ( signature.startsWith("kotlin.") || signature.startsWith("java.") ) && !relevantAnnotations.contains(signature) ) { // @Override, @SuppressWarnings etc. Ignore continue } if (relevantAnnotations.contains(signature)) { val uAnnotation = JavaUAnnotation.wrap(annotation) // Common case: there's just one annotation; no need to create a list copy if (length == 1) { return listOf(uAnnotation) } if (result == null) { result = ArrayList(2) } result.add(uAnnotation) continue } // Special case @IntDef and @StringDef: These are used on annotations // themselves. For example, you create a new annotation named @foo.bar.Baz, // annotate it with @IntDef, and then use @foo.bar.Baz in your signatures. // Here we want to map from @foo.bar.Baz to the corresponding int def. // Don't need to compute this if performing @IntDef or @StringDef lookup val cls = annotation.nameReferenceElement?.resolve() ?: run { val project = annotation.project JavaPsiFacade.getInstance(project).findClass( signature, GlobalSearchScope.projectScope(project) ) } ?: continue if (cls !is PsiClass || !cls.isAnnotationType) { continue } val innerAnnotations = evaluator.getAllAnnotations(cls, inHierarchy = false) for (j in innerAnnotations.indices) { val inner = innerAnnotations[j] val a = inner.qualifiedName if (a != null && relevantAnnotations.contains(a)) { if (result == null) { result = ArrayList(2) } val innerU = UastFacade.convertElement( inner, null, UAnnotation::class.java ) as UAnnotation result.add(innerU) } } } return result ?: emptyList() } // Used for drop-in compatibility with code from Lint's `AnnotationHandler`. private val relevantAnnotations: List<String> get() = applicableAnnotations() override fun visitAnnotationUsage( context: JavaContext, usage: UElement, type: AnnotationUsageType, annotation: UAnnotation, qualifiedName: String, method: PsiMethod?, referenced: PsiElement?, annotations: List<UAnnotation>, allMemberAnnotations: List<UAnnotation>, allClassAnnotations: List<UAnnotation>, allPackageAnnotations: List<UAnnotation> ) { // Are we visiting a Kotlin property as a field reference when it's actually a method? // Ignore it, since we'll also visit it as a method. if (isKotlin(usage.sourcePsi) && type == FIELD_REFERENCE && referenced is PsiMethod) { return } when (qualifiedName) { JAVA_EXPERIMENTAL_ANNOTATION, JAVA_REQUIRES_OPT_IN_ANNOTATION -> { // Only allow Java annotations, since the Kotlin compiler doesn't understand our // annotations and could get confused when it's trying to opt-in to some random // annotation that it doesn't understand. checkExperimentalUsage( context, annotation, referenced, usage, listOf( JAVA_USE_EXPERIMENTAL_ANNOTATION, JAVA_OPT_IN_ANNOTATION ), ) } KOTLIN_EXPERIMENTAL_ANNOTATION, KOTLIN_REQUIRES_OPT_IN_ANNOTATION -> { // Don't check usages of Kotlin annotations from Kotlin sources, since the Kotlin // compiler handles that already. Allow either Java or Kotlin annotations, since // we can enforce both and it's possible that a Kotlin-sourced experimental library // is being used from Java without the Kotlin stdlib in the classpath. if (!isKotlin(usage.sourcePsi)) { checkExperimentalUsage( context, annotation, referenced, usage, listOf( KOTLIN_USE_EXPERIMENTAL_ANNOTATION, KOTLIN_OPT_IN_ANNOTATION, JAVA_USE_EXPERIMENTAL_ANNOTATION, JAVA_OPT_IN_ANNOTATION ), ) } } } } /** * Check whether the given experimental API [annotation] can be referenced from [usage] call * site. * * @param context the lint scanning context * @param annotation the experimental opt-in annotation detected on the referenced element * @param usage the element whose usage should be checked * @param optInFqNames fully-qualified class name for experimental opt-in annotation */ private fun checkExperimentalUsage( context: JavaContext, annotation: UAnnotation, referenced: PsiElement?, usage: UElement, optInFqNames: List<String> ) { val annotationFqName = (annotation.uastParent as? UClass)?.qualifiedName ?: return // This method may get called multiple times when there is more than one instance of the // annotation in the hierarchy. We don't care which one we're looking at, but we shouldn't // report the same usage and annotation pair multiple times. val visitedAnnotations = visitedUsages.getOrPut(usage) { mutableSetOf() } if (!visitedAnnotations.add(annotationFqName)) { return } // Check whether the usage actually considered experimental. val decl = referenced.toUElement() ?: usage.getReferencedElement() ?: return if (!decl.isExperimentalityRequired(context, annotationFqName)) { return } // Check whether the usage is acceptable, either due to opt-in or propagation. if (usage.isExperimentalityAccepted(context, annotationFqName, optInFqNames)) { return } // For some reason we can't read the explicit default level from the compiled version // of `kotlin.Experimental` (but we can from `kotlin.RequiresOptIn`... go figure). It's // possible that we'll fail to read the level for other reasons, but the safest // fallback is `ERROR` either way. val level = annotation.extractAttribute(context, "level", "ERROR") if (level != null) { report( context, usage, annotationFqName, "This declaration is opt-in and its usage should be marked with " + "`@$annotationFqName` or `@OptIn(markerClass = $annotationFqName.class)`", level ) } else { // This is a more serious failure where we obtained a representation that we // couldn't understand. report( context, usage, annotationFqName, "Failed to read `level` from `@$annotationFqName` -- assuming `ERROR`. " + "This declaration is opt-in and its usage should be marked with " + "`@$annotationFqName` or `@OptIn(markerClass = $annotationFqName.class)`", "ERROR" ) } } /** * Determines if the element is within scope of the experimental marker identified by * [annotationFqName], thus whether it requires either opt-in or propagation of the marker. * * This is functionally equivalent to a containment check for [annotationFqName] on the result * of the Kotlin compiler's implementation of `DeclarationDescriptor.loadExperimentalities()` * within `ExperimentalUsageChecker`. */ private fun UElement.isExperimentalityRequired( context: JavaContext, annotationFqName: String, ): Boolean { // Is the element itself experimental? if (isDeclarationAnnotatedWith(annotationFqName)) { return true } // Is a parent of the element experimental? Kotlin's implementation skips this check if // the current element is a constructor method, but it's required when we're looking at // the syntax tree through UAST. Unclear why. if ((uastParent as? UClass)?.isExperimentalityRequired(context, annotationFqName) == true) { return true } // Is the containing package experimental? if (context.evaluator.getPackage(this)?.getAnnotation(annotationFqName) != null) { return true } return false } /** * Returns whether the element has accepted the scope of the experimental marker identified by * [annotationFqName], either by opting-in via an annotation in [optInFqNames] or propagating * the marker. * * This is functionally equivalent to the Kotlin compiler's implementation of * `PsiElement.isExperimentalityAccepted()` within `ExperimentalUsageChecker`. */ private fun UElement.isExperimentalityAccepted( context: JavaContext, annotationFqName: String, optInFqNames: List<String>, ): Boolean { val config = context.configuration return config.getOption(ISSUE_ERROR, "opt-in")?.contains(annotationFqName) == true || config.getOption(ISSUE_WARNING, "opt-in")?.contains(annotationFqName) == true || anyParentMatches({ element -> element.isDeclarationAnnotatedWith(annotationFqName) || element.isDeclarationAnnotatedWithOptInOf(annotationFqName, optInFqNames) }) || context.evaluator.getPackage(this)?.let { element -> element.isAnnotatedWith(annotationFqName) || element.isAnnotatedWithOptInOf(annotationFqName, optInFqNames) } ?: false } private fun createLintFix( context: JavaContext, usage: UElement, annotation: String, ): LintFix { val propagateAnnotation = "@$annotation" val lintFixes = fix().alternatives() usage.getContainingUMethod()?.let { containingMethod -> val isKotlin = isKotlin(usage.sourcePsi) val optInAnnotation = if (isKotlin) { "@androidx.annotation.OptIn($annotation::class)" } else { "@androidx.annotation.OptIn(markerClass = $annotation.class)" } lintFixes.add(createAnnotateFix(context, containingMethod, optInAnnotation)) lintFixes.add(createAnnotateFix(context, containingMethod, propagateAnnotation)) } usage.getContainingUClass()?.let { containingClass -> lintFixes.add(createAnnotateFix(context, containingClass, propagateAnnotation)) } return lintFixes.build() } private fun createAnnotateFix( context: JavaContext, element: UDeclaration, annotation: String, ): LintFix { val elementLabel = when (element) { is UMethod -> "'${element.name}'" is UClass -> "containing class '${element.name}'" is UAnonymousClass -> "containing anonymous class" else -> throw IllegalArgumentException("Unsupported element type") } // If the element has a modifier list, e.g. not an anonymous class or lambda, then place the // insertion point at the beginning of the modifiers list. This ensures that we don't insert // the annotation in an invalid position, such as after the "public" or "fun" keywords. We // also don't want to place it on the element range itself, since that would place it before // the comments. val elementLocation = context.getLocation(element.modifierList ?: element as UElement) return fix() .replace() .name("Add '$annotation' annotation to $elementLabel") .range(elementLocation) .beginning() .shortenNames() .with("$annotation ") .build() } /** * Reports an issue and trims indentation on the [message]. */ private fun report( context: JavaContext, usage: UElement, annotation: String, message: String, level: String, ) { val issue = when (level) { ENUM_ERROR -> ISSUE_ERROR ENUM_WARNING -> ISSUE_WARNING else -> throw IllegalArgumentException( "Level was \"$level\" but must be one of: $ENUM_ERROR, $ENUM_WARNING" ) } try { if (context.configuration.getOption(issue, "opt-in")?.contains(annotation) != true) { context.report(issue, usage, context.getNameLocation(usage), message.trimIndent(), createLintFix(context, usage, annotation)) } } catch (e: UnsupportedOperationException) { if ("Method not implemented" == e.message) { // Workaround for b/191286558 where lint attempts to read annotations from a // compiled UAST parent of `usage`. Swallow the exception and don't report anything. } else { throw e } } } companion object { private val IMPLEMENTATION = Implementation( ExperimentalDetector::class.java, Scope.JAVA_FILE_SCOPE, ) const val KOTLIN_EXPERIMENTAL_ANNOTATION = "kotlin.Experimental" const val KOTLIN_USE_EXPERIMENTAL_ANNOTATION = "kotlin.UseExperimental" const val KOTLIN_OPT_IN_ANNOTATION = "kotlin.OptIn" const val KOTLIN_REQUIRES_OPT_IN_ANNOTATION = "kotlin.RequiresOptIn" const val JAVA_EXPERIMENTAL_ANNOTATION = "androidx.annotation.experimental.Experimental" const val JAVA_USE_EXPERIMENTAL_ANNOTATION = "androidx.annotation.experimental.UseExperimental" const val JAVA_REQUIRES_OPT_IN_ANNOTATION = "androidx.annotation.RequiresOptIn" const val JAVA_OPT_IN_ANNOTATION = "androidx.annotation.OptIn" const val ENUM_ERROR = "ERROR" const val ENUM_WARNING = "WARNING" private fun issueForLevel( levelEnum: String, severity: Severity, ): Issue { val levelText = levelEnum.toLowerCaseAsciiOnly() val issueId = "UnsafeOptInUsage${levelText.capitalizeAsciiOnly()}" return Issue.create( id = issueId, briefDescription = "Unsafe opt-in usage intended to be $levelText-level severity", explanation = """ This API has been flagged as opt-in with $levelText-level severity. Any declaration annotated with this marker is considered part of an unstable or otherwise non-standard API surface and its call sites should accept the opt-in aspect of it by using the `@OptIn` annotation, using the marker annotation -- effectively causing further propagation of the opt-in aspect -- or configuring the `$issueId` check's options for project-wide opt-in. To configure project-wide opt-in, specify the `opt-in` option value in `lint.xml` as a comma-delimited list of opted-in annotations: ``` <lint> <issue id="$issueId"> <option name="opt-in" value="com.foo.ExperimentalBarAnnotation" /> </issue> </lint> ``` """, category = Category.CORRECTNESS, priority = 4, severity = severity, implementation = IMPLEMENTATION, ) } val ISSUE_ERROR = issueForLevel(ENUM_ERROR, Severity.ERROR) val ISSUE_WARNING = issueForLevel(ENUM_WARNING, Severity.WARNING) val ISSUES = listOf( ISSUE_ERROR, ISSUE_WARNING, ) } } private fun UAnnotation.hasMatchingAttributeValueClass( attributeName: String, className: String ): Boolean { val attributeValue = findDeclaredAttributeValue(attributeName) if (attributeValue.getFullyQualifiedName() == className) { return true } if (attributeValue is UCallExpression) { return attributeValue.valueArguments.any { attrValue -> attrValue.getFullyQualifiedName() == className } } return false } /** * Returns the fully-qualified class name for a given attribute value, if any. */ private fun UExpression?.getFullyQualifiedName(): String? { val type = if (this is UClassLiteralExpression) this.type else this?.evaluate() return (type as? PsiClassType)?.canonicalText } private fun UElement?.getReferencedElement(): UElement? = when (this) { is UBinaryExpression -> leftOperand.tryResolve() // or referenced is UMethod -> this // or referenced is UClass -> uastSuperTypes.firstNotNullOfOrNull { PsiTypesUtil.getPsiClass(it.type) } // or referenced is USimpleNameReferenceExpression -> resolve().let { field -> field as? PsiField ?: field as? PsiMethod } // or referenced is UCallExpression -> resolve() ?: classReference?.resolve() // referenced is empty for constructor is UCallableReferenceExpression -> resolve() as? PsiMethod // or referenced is UAnnotation -> null is UEnumConstant -> resolveMethod() // or referenced is UArrayAccessExpression -> (receiver as? UReferenceExpression)?.resolve() // or referenced is UVariable -> this else -> null }.toUElement() /** * Tests each parent in the elements hierarchy including the element itself. Returns `true` for the * first element where [positivePredicate] matches or `false` for the first element where * [negativePredicate] returns matches. If neither predicate is matched, returns [defaultValue]. */ private inline fun UElement.anyParentMatches( positivePredicate: (element: UElement) -> Boolean, negativePredicate: (element: UElement) -> Boolean = { false }, defaultValue: Boolean = false ): Boolean { var element = this while (true) { if (positivePredicate(element)) return true if (negativePredicate(element)) return false element = element.uastParent ?: return defaultValue } } /** * Returns whether the package is annotated with the specified annotation. */ private fun PsiPackage.isAnnotatedWith( annotationFqName: String, ): Boolean = annotations.any { annotation -> annotation.hasQualifiedName(annotationFqName) } /** * Returns whether the package is annotated with any of the specified opt-in annotations where the * value of `markerClass` contains the specified annotation. */ private fun PsiPackage.isAnnotatedWithOptInOf( annotationFqName: String, optInFqNames: List<String>, ): Boolean = optInFqNames.any { optInFqName -> annotations.any { annotation -> annotation.hasQualifiedName(optInFqName) && ((annotation.toUElement() as? UAnnotation)?.hasMatchingAttributeValueClass( "markerClass", annotationFqName, ) ?: false) } } /** * Returns whether the element declaration is annotated with the specified annotation. */ private fun UElement.isDeclarationAnnotatedWith( annotationFqName: String, ) = (this as? UAnnotated)?.findAnnotation(annotationFqName) != null /** * Returns whether the element declaration is annotated with any of the specified opt-in * annotations where the value of `markerClass` contains the specified annotation. */ private fun UElement.isDeclarationAnnotatedWithOptInOf( annotationFqName: String, optInFqNames: List<String>, ) = (this as? UAnnotated)?.let { annotated -> optInFqNames.any { optInFqName -> annotated.findAnnotation(optInFqName)?.hasMatchingAttributeValueClass( "markerClass", annotationFqName, ) == true } } == true private fun PsiModifierListOwner.isAbstract(): Boolean = modifierList?.hasModifierProperty(PsiModifier.ABSTRACT) == true
apache-2.0
8991f46768084270a1be7750bce938fa
39.021421
100
0.594101
5.552792
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromCallWithConstructorCalleeActionFactory.kt
4
3593
// 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.quickfix.createFromUsage.createClass import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.caches.resolve.analyzeAndGetResult import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.utils.ifEmpty import java.util.* object CreateClassFromCallWithConstructorCalleeActionFactory : CreateClassFromUsageFactory<KtCallElement>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtCallElement? { val diagElement = diagnostic.psiElement val callElement = PsiTreeUtil.getParentOfType( diagElement, KtAnnotationEntry::class.java, KtSuperTypeCallEntry::class.java ) as? KtCallElement ?: return null val callee = callElement.calleeExpression as? KtConstructorCalleeExpression ?: return null val calleeRef = callee.constructorReferenceExpression ?: return null if (!calleeRef.isAncestor(diagElement)) return null return callElement } override fun getPossibleClassKinds(element: KtCallElement, diagnostic: Diagnostic): List<ClassKind> { return listOf(if (element is KtAnnotationEntry) ClassKind.ANNOTATION_CLASS else ClassKind.PLAIN_CLASS) } override fun extractFixData(element: KtCallElement, diagnostic: Diagnostic): ClassInfo? { val isAnnotation = element is KtAnnotationEntry val callee = element.calleeExpression as? KtConstructorCalleeExpression ?: return null val calleeRef = callee.constructorReferenceExpression ?: return null val typeRef = callee.typeReference ?: return null val userType = typeRef.typeElement as? KtUserType ?: return null val (context, module) = userType.analyzeAndGetResult() val qualifier = userType.qualifier?.referenceExpression val qualifierDescriptor = qualifier?.let { context[BindingContext.REFERENCE_TARGET, it] } val targetParents = getTargetParentsByQualifier(element, qualifier != null, qualifierDescriptor).ifEmpty { return null } val anyType = module.builtIns.nullableAnyType val valueArguments = element.valueArguments val defaultParamName = if (valueArguments.size == 1) "value" else null val parameterInfos = valueArguments.map { ParameterInfo( it.getArgumentExpression()?.let { TypeInfo(it, Variance.IN_VARIANCE) } ?: TypeInfo(anyType, Variance.IN_VARIANCE), it.getArgumentName()?.asName?.asString() ?: defaultParamName ) } val typeArgumentInfos = when { isAnnotation -> Collections.emptyList<TypeInfo>() else -> element.typeArguments.mapNotNull { it.typeReference?.let { TypeInfo(it, Variance.INVARIANT) } } } return ClassInfo( name = calleeRef.getReferencedName(), targetParents = targetParents, expectedTypeInfo = TypeInfo.Empty, parameterInfos = parameterInfos, open = !isAnnotation, typeArguments = typeArgumentInfos ) } }
apache-2.0
a6800ad0ef4acf45093f2f7f341f2c0f
46.276316
158
0.724186
5.519201
false
false
false
false
GunoH/intellij-community
java/idea-ui/src/com/intellij/ide/starters/local/generator/AssetsProcessor.kt
7
3737
// 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.ide.starters.local.generator import com.intellij.ide.starters.local.* import com.intellij.ide.starters.local.GeneratorContext import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.annotations.ApiStatus import java.io.IOException @ApiStatus.Experimental class AssetsProcessor { private val LOG = logger<AssetsProcessor>() internal fun generateSources(context: GeneratorContext, templateProperties: Map<String, Any>) { val outputDir = VfsUtil.createDirectoryIfMissing(context.outputDirectory.fileSystem, context.outputDirectory.path) ?: throw IllegalStateException("Unable to create directory ${context.outputDirectory.path}") generateSources(outputDir, context.assets, templateProperties + ("context" to context)) } fun generateSources( outputDirectory: String, assets: List<GeneratorAsset>, templateProperties: Map<String, Any> ): List<VirtualFile> { val outputDir = VfsUtil.createDirectoryIfMissing(LocalFileSystem.getInstance(), outputDirectory) ?: throw IllegalStateException("Unable to create directory ${outputDirectory}") return generateSources(outputDir, assets, templateProperties) } fun generateSources( outputDirectory: VirtualFile, assets: List<GeneratorAsset>, templateProperties: Map<String, Any> ): List<VirtualFile> { return assets.map { asset -> when (asset) { is GeneratorTemplateFile -> generateSources(outputDirectory, asset, templateProperties) is GeneratorResourceFile -> generateSources(outputDirectory, asset) is GeneratorEmptyDirectory -> generateSources(outputDirectory, asset) } } } private fun createFile(outputDirectory: VirtualFile, relativePath: String): VirtualFile { val subPath = if (relativePath.contains("/")) "/" + relativePath.substringBeforeLast("/") else "" val fileDirectory = if (subPath.isEmpty()) { outputDirectory } else { VfsUtil.createDirectoryIfMissing(outputDirectory, subPath) ?: throw IllegalStateException("Unable to create directory ${subPath} in ${outputDirectory.path}") } val fileName = relativePath.substringAfterLast("/") LOG.info("Creating file $fileName in ${fileDirectory.path}") return fileDirectory.findOrCreateChildData(this, fileName) } private fun generateSources(outputDirectory: VirtualFile, asset: GeneratorTemplateFile, templateProps: Map<String, Any>): VirtualFile { val sourceCode = try { asset.template.getText(templateProps) } catch (e: Exception) { throw TemplateProcessingException(e) } val file = createFile(outputDirectory, asset.targetFileName) VfsUtil.saveText(file, sourceCode) return file } private fun generateSources(outputDirectory: VirtualFile, asset: GeneratorResourceFile): VirtualFile { val file = createFile(outputDirectory, asset.targetFileName) asset.resource.openStream().use { file.setBinaryContent(it.readBytes()) } return file } private fun generateSources(outputDirectory: VirtualFile, asset: GeneratorEmptyDirectory): VirtualFile { LOG.info("Creating empty directory ${asset.targetFileName} in ${outputDirectory.path}") return VfsUtil.createDirectoryIfMissing(outputDirectory, asset.targetFileName) } private class TemplateProcessingException(t: Throwable) : IOException("Unable to process template", t) }
apache-2.0
79d12e13c11a0a41faaff0f61b73bfa7
38.765957
158
0.747123
5.016107
false
false
false
false
GunoH/intellij-community
plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseClasspathTest.kt
5
3525
// 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.eclipse import com.intellij.testFramework.junit5.TestApplication import com.intellij.testFramework.rules.TempDirectoryExtension import com.intellij.testFramework.rules.TestNameExtension import com.intellij.util.PathUtil import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension import java.nio.file.Path import kotlin.io.path.copyTo @TestApplication class EclipseClasspathTest { @JvmField @RegisterExtension val tempDirectory = TempDirectoryExtension() @JvmField @RegisterExtension val testName = TestNameExtension() @Test fun testAbsolutePaths() { doTest("parent/parent/test") } @Test fun testWorkspaceOnly() { doTest() } @Test fun testExportedLibs() { doTest() } @Test fun testPathVariables() { doTest() } @Test fun testJunit() { doTest() } @Test fun testSrcBinJRE() { doTest() } @Test fun testSrcBinJRESpecific() { doTest() } @Test fun testNativeLibs() { doTest() } @Test fun testAccessrulez() { doTest() } @Test fun testSrcBinJREProject() { doTest() } @Test fun testSourceFolderOutput() { doTest() } @Test fun testMultipleSourceFolders() { doTest() } @Test fun testEmptySrc() { doTest() } @Test fun testHttpJavadoc() { doTest() } @Test fun testHome() { doTest() } //public void testNoJava() throws Exception { // doTest(); @Test//} fun testNoSource() { doTest() } @Test fun testPlugin() { doTest() } @Test fun testRoot() { doTest() } @Test fun testUnknownCon() { doTest() } @Test fun testSourcesAfterAll() { doTest() } @Test fun testLinkedSrc() { doTest() } @Test fun testSrcRootsOrder() { doTest() } @Test fun testResolvedVariables() { doTest(setupPathVariables = true) } @Test fun testResolvedVars() { doTest("test", true, "linked") } @Test fun testResolvedVarsInOutput() { doTest("test", true, "linked") } @Test fun testResolvedVarsInLibImlCheck1() { doTest("test", true, "linked") } @Test fun testNoDotProject() { doTest(fileSuffixesToCheck = listOf("/.classpath", "/.project", ".iml"), updateExpectedDir = { val dotProject = eclipseTestDataRoot.resolve("round/workspaceOnly/test/.project") dotProject.copyTo(it.resolve("test/.project")) }) } private fun doTest( eclipseProjectDirPath: String = "test", setupPathVariables: Boolean = false, testDataParentDir: String = "round", updateExpectedDir: (Path) -> Unit = {}, fileSuffixesToCheck: List<String> = listOf("/.classpath", ".iml") ) { val testDataRoot = eclipseTestDataRoot val testRoot = testDataRoot.resolve(testDataParentDir).resolve(testName.methodName.removePrefix("test").decapitalize()) val commonRoot = testDataRoot.resolve("common").resolve("testModuleWithClasspathStorage") val modulePath = "$eclipseProjectDirPath/${PathUtil.getFileName(eclipseProjectDirPath)}" loadEditSaveAndCheck( testDataDirs = listOf(testRoot, commonRoot), tempDirectory = tempDirectory, setupPathVariables = setupPathVariables, imlFilePaths = listOf("test" to modulePath), edit = ::forceSave, updateExpectedDir = updateExpectedDir, fileSuffixesToCheck = fileSuffixesToCheck ) } }
apache-2.0
8d0e7c8c2167cbb86a3c3ef3f9df08c3
18.163043
123
0.671206
4.056387
false
true
false
false
poetix/centipede
src/main/java/com/codepoetics/centipede/Centipede.kt
1
747
package com.codepoetics.centipede import java.net.URI class Centipede(uriSetFetcher: UriSetFetcher, linkClassifier: LinkClassifier = SuffixAwareLinkClassifier()) { val pageVisitor = uriSetFetcher.classifyingWith(linkClassifier) operator fun invoke(uri: URI): SiteMap = mapOf(uri to pageVisitor(uri)).closure(pageVisitor) } fun main(args: Array<String>) { if (args.size == 0) { println("Usage: java -jar target/centipede-1.0-SNAPSHOT.jar [start uri]") return } val startUri = URI.create(args[0]) val pageFetcher = HttpPageFetcher() val uriSetExtractor = RegexUriSetExtractor() val centipede = Centipede(pageFetcher.extractingWith(uriSetExtractor)) centipede(startUri).prettyPrint(startUri) }
apache-2.0
1650e38f64943ef1d16e5eaed0068e58
34.571429
109
0.736278
3.557143
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/platforms/src/org/jetbrains/kotlin/idea/base/platforms/library/JSLibraryType.kt
5
3702
// 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.base.platforms.library import com.intellij.ide.JavaUiBundle import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.FileElement import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.libraries.DummyLibraryProperties import com.intellij.openapi.roots.libraries.LibraryType import com.intellij.openapi.roots.libraries.LibraryTypeService import com.intellij.openapi.roots.libraries.NewLibraryConfiguration import com.intellij.openapi.roots.libraries.ui.DescendentBasedRootFilter import com.intellij.openapi.roots.libraries.ui.LibraryEditorComponent import com.intellij.openapi.roots.libraries.ui.RootDetector import com.intellij.openapi.roots.ui.configuration.libraryEditor.DefaultLibraryRootsComponentDescriptor import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.base.platforms.KotlinBasePlatformsBundle import org.jetbrains.kotlin.idea.base.platforms.KotlinJavaScriptLibraryKind import javax.swing.JComponent class JSLibraryType : LibraryType<DummyLibraryProperties>(KotlinJavaScriptLibraryKind) { override fun createPropertiesEditor(editorComponent: LibraryEditorComponent<DummyLibraryProperties>) = null @Suppress("HardCodedStringLiteral") override fun getCreateActionName() = "Kotlin/JS" override fun createNewLibrary( parentComponent: JComponent, contextDirectory: VirtualFile?, project: Project ): NewLibraryConfiguration? = LibraryTypeService.getInstance().createLibraryFromFiles( RootsComponentDescriptor, parentComponent, contextDirectory, this, project ) override fun getIcon(properties: DummyLibraryProperties?) = KotlinIcons.JS companion object { @Suppress("DEPRECATION") fun getInstance() = Extensions.findExtension(EP_NAME, JSLibraryType::class.java) } object RootsComponentDescriptor : DefaultLibraryRootsComponentDescriptor() { override fun createAttachFilesChooserDescriptor(libraryName: String?): FileChooserDescriptor { val descriptor = FileChooserDescriptor(true, true, true, false, true, true).withFileFilter { FileElement.isArchive(it) || isAcceptedForJsLibrary(it.extension) } descriptor.title = if (StringUtil.isEmpty(libraryName)) ProjectBundle.message("library.attach.files.action") else ProjectBundle.message("library.attach.files.to.library.action", libraryName!!) descriptor.description = JavaUiBundle.message("library.java.attach.files.description") return descriptor } override fun getRootTypes() = arrayOf(OrderRootType.CLASSES, OrderRootType.SOURCES) override fun getRootDetectors(): List<RootDetector> = arrayListOf( DescendentBasedRootFilter(OrderRootType.CLASSES, false, KotlinBasePlatformsBundle.message("presentable.type.js.files")) { isAcceptedForJsLibrary(it.extension) }, DescendentBasedRootFilter.createFileTypeBasedFilter(OrderRootType.SOURCES, false, KotlinFileType.INSTANCE, "sources") ) } } private fun isAcceptedForJsLibrary(extension: String?) = extension == "js" || extension == "kjsm"
apache-2.0
cd9a28f0a257784092f6e2da33f77147
49.040541
133
0.773366
4.94259
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmarks/actions/MnemonicChooser.kt
1
6867
// 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.ide.bookmarks.actions import com.intellij.ide.bookmark.BookmarkType import com.intellij.ide.bookmarks.BookmarkBundle.message import com.intellij.ide.bookmarks.BookmarkManager import com.intellij.openapi.util.registry.Registry import com.intellij.ui.JBColor.namedColor import com.intellij.ui.components.panels.HorizontalLayout import com.intellij.ui.components.panels.RowGridLayout 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.ApiStatus import org.jetbrains.annotations.Nls import java.awt.* import java.awt.RenderingHints.* import java.awt.event.KeyEvent import java.awt.event.KeyListener import javax.swing.* private val ASSIGNED_FOREGROUND = namedColor("BookmarkMnemonicAssigned.foreground", 0x000000, 0xBBBBBB) private val ASSIGNED_BACKGROUND = namedColor("BookmarkMnemonicAssigned.background", 0xF7C777, 0x665632) private val ASSIGNED_BORDER = namedColor("BookmarkMnemonicAssigned.borderColor", ASSIGNED_BACKGROUND) private val CURRENT_FOREGROUND = namedColor("BookmarkMnemonicCurrent.foreground", 0xFFFFFF, 0xFEFEFE) private val CURRENT_BACKGROUND = namedColor("BookmarkMnemonicCurrent.background", 0x389FD6, 0x345F85) private val CURRENT_BORDER = namedColor("BookmarkMnemonicCurrent.borderColor", CURRENT_BACKGROUND) 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>) = Dimension(JBUI.scale(24), JBUI.scale(28)) } } @ApiStatus.ScheduledForRemoval @Deprecated("This class will be removed soon", ReplaceWith("com.intellij.ide.bookmark.actions.BookmarkTypeChooser"), DeprecationLevel.ERROR) internal class MnemonicChooser( private val manager: BookmarkManager, private val current: BookmarkType?, private val onChosen: (BookmarkType) -> Unit ) : BorderLayoutPanel(), KeyListener { init { isFocusCycleRoot = true focusTraversalPolicy = LayoutFocusTraversalPolicy() border = JBUI.Borders.empty(2, 6) addToLeft(JPanel(SHARED_LAYOUT).apply { border = JBUI.Borders.empty(5) BookmarkType.values() .filter { it.mnemonic.isDigit() } .forEach { add(createButton(it)) } }) addToRight(JPanel(SHARED_LAYOUT).apply { border = JBUI.Borders.empty(5) BookmarkType.values() .filter { it.mnemonic.isLetter() } .forEach { add(createButton(it)) } }) if (manager.hasBookmarksWithMnemonics()) { addToBottom(BorderLayoutPanel().apply { border = JBUI.Borders.empty(5, 6, 1, 6) addToTop(JSeparator()) addToBottom(JPanel(HorizontalLayout(12)).apply { border = JBUI.Borders.empty(5, 1) add(HorizontalLayout.LEFT, createLegend(ASSIGNED_BACKGROUND, message("mnemonic.chooser.legend.assigned.bookmark"))) if (current != null && current != BookmarkType.DEFAULT) { add(HorizontalLayout.LEFT, createLegend(CURRENT_BACKGROUND, message("mnemonic.chooser.legend.current.bookmark"))) } }) }) } } fun buttons() = UIUtil.uiTraverser(this).traverse().filter(JButton::class.java) private fun createButton(type: BookmarkType) = JButton(type.mnemonic.toString()).apply { setMnemonic(type.mnemonic) addActionListener { onChosen(type) } putClientProperty("ActionToolbar.smallVariant", true) when { type == current -> { putClientProperty("JButton.textColor", CURRENT_FOREGROUND) putClientProperty("JButton.backgroundColor", CURRENT_BACKGROUND) putClientProperty("JButton.borderColor", CURRENT_BORDER) } manager.findBookmarkForMnemonic(type.mnemonic) != null -> { putClientProperty("JButton.textColor", ASSIGNED_FOREGROUND) putClientProperty("JButton.backgroundColor", ASSIGNED_BACKGROUND) putClientProperty("JButton.borderColor", ASSIGNED_BORDER) } else -> { putClientProperty("JButton.textColor", UIManager.getColor("BookmarkMnemonicAvailable.foreground")) putClientProperty("JButton.backgroundColor", UIManager.getColor("BookmarkMnemonicAvailable.background")) putClientProperty("JButton.borderColor", UIManager.getColor("BookmarkMnemonicAvailable.borderColor")) } } inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "released") inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "pressed") cursor = SHARED_CURSOR }.also { it.addKeyListener(this) } 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 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() else -> { val type = BookmarkType.get(event.keyCode.toChar()) if (type != BookmarkType.DEFAULT) onChosen(type) } } } } }
apache-2.0
33a1ce2cdd8005f9c452d9a0c55811a6
42.738854
158
0.712975
4.099701
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/security/controller/BiometricUtils.kt
1
1971
package com.maubis.scarlet.base.security.controller import androidx.appcompat.app.AppCompatActivity import androidx.biometric.BiometricManager import androidx.biometric.BiometricPrompt import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import com.maubis.scarlet.base.R import com.maubis.scarlet.base.config.ApplicationBase.Companion.sBiometricManager import com.maubis.scarlet.base.settings.sheet.sSecurityBiometricEnabled fun deviceHasBiometricEnabled(): Boolean { return sBiometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS } fun isBiometricEnabled() = sSecurityBiometricEnabled && deviceHasBiometricEnabled() fun showBiometricPrompt( activity: AppCompatActivity, fragment: Fragment? = null, onSuccess: () -> Unit = {}, onFailure: () -> Unit = {}, title: Int = R.string.biometric_prompt_unlock_app, subtitle: Int = R.string.biometric_prompt_unlock_app_details) { val executor = ContextCompat.getMainExecutor(activity) val callback = object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { super.onAuthenticationError(errorCode, errString) onFailure() } override fun onAuthenticationFailed() { super.onAuthenticationFailed() onFailure() } override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { super.onAuthenticationSucceeded(result) onSuccess() } } val prompt = when { fragment !== null -> BiometricPrompt(fragment, executor, callback) else -> BiometricPrompt(activity, executor, callback) } val promptInfo = BiometricPrompt.PromptInfo.Builder() .setTitle(activity.getString(title)) .setDescription(activity.getString(subtitle)) .setDeviceCredentialAllowed(false) .setNegativeButtonText(activity.getString(R.string.delete_sheet_delete_trash_no)) .build() prompt.authenticate(promptInfo) }
gpl-3.0
535d06a9fe6196a75ce3b18ba8f17fab
34.854545
90
0.771689
4.637647
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/CheckComponentsUsageSearchAction.kt
4
5919
// 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.actions.internal import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileVisitor import com.intellij.psi.PsiManager import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.search.usagesSearch.ExpressionsOfTypeProcessor import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtFile import javax.swing.SwingUtilities class CheckComponentsUsageSearchAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val project = CommonDataKeys.PROJECT.getData(e.dataContext) ?: return val selectedKotlinFiles = selectedKotlinFiles(e).toList() ProgressManager.getInstance().runProcessWithProgressSynchronously( { runReadAction { process(selectedKotlinFiles, project) } }, KotlinBundle.message("checking.data.classes"), true, project ) } private fun process(files: Collection<KtFile>, project: Project) { val dataClasses = files.asSequence() .flatMap { it.declarations.asSequence() } .filterIsInstance<KtClass>() .filter { it.isData() } .toList() val progressIndicator = ProgressManager.getInstance().progressIndicator for ((i, dataClass) in dataClasses.withIndex()) { progressIndicator?.text = KotlinBundle.message("checking.data.class.0.of.1", i + 1, dataClasses.size) @NlsSafe val fqName = dataClass.fqName?.asString() ?: "" progressIndicator?.text2 = fqName val parameter = dataClass.primaryConstructor?.valueParameters?.firstOrNull() if (parameter != null) { try { var smartRefsCount = 0 var goldRefsCount = 0 ProgressManager.getInstance().runProcess( { ExpressionsOfTypeProcessor.mode = ExpressionsOfTypeProcessor.Mode.ALWAYS_SMART smartRefsCount = ReferencesSearch.search(parameter).findAll().size ExpressionsOfTypeProcessor.mode = ExpressionsOfTypeProcessor.Mode.ALWAYS_PLAIN goldRefsCount = ReferencesSearch.search(parameter).findAll().size }, EmptyProgressIndicator() ) if (smartRefsCount != goldRefsCount) { SwingUtilities.invokeLater { Messages.showInfoMessage( project, KotlinBundle.message( "difference.found.for.data.class.0.found.1.2", dataClass.fqName?.asString().toString(), smartRefsCount, goldRefsCount ), KotlinBundle.message("title.error") ) } return } } finally { ExpressionsOfTypeProcessor.mode = ExpressionsOfTypeProcessor.Mode.PLAIN_WHEN_NEEDED } } progressIndicator?.fraction = (i + 1) / dataClasses.size.toDouble() } SwingUtilities.invokeLater { Messages.showInfoMessage( project, KotlinBundle.message("analyzed.0.classes.no.difference.found", dataClasses.size), KotlinBundle.message("title.success") ) } } override fun update(e: AnActionEvent) { if (!isApplicationInternalMode()) { e.presentation.isVisible = false e.presentation.isEnabled = false } else { e.presentation.isVisible = true e.presentation.isEnabled = true } } private fun selectedKotlinFiles(e: AnActionEvent): Sequence<KtFile> { val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return sequenceOf() val project = CommonDataKeys.PROJECT.getData(e.dataContext) ?: return sequenceOf() return allKotlinFiles(virtualFiles, project) } private fun allKotlinFiles(filesOrDirs: Array<VirtualFile>, project: Project): Sequence<KtFile> { val manager = PsiManager.getInstance(project) return allFiles(filesOrDirs) .asSequence() .mapNotNull { manager.findFile(it) as? KtFile } } private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> { val result = ArrayList<VirtualFile>() for (file in filesOrDirs) { VfsUtilCore.visitChildrenRecursively(file, object : VirtualFileVisitor<Unit>() { override fun visitFile(file: VirtualFile): Boolean { result.add(file) return true } }) } return result } }
apache-2.0
bb2c038ba059d5c57dea43de043b68ac
41.278571
158
0.605677
5.61575
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/find/actions/ShowTargetUsagesActionHandler.kt
1
4244
// 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.find.actions import com.intellij.find.actions.SearchOptionsService.SearchVariant import com.intellij.find.usages.api.SearchTarget import com.intellij.find.usages.api.UsageHandler import com.intellij.find.usages.api.UsageOptions.createOptions import com.intellij.find.usages.impl.AllSearchOptions import com.intellij.find.usages.impl.buildUsageViewQuery import com.intellij.find.usages.impl.hasTextSearchStrings import com.intellij.ide.nls.NlsMessages import com.intellij.lang.LangBundle import com.intellij.lang.Language import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.usages.UsageSearchPresentation import com.intellij.usages.UsageSearcher // data class for `copy` method internal data class ShowTargetUsagesActionHandler<O>( private val project: Project, private val target: SearchTarget, private val usageHandler: UsageHandler<O>, private val allOptions: AllSearchOptions<O> ) : ShowUsagesActionHandler { override fun isValid(): Boolean = true override fun getPresentation(): UsageSearchPresentation = object: UsageSearchPresentation { override fun getSearchTargetString(): String = usageHandler.getSearchString(allOptions) override fun getOptionsString(): String { val optionsList = ArrayList<String>() if (allOptions.options.isUsages) optionsList.add(LangBundle.message("target.usages.option")) if (allOptions.textSearch == true) optionsList.add(LangBundle.message("target.text.occurrences.option")) return StringUtil.capitalize(NlsMessages.formatOrList(optionsList)) } } override fun createUsageSearcher(): UsageSearcher { val query = buildUsageViewQuery(project, target, usageHandler, allOptions) return UsageSearcher { query.forEach(it) } } override fun showDialog(): ShowUsagesActionHandler? { val dialog = UsageOptionsDialog(project, target.displayString, usageHandler, allOptions, target.showScopeChooser(), false) if (!dialog.showAndGet()) { // cancelled return null } val dialogResult = dialog.result() setSearchOptions(SearchVariant.SHOW_USAGES, target, dialogResult) return copy(allOptions = dialogResult) } override fun withScope(searchScope: SearchScope): ShowUsagesActionHandler { return copy(allOptions = allOptions.copy(options = createOptions(allOptions.options.isUsages, searchScope))) } override fun findUsages(): Unit = findUsages(project, target, usageHandler, allOptions) override fun getSelectedScope(): SearchScope = allOptions.options.searchScope override fun getMaximalScope(): SearchScope = target.maximalSearchScope ?: GlobalSearchScope.allScope(project) override fun getTargetLanguage(): Language? = null override fun getTargetClass(): Class<*> = target::class.java companion object { @JvmStatic fun showUsages(project: Project, searchScope: SearchScope, target: SearchTarget, parameters: ShowUsagesParameters) { ShowUsagesAction.showElementUsages(parameters, createActionHandler(project, searchScope, target, target.usageHandler)) } private fun <O> createActionHandler(project: Project, searchScope: SearchScope, target: SearchTarget, usageHandler: UsageHandler<O>): ShowTargetUsagesActionHandler<O> { val persistedOptions: PersistedSearchOptions = getSearchOptions(SearchVariant.SHOW_USAGES, target) return ShowTargetUsagesActionHandler( project, target = target, usageHandler = usageHandler, allOptions = AllSearchOptions( options = createOptions(persistedOptions.usages, searchScope), textSearch = if (target.hasTextSearchStrings()) persistedOptions.textSearch else null, customOptions = usageHandler.getCustomOptions(UsageHandler.UsageAction.SHOW_USAGES) ) ) } } }
apache-2.0
7625f209da74e5dc7490246f641b5f6a
41.868687
158
0.748115
4.674009
false
false
false
false
ThiagoGarciaAlves/intellij-community
java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/LibraryJarsDiffDialog.kt
3
2767
/* * 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. */ package com.intellij.openapi.roots.ui.configuration.projectRoot import com.intellij.diff.DiffManager import com.intellij.diff.DiffRequestFactory import com.intellij.diff.DiffRequestPanel import com.intellij.diff.requests.ContentDiffRequest import com.intellij.ide.diff.DirDiffSettings import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.components.JBLabel import com.intellij.xml.util.XmlStringUtil import org.jetbrains.jps.model.library.JpsMavenRepositoryLibraryDescriptor import java.awt.event.ActionEvent import javax.swing.Action /** * @author nik */ class LibraryJarsDiffDialog(libraryFile: VirtualFile, downloadedFile: VirtualFile, private val mavenCoordinates: JpsMavenRepositoryLibraryDescriptor, private val libraryName: String, project: Project) : DialogWrapper(project) { companion object { val CHANGE_COORDINATES_CODE = 2; } private val panel: DiffRequestPanel init { title = "Replace Library" setOKButtonText("Replace") val request: ContentDiffRequest = DiffRequestFactory.getInstance().createFromFiles(project, libraryFile, downloadedFile) panel = DiffManager.getInstance().createRequestPanel(project, disposable, window) panel.putContextHints(DirDiffSettings.KEY, DirDiffSettings().apply { enableChoosers = false enableOperations = false }) panel.setRequest(request) init() } override fun createNorthPanel() = JBLabel(XmlStringUtil.wrapInHtml("${mavenCoordinates.mavenId} JARs differ from '$libraryName' library JARs.")) override fun createCenterPanel() = panel.component override fun getPreferredFocusedComponent() = panel.preferredFocusedComponent override fun createActions(): Array<Action> { return arrayOf(okAction, ChangeCoordinatesAction(), cancelAction) } private inner class ChangeCoordinatesAction : DialogWrapperAction("Change Coordinates...") { override fun doAction(e: ActionEvent?) { close(CHANGE_COORDINATES_CODE) } } }
apache-2.0
e1730eed2b5cecbead6b72fffed4005c
36.405405
146
0.747741
4.77069
false
false
false
false
vicpinm/KPresenterAdapter
sample/src/main/java/com/vicpin/sample/view/fragment/AutoBindingFragment.kt
1
2557
package com.vicpin.sample.view.fragment import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.vicpin.kpresenteradapter.PresenterAdapter import com.vicpin.kpresenteradapter.extensions.inflate import com.vicpin.sample.R import com.vicpin.sample.di.Injector import com.vicpin.sample.extensions.finishIdlingResource import com.vicpin.sample.extensions.showToast import com.vicpin.sample.extensions.startIdlingResource import com.vicpin.sample.model.* import kotlinx.android.synthetic.main.fragment_main.* /** * Created by Victor on 25/06/2016. */ class AutoBindingFragment : Fragment() { private var currentPage: Int = 0 private lateinit var adapter: PresenterAdapter<Town> private lateinit var repository: IRepository<Town> override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = container?.inflate(R.layout.fragment_main) override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) this.repository = Injector.get().getTownRepository() initView() } private fun initView(){ setupAdapter() appendListeners() setupRecyclerView() } private fun setupAdapter() { val data = repository.getItemsPage(0) adapter = TownPresenterAdapter(R.layout.adapter_town) adapter.setData(data) adapter.enableLoadMore { onLoadMore() } } private fun appendListeners() { adapter.apply { itemClickListener = { item, view -> showToast("Country clicked: " + item.name) } itemLongClickListener = { item, view -> showToast("Country long pressed: " + item.name) } customListener = this@AutoBindingFragment } } private fun setupRecyclerView() { recycler.layoutManager = LinearLayoutManager(activity) recycler.adapter = adapter } /** * Pagination listener. Simulates a 1500ms load delay. */ private fun onLoadMore() { startIdlingResource() Handler().postDelayed({ currentPage++ val newData = repository.getItemsPage(currentPage) if (newData.isNotEmpty()) { adapter.addData(newData) } else { adapter.disableLoadMore() } finishIdlingResource() }, 1500) } }
apache-2.0
3ddbc80c95f14d44ee5e24d9ab97fa4b
29.440476
152
0.687133
4.898467
false
false
false
false
bhubie/Expander
app/src/main/kotlin/com/wanderfar/expander/AppSettings/AppSettingsImpl.kt
1
3332
/* * Expander: Text Expansion Application * Copyright (C) 2016 Brett Huber * * 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 com.wanderfar.expander.AppSettings import android.accessibilityservice.AccessibilityServiceInfo import android.content.Context import android.os.Build import android.preference.PreferenceManager import android.provider.Settings import android.view.accessibility.AccessibilityEvent import android.view.accessibility.AccessibilityManager import com.wanderfar.expander.Models.MacroConstants class AppSettingsImpl (var context: Context) : AppSettings{ var prefs = PreferenceManager.getDefaultSharedPreferences(context) var accessibilityManager = context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager override fun isDynamicValuesEnabled(): Boolean { return prefs.getBoolean("isDynamicValuesEnabled", false) } override fun isFloatingUIEnabled(): Boolean { return prefs.getBoolean("IsFloatingUIEnabled", true) } override fun isSystemAlertPermissionGranted(): Boolean { var result = false if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ){ result = isFloatingUIEnabled() } else { result = Settings.canDrawOverlays(context) } return result } override fun getOpacityValue(): Int { return prefs.getInt("Opacity_Value", 75) } override fun getFloatingUIColor(): Int { return prefs.getInt("floatingUIColor", -24832) } override fun isAccessibilityServiceEnabled(): Boolean { val runningServices: List<AccessibilityServiceInfo> = accessibilityManager .getEnabledAccessibilityServiceList(AccessibilityEvent.TYPES_ALL_MASK) return runningServices.any { "com.wanderfar.expander/.MacroAccessibilityService.MacroAccessibilityService" == it.id } } override fun setMacroListSortByPreference(sortBy: Int) { val editor = prefs.edit() editor.putInt("SortByMethod", sortBy) editor.apply() } override fun getMacroListSortByMethod(): Int { return prefs.getInt("SortByMethod", MacroConstants.SORT_BY_NAME) } override fun isRedoButtonEnabled(): Boolean { return prefs.getBoolean("ShowRedoButton", true) } override fun isUndoButtonEnabled(): Boolean { return prefs.getBoolean("ShowUndoButton", true) } override fun isApplicationFirstStart(): Boolean { return prefs.getBoolean("FirstStart", true) } override fun setApplicationFirstStart(firstStart: Boolean) { val editor = prefs.edit() editor.putBoolean("FirstStart", firstStart) editor.apply() } }
gpl-3.0
35ea930ce85b3cd4eba64eafa6b4b0bb
33.010204
110
0.717887
4.815029
false
false
false
false
neverwoodsS/StudyWithKotlin
src/linearlist/Sequence.kt
1
1486
package linearlist /** * Created by zhangll on 2017/1/16. */ class Sequence { var array: Array<String> = arrayOf("false", "false", "false", "false", "false") fun addElement(element: String, position: Int) { val temp: Array<String> = Array(array.size + 1, { "temp" }) // 插入位置前的参数不变, 插入位置的参数取插入数值,插入位置后的参数取前一位对应参数 (0 .. array.size).forEach { temp[it] = when(it) { in 0 until position -> array[it] position -> element in (position + 1) .. array.size -> array[it - 1] else -> throw Exception("wrong") } } array = temp } fun deleteElement(position: Int) { if (position >= array.size) { println("out of index $position, current size is ${array.size}") return } val temp: Array<String> = Array(array.size - 1, { "temp" }) // 删除位置前的参数不变,删除位置开始取后一位参数 (0 .. array.size - 2).forEach { temp[it] = when(it) { in 0 until position -> array[it] in position .. array.size - 2 -> array[it + 1] else -> throw Exception("wrong") } } array = temp } fun log() { (0 until array.size).map { array[it] }.forEach { print(it + ", ") } println("\n") } }
mit
42138aa75df4b845fc3f8eb78ea5f19e
26.77551
83
0.491912
3.665768
false
false
false
false
googlecodelabs/while-in-use-location
base/src/main/java/com/example/android/whileinuselocation/ForegroundOnlyLocationService.kt
1
11227
/* * Copyright 2019 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 * * 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. */ package com.example.android.whileinuselocation import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.content.res.Configuration import android.location.Location import android.os.Binder import android.os.Build import android.os.IBinder import android.os.Looper import android.util.Log import androidx.core.app.NotificationCompat import androidx.localbroadcastmanager.content.LocalBroadcastManager import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationCallback import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationResult import com.google.android.gms.location.LocationServices import java.util.concurrent.TimeUnit /** * Service tracks location when requested and updates Activity via binding. If Activity is * stopped/unbinds and tracking is enabled, the service promotes itself to a foreground service to * insure location updates aren't interrupted. * * For apps running in the background on O+ devices, location is computed much less than previous * versions. Please reference documentation for details. */ class ForegroundOnlyLocationService : Service() { /* * Checks whether the bound activity has really gone away (foreground service with notification * created) or simply orientation change (no-op). */ private var configurationChange = false private var serviceRunningInForeground = false private val localBinder = LocalBinder() private lateinit var notificationManager: NotificationManager // TODO: Step 1.1, Review variables (no changes). // FusedLocationProviderClient - Main class for receiving location updates. private lateinit var fusedLocationProviderClient: FusedLocationProviderClient // LocationRequest - Requirements for the location updates, i.e., how often you should receive // updates, the priority, etc. private lateinit var locationRequest: LocationRequest // LocationCallback - Called when FusedLocationProviderClient has a new Location. private lateinit var locationCallback: LocationCallback // Used only for local storage of the last known location. Usually, this would be saved to your // database, but because this is a simplified sample without a full database, we only need the // last location to create a Notification if the user navigates away from the app. private var currentLocation: Location? = null override fun onCreate() { Log.d(TAG, "onCreate()") notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // TODO: Step 1.2, Review the FusedLocationProviderClient. fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this) // TODO: Step 1.3, Create a LocationRequest. // TODO: Step 1.4, Initialize the LocationCallback. } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { Log.d(TAG, "onStartCommand()") val cancelLocationTrackingFromNotification = intent.getBooleanExtra(EXTRA_CANCEL_LOCATION_TRACKING_FROM_NOTIFICATION, false) if (cancelLocationTrackingFromNotification) { unsubscribeToLocationUpdates() stopSelf() } // Tells the system not to recreate the service after it's been killed. return START_NOT_STICKY } override fun onBind(intent: Intent): IBinder { Log.d(TAG, "onBind()") // MainActivity (client) comes into foreground and binds to service, so the service can // become a background services. stopForeground(true) serviceRunningInForeground = false configurationChange = false return localBinder } override fun onRebind(intent: Intent) { Log.d(TAG, "onRebind()") // MainActivity (client) returns to the foreground and rebinds to service, so the service // can become a background services. stopForeground(true) serviceRunningInForeground = false configurationChange = false super.onRebind(intent) } override fun onUnbind(intent: Intent): Boolean { Log.d(TAG, "onUnbind()") // MainActivity (client) leaves foreground, so service needs to become a foreground service // to maintain the 'while-in-use' label. // NOTE: If this method is called due to a configuration change in MainActivity, // we do nothing. if (!configurationChange && SharedPreferenceUtil.getLocationTrackingPref(this)) { Log.d(TAG, "Start foreground service") val notification = generateNotification(currentLocation) startForeground(NOTIFICATION_ID, notification) serviceRunningInForeground = true } // Ensures onRebind() is called if MainActivity (client) rebinds. return true } override fun onDestroy() { Log.d(TAG, "onDestroy()") } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) configurationChange = true } fun subscribeToLocationUpdates() { Log.d(TAG, "subscribeToLocationUpdates()") SharedPreferenceUtil.saveLocationTrackingPref(this, true) // Binding to this service doesn't actually trigger onStartCommand(). That is needed to // ensure this Service can be promoted to a foreground service, i.e., the service needs to // be officially started (which we do here). startService(Intent(applicationContext, ForegroundOnlyLocationService::class.java)) try { // TODO: Step 1.5, Subscribe to location changes. } catch (unlikely: SecurityException) { SharedPreferenceUtil.saveLocationTrackingPref(this, false) Log.e(TAG, "Lost location permissions. Couldn't remove updates. $unlikely") } } fun unsubscribeToLocationUpdates() { Log.d(TAG, "unsubscribeToLocationUpdates()") try { // TODO: Step 1.6, Unsubscribe to location changes. SharedPreferenceUtil.saveLocationTrackingPref(this, false) } catch (unlikely: SecurityException) { SharedPreferenceUtil.saveLocationTrackingPref(this, true) Log.e(TAG, "Lost location permissions. Couldn't remove updates. $unlikely") } } /* * Generates a BIG_TEXT_STYLE Notification that represent latest location. */ private fun generateNotification(location: Location?): Notification { Log.d(TAG, "generateNotification()") // Main steps for building a BIG_TEXT_STYLE notification: // 0. Get data // 1. Create Notification Channel for O+ // 2. Build the BIG_TEXT_STYLE // 3. Set up Intent / Pending Intent for notification // 4. Build and issue the notification // 0. Get data val mainNotificationText = location?.toText() ?: getString(R.string.no_location_text) val titleText = getString(R.string.app_name) // 1. Create Notification Channel for O+ and beyond devices (26+). if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notificationChannel = NotificationChannel( NOTIFICATION_CHANNEL_ID, titleText, NotificationManager.IMPORTANCE_DEFAULT) // Adds NotificationChannel to system. Attempting to create an // existing notification channel with its original values performs // no operation, so it's safe to perform the below sequence. notificationManager.createNotificationChannel(notificationChannel) } // 2. Build the BIG_TEXT_STYLE. val bigTextStyle = NotificationCompat.BigTextStyle() .bigText(mainNotificationText) .setBigContentTitle(titleText) // 3. Set up main Intent/Pending Intents for notification. val launchActivityIntent = Intent(this, MainActivity::class.java) val cancelIntent = Intent(this, ForegroundOnlyLocationService::class.java) cancelIntent.putExtra(EXTRA_CANCEL_LOCATION_TRACKING_FROM_NOTIFICATION, true) val servicePendingIntent = PendingIntent.getService( this, 0, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT) val activityPendingIntent = PendingIntent.getActivity( this, 0, launchActivityIntent, 0) // 4. Build and issue the notification. // Notification Channel Id is ignored for Android pre O (26). val notificationCompatBuilder = NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL_ID) return notificationCompatBuilder .setStyle(bigTextStyle) .setContentTitle(titleText) .setContentText(mainNotificationText) .setSmallIcon(R.mipmap.ic_launcher) .setDefaults(NotificationCompat.DEFAULT_ALL) .setOngoing(true) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .addAction( R.drawable.ic_launch, getString(R.string.launch_activity), activityPendingIntent ) .addAction( R.drawable.ic_cancel, getString(R.string.stop_location_updates_button_text), servicePendingIntent ) .build() } /** * Class used for the client Binder. Since this service runs in the same process as its * clients, we don't need to deal with IPC. */ inner class LocalBinder : Binder() { internal val service: ForegroundOnlyLocationService get() = this@ForegroundOnlyLocationService } companion object { private const val TAG = "ForegroundOnlyLocationService" private const val PACKAGE_NAME = "com.example.android.whileinuselocation" internal const val ACTION_FOREGROUND_ONLY_LOCATION_BROADCAST = "$PACKAGE_NAME.action.FOREGROUND_ONLY_LOCATION_BROADCAST" internal const val EXTRA_LOCATION = "$PACKAGE_NAME.extra.LOCATION" private const val EXTRA_CANCEL_LOCATION_TRACKING_FROM_NOTIFICATION = "$PACKAGE_NAME.extra.CANCEL_LOCATION_TRACKING_FROM_NOTIFICATION" private const val NOTIFICATION_ID = 12345678 private const val NOTIFICATION_CHANNEL_ID = "while_in_use_channel_01" } }
apache-2.0
463da65086537effb95ba000d9cc019a
38.392982
99
0.693685
5.066336
false
false
false
false
aosp-mirror/platform_frameworks_support
core/ktx/src/main/java/androidx/core/util/LruCache.kt
1
2205
/* * Copyright (C) 2018 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.core.util import android.util.LruCache /** * Creates an [LruCache] with the given parameters. * * @param maxSize for caches that do not specify [sizeOf], this is * the maximum number of entries in the cache. For all other caches, * this is the maximum sum of the sizes of the entries in this cache. * @param sizeOf function that returns the size of the entry for key and value in * user-defined units. The default implementation returns 1. * @param create a create called after a cache miss to compute a value for the corresponding key. * Returns the computed value or null if no value can be computed. The default implementation * returns null. * @param onEntryRemoved a function called for entries that have been evicted or removed. * * @see LruCache.sizeOf * @see LruCache.create * @see LruCache.entryRemoved */ inline fun <K : Any, V : Any> lruCache( maxSize: Int, crossinline sizeOf: (key: K, value: V) -> Int = { _, _ -> 1 }, @Suppress("USELESS_CAST") // https://youtrack.jetbrains.com/issue/KT-21946 crossinline create: (key: K) -> V? = { null as V? }, crossinline onEntryRemoved: (evicted: Boolean, key: K, oldValue: V, newValue: V?) -> Unit = { _, _, _, _ -> } ): LruCache<K, V> { return object : LruCache<K, V>(maxSize) { override fun sizeOf(key: K, value: V) = sizeOf(key, value) override fun create(key: K) = create(key) override fun entryRemoved(evicted: Boolean, key: K, oldValue: V, newValue: V?) { onEntryRemoved(evicted, key, oldValue, newValue) } } }
apache-2.0
b3a76c6f102340a70fd345255c66c184
40.603774
97
0.691156
3.909574
false
false
false
false
intrigus/jtransc
jtransc-core/src/com/jtransc/ast/feature/method/UndeterministicParameterEvaluationFeature.kt
1
7108
package com.jtransc.ast.feature.method import com.jtransc.ast.* import com.jtransc.error.invalidOp import com.jtransc.error.noImpl class UndeterministicParameterEvaluationFeature : AstMethodFeature() { override fun add(method: AstMethod, body: AstBody, settings: AstBuildSettings, types: AstTypes): AstBody { return body.copy(stm = MyProcess().process(body.stm)) } class MyProcess { var lastLocalIndex: Int = 0 fun process(stm: AstStm): AstStm = stm.processStm() fun AstStm.processStm() = this.stms.processStm().stms fun List<AstStm>.processStm(): List<AstStm> { val stms = this val out = arrayListOf<AstStm>() for (stm in stms) { when (stm) { is AstStm.NOP -> out += stm is AstStm.LINE -> out += stm is AstStm.RETURN_VOID -> out += stm is AstStm.STM_LABEL -> out += stm is AstStm.GOTO -> out += stm is AstStm.RETURN -> out += AstStm.RETURN(stm.retval.processExpr(out)) is AstStm.STMS -> out += stm.stmsUnboxed.processStm().stms is AstStm.STM_EXPR -> { val expr = stm.expr.processExpr(out); val dummy = (expr is AstExpr.LITERAL && expr.value == null) if (!dummy) out += AstStm.STM_EXPR(expr) } is AstStm.IF -> out += AstStm.IF(stm.cond.processExpr(out), stm.strue.value.processStm()) is AstStm.IF_ELSE -> out += AstStm.IF_ELSE(stm.cond.processExpr(out), stm.strue.value.processStm(), stm.sfalse.value.processStm()) is AstStm.IF_GOTO -> out += AstStm.IF_GOTO(stm.label, stm.cond.processExpr(out)) is AstStm.SWITCH -> out += AstStm.SWITCH(stm.subject.processExpr(out), stm.default.value.processStm(), stm.cases.map { it.first to it.second.value.processStm() }) is AstStm.SWITCH_GOTO -> out += AstStm.SWITCH_GOTO(stm.subject.processExpr(out), stm.default, stm.cases) is AstStm.MONITOR_ENTER -> out += AstStm.MONITOR_ENTER(stm.expr.processExpr(out)) is AstStm.MONITOR_EXIT -> out += AstStm.MONITOR_EXIT(stm.expr.processExpr(out)) is AstStm.THROW -> out += AstStm.THROW(stm.exception.processExpr(out)) is AstStm.WHILE -> out += AstStm.WHILE(stm.cond.processExpr(out), stm.iter.value) is AstStm.SET_LOCAL -> out += AstStm.SET_LOCAL(stm.local, stm.expr.processExpr(out), true) is AstStm.SET_ARRAY -> { // Like this to keep order val value = stm.expr.processExpr(out) val index = stm.index.processExpr(out) val array = stm.array.processExpr(out) out += AstStm.SET_ARRAY(array, index, value) } is AstStm.SET_ARRAY_LITERALS -> { out += AstStm.SET_ARRAY_LITERALS(stm.array.processExpr(out), stm.startIndex, stm.values.map { it.processExpr(out).box }) } is AstStm.SET_FIELD_INSTANCE -> { val expr = stm.expr.processExpr(out) val l = stm.left.processExpr(out) out += AstStm.SET_FIELD_INSTANCE(stm.field, l, expr) } is AstStm.SET_FIELD_STATIC -> { val expr = stm.expr.processExpr(out) out += AstStm.SET_FIELD_STATIC(stm.field, expr) } else -> { //out += stm noImpl("UndeterministicParameterEvaluationFeature: $stm") } } } return out } fun AstExpr.Box.processExpr(stms: ArrayList<AstStm>): AstExpr = this.value.processExpr(stms) private fun alloc(type: AstType): AstLocal { val id = lastLocalIndex++ return AstLocal(9000 + id, "ltt$id", type) } inline private fun ArrayList<AstStm>.buildLocalExpr(callback: () -> AstExpr): AstExpr.LOCAL { val stms = this val expr = callback() val local = alloc(expr.type) stms += local.setTo(expr) return local.expr } fun AstExpr.processExpr(stms: ArrayList<AstStm>): AstExpr { val expr = this return when (expr) { is AstExpr.LITERAL -> expr is AstExpr.LOCAL -> { //stms.buildLocalExpr { expr } expr } is AstExpr.PARAM -> expr is AstExpr.THIS -> expr is AstExpr.NEW -> expr is AstExpr.INTARRAY_LITERAL -> expr is AstExpr.NEW_ARRAY -> { val length = expr.counts.map { it.processExpr(stms) } stms.buildLocalExpr { AstExpr.NEW_ARRAY(expr.arrayType, length) } } is AstExpr.FIELD_STATIC_ACCESS -> expr is AstExpr.ARRAY_ACCESS -> { val array = expr.array.processExpr(stms) val index = expr.index.processExpr(stms) //stms.buildLocalExpr { AstExpr.ARRAY_ACCESS(array, index) } AstExpr.ARRAY_ACCESS(array, index) } is AstExpr.INSTANCE_OF -> { val l = expr.expr.processExpr(stms) //stms.buildLocalExpr { AstExpr.INSTANCE_OF(l, expr.checkType) } AstExpr.INSTANCE_OF(l, expr.checkType) } is AstExpr.ARRAY_LENGTH -> { AstExpr.ARRAY_LENGTH(expr.array.processExpr(stms)) } is AstExpr.FIELD_INSTANCE_ACCESS -> { val l = expr.expr.processExpr(stms) //stms.buildLocalExpr { AstExpr.FIELD_INSTANCE_ACCESS(expr.field, l) } AstExpr.FIELD_INSTANCE_ACCESS(expr.field, l) } is AstExpr.BINOP -> { val l = expr.left.processExpr(stms) val r = expr.right.processExpr(stms) //stms.buildLocalExpr { AstExpr.BINOP(expr.type, l, expr.op, r) } AstExpr.BINOP(expr.type, l, expr.op, r) } is AstExpr.UNOP -> { //val r = expr.right.processExpr(stms) //stms.buildLocalExpr { AstExpr.UNOP(expr.op, r) } AstExpr.UNOP(expr.op, expr.right.processExpr(stms)) } is AstExpr.CAST -> { expr.subject.processExpr(stms).castTo(expr.type) //expr.processExpr(stms) /* val subjectWithoutCasts = expr.subject.value.withoutCasts() if (subjectWithoutCasts is AstExpr.LITERAL || subjectWithoutCasts is AstExpr.LocalExpr) { expr } else { val subject = expr.subject.processExpr(stms) stms.buildLocalExpr { subject.castTo(expr.type) } } */ } is AstExpr.CHECK_CAST -> { expr.subject.processExpr(stms).checkedCastTo(expr.type) } is AstExpr.CALL_BASE -> { val method = expr.method val isSpecial = expr.isSpecial val args = expr.args.map { it.processExpr(stms) } val newExpr = when (expr) { is AstExpr.CALL_BASE_OBJECT -> { val obj = expr.obj.processExpr(stms) if (expr is AstExpr.CALL_SUPER) { AstExpr.CALL_SUPER(obj, expr.target, method, args, isSpecial = isSpecial) } else { AstExpr.CALL_INSTANCE(obj, method, args, isSpecial = isSpecial) } } is AstExpr.CALL_STATIC -> { AstExpr.CALL_STATIC(method, args, isSpecial = isSpecial) } else -> invalidOp } if (method.type.retVoid) { stms += AstStm.STM_EXPR(newExpr) AstExpr.LITERAL(null, dummy = true) } else { stms.buildLocalExpr { newExpr } } } is AstExpr.INVOKE_DYNAMIC_METHOD -> { val args = expr.startArgs.map { it.processExpr(stms) } AstExpr.INVOKE_DYNAMIC_METHOD(expr.methodInInterfaceRef, expr.methodToConvertRef, expr.extraArgCount, args) } is AstExpr.NEW_WITH_CONSTRUCTOR -> { val args = expr.args.map { it.processExpr(stms) } stms.buildLocalExpr { AstExpr.NEW_WITH_CONSTRUCTOR(expr.constructor, args) } } else -> noImpl("UndeterministicParameterEvaluationFeature: $this") //else -> expr } } } }
apache-2.0
9bc2150f280d6c85e0133f61bf349d33
36.415789
167
0.652504
3.140963
false
false
false
false
sophiataskova/WeBingo
app/src/main/java/com/example/sophiataskova/webingo/BingoUtils.kt
1
3783
package com.example.sophiataskova.webingo import com.example.sophiataskova.webingo.FullscreenActivity.Companion.bingoCard import com.example.sophiataskova.webingo.FullscreenActivity.Companion.selectedBingoNumbers import java.security.SecureRandom val BINGO = arrayOf("B", "I", "N", "G", "O") val RANGES = arrayOf((1..15), (16..30), (31..45), (46..60), (61..75)) fun getAllBingoEntriesInOrder() : List<String> { val result = ArrayList<String>() for (index in 0..BINGO.size - 1) { result.addAll(getBingoEntriesForLetter(BINGO[index], RANGES[index])) } return result } fun getBingoEntriesForLetter(s: String, r: IntRange) : List<String> { val result = ArrayList<String>() r.mapTo(result) { s + it } return result } fun generateRandomBingoCard() : Set<Int> { var resultSet = LinkedHashSet<Int>() for (range in RANGES) { resultSet.addAll(chooseKUniqueElementsFromRange(5, range)) } return resultSet } /** * Row, col, or diagonal // //0 1 2 3 4 //5 6 7 8 9 //10 11 12 13 14 //15 16 17 18 19 //20 21 22 23 24 */ fun checkForBingo() : Boolean { (0..4).filter { selectedBingoNumbers.contains(bingoCard.elementAt(it)) && selectedBingoNumbers.contains(bingoCard.elementAt(it + 5)) && selectedBingoNumbers.contains(bingoCard.elementAt(it + 10)) && selectedBingoNumbers.contains(bingoCard.elementAt(it + 15)) && selectedBingoNumbers.contains(bingoCard.elementAt(it + 20)) } .forEach { return true } if (selectedBingoNumbers.contains(bingoCard.elementAt(0)) && selectedBingoNumbers.contains(bingoCard.elementAt(6)) && selectedBingoNumbers.contains(bingoCard.elementAt(12)) && selectedBingoNumbers.contains(bingoCard.elementAt(18)) && selectedBingoNumbers.contains(bingoCard.elementAt(24))) { return true } if (selectedBingoNumbers.contains(bingoCard.elementAt(4)) && selectedBingoNumbers.contains(bingoCard.elementAt(8)) && selectedBingoNumbers.contains(bingoCard.elementAt(12)) && selectedBingoNumbers.contains(bingoCard.elementAt(16)) && selectedBingoNumbers.contains(bingoCard.elementAt(20))) { return true } return (0..20 step 5).any { (selectedBingoNumbers.contains(bingoCard.elementAt(it))) && (selectedBingoNumbers.contains(bingoCard.elementAt(it + 1))) && (selectedBingoNumbers.contains(bingoCard.elementAt(it + 2))) && (selectedBingoNumbers.contains(bingoCard.elementAt(it + 3))) && (selectedBingoNumbers.contains(bingoCard.elementAt(it + 4))) } } /** * Theoretically, this could run infinitely */ fun chooseKUniqueElementsFromRange(k:Int, r: IntRange) : Set<Int> { val result = LinkedHashSet<Int>() val random = SecureRandom() while (result.size.compareTo(k) < 0) { result.add((r.elementAt(random.nextInt(r.last - r.first)))) } return result } fun getBingoNumToShow() : Int { val divideBy: Long = 4000 return (((System.currentTimeMillis()/divideBy * 3) + (System.currentTimeMillis()-7)) % 75).toInt() } fun numberToBingoNumber(number: Int): String { var bingoNumber = "" if (number in 1..15) { bingoNumber = "B" + number } else if (number in 16..30) { bingoNumber = "I" + number } else if (number in 31..45) { bingoNumber = "N" + number } else if (number in 46..60) { bingoNumber = "G" + number } else if (number in 60..75) { bingoNumber = "O" + number } else { // todo eliminate 0 BingoApplication.instance?.toast("Number was " + number) } return bingoNumber }
mit
dc65e1a62aa72b0bb80dd404d02aad2f
33.081081
102
0.638911
3.578997
false
false
false
false
denofevil/AureliaStorm
src/main/kotlin/com/github/denofevil/aurelia/FrameworkHandler.kt
1
2100
package com.github.denofevil.aurelia import com.intellij.codeInsight.completion.CompletionUtil import com.intellij.lang.javascript.index.FrameworkIndexingHandler import com.intellij.lang.javascript.psi.JSQualifiedNameImpl import com.intellij.lang.javascript.psi.JSReferenceExpression import com.intellij.lang.javascript.psi.ecmal4.JSClass import com.intellij.lang.javascript.psi.resolve.JSTypeInfo import com.intellij.lang.javascript.psi.types.JSContext import com.intellij.lang.javascript.psi.types.JSNamedTypeFactory import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.resolve.FileContextUtil import com.intellij.psi.util.PsiTreeUtil /** * @author Dennis.Ushakov */ class FrameworkHandler : FrameworkIndexingHandler() { override fun addContextType(info: JSTypeInfo, context: PsiElement) { val controller = findController(context) ?: return val namespace = JSQualifiedNameImpl.buildProvidedNamespace(controller) info.addType(JSNamedTypeFactory.createNamespace(namespace, JSContext.INSTANCE, null, true), false) } override fun addContextNames(context: PsiElement, names: MutableList<String>) { val controller = findController(context) ?: return names.add(controller.qualifiedName!!) } private fun findController(context: PsiElement): JSClass? { if (context !is JSReferenceExpression || context.qualifier != null) { return null } if (!Aurelia.present(context.getProject())) return null val original = CompletionUtil.getOriginalOrSelf<PsiElement>(context) val hostFile = FileContextUtil.getContextFile(if (original !== context) original else context.getContainingFile().originalFile) ?: return null val directory = hostFile.originalFile.parent ?: return null val name = FileUtil.getNameWithoutExtension(hostFile.name) val controllerFile = directory.findFile("$name.ts") ?: directory.findFile("$name.js") return PsiTreeUtil.findChildOfType(controllerFile, JSClass::class.java) } }
mit
3688d7a102ca37eb0f523d1189e5ee85
43.680851
150
0.762857
4.421053
false
false
false
false
Litote/kmongo
kmongo-benchmark/common/src/main/kotlin/org/litote/kmongo/FriendWithBuddies.kt
1
1187
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo import kotlinx.serialization.Contextual import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.bson.codecs.pojo.annotations.BsonId import org.bson.types.ObjectId import org.litote.kmongo.id.MongoId /** * */ @Serializable data class FriendWithBuddies( @Contextual @SerialName("_id") @BsonId val id: ObjectId? = null, val name: String? = null, val address: String? = null, val coordinate: Coordinate? = null, val gender: Gender? = null, val buddies: List<FriendWithBuddies> = emptyList() )
apache-2.0
a432714ae124c57a9888e4f8c9412936
28.7
75
0.73631
3.996633
false
false
false
false
AdamMc331/CashCaretaker
app/src/androidTest/java/com/androidessence/cashcaretaker/TestUtils.kt
1
3374
package com.androidessence.cashcaretaker import android.view.View import android.widget.Checkable import androidx.recyclerview.widget.RecyclerView import androidx.test.espresso.Espresso.onView import androidx.test.espresso.UiController import androidx.test.espresso.ViewAction import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.contrib.RecyclerViewActions import androidx.test.espresso.matcher.ViewMatchers.isCompletelyDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import org.hamcrest.Description import org.hamcrest.Matcher import org.hamcrest.Matchers.allOf import org.hamcrest.Matchers.isA /** * Utility methods for testing. */ class TestUtils { companion object { fun <T : RecyclerView.ViewHolder> matchTextInRecyclerView( text: String, recyclerViewId: Int, textViewId: Int, position: Int ) { onView(allOf(withId(recyclerViewId), isCompletelyDisplayed())).perform( RecyclerViewActions.actionOnItemAtPosition<T>(position, scrollTo()) ) onView( allOf( withRecyclerView(recyclerViewId).atPositionOnView(position, textViewId), isCompletelyDisplayed() ) ).check(matches(withText(text))) } fun <T : RecyclerView.ViewHolder> clickItemInRecyclerView( recyclerViewId: Int, targetViewId: Int, position: Int ) { onView(allOf(withId(recyclerViewId), isCompletelyDisplayed())).perform( RecyclerViewActions.actionOnItemAtPosition<T>(position, scrollTo()) ) onView( allOf( withRecyclerView(recyclerViewId).atPositionOnView(position, targetViewId), isCompletelyDisplayed() ) ).perform(click()) } private fun scrollTo(): ViewAction = ScrollToAction() private fun withRecyclerView(recyclerViewId: Int): RecyclerViewMatcher = RecyclerViewMatcher(recyclerViewId) fun setChecked(checked: Boolean): ViewAction { return object : ViewAction { override fun getConstraints(): Matcher<View> { return object : Matcher<View> { override fun matches(item: Any): Boolean = isA(Checkable::class.java).matches(item) override fun describeMismatch( item: Any, mismatchDescription: Description ) { } override fun describeTo(description: Description) {} override fun _dont_implement_Matcher___instead_extend_BaseMatcher_() { } } } override fun getDescription(): String? = null override fun perform(uiController: UiController, view: View) { val checkableView = view as Checkable checkableView.isChecked = checked } } } } }
mit
ad4e97aa18f45336851430b4242222ea
34.893617
94
0.597214
5.83737
false
true
false
false
mniami/android.kotlin.benchmark
data_structure/src/main/java/guideme/volunteers/eventbus/EventBus.kt
2
818
package guideme.volunteers.eventbus import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.Subject import java.io.Serializable import java.util.* class EventBusContainer { val map : MutableMap<Serializable, EventBus<*>> = HashMap() fun <T> get(key: Serializable): EventBus<T>? { return if (map.containsKey(key)) { @Suppress("UNCHECKED_CAST") map[key] as EventBus<T> } else { val eventBus = EventBus<T>() map[key] = eventBus eventBus } } } class EventBus<T> @JvmOverloads constructor(private val subject: Subject<T> = PublishSubject.create<T>()) { fun <E : T> post(event: E) { subject.onNext(event) } fun observe(): Observable<T> = subject }
apache-2.0
b702a70663e7979d0d1c3842f27d4166
25.419355
107
0.632029
4.110553
false
false
false
false
gradle/gradle
.teamcity/src/main/kotlin/model/PerformanceTestSpec.kt
3
3796
/* * Copyright 2020 the original author or 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 model import common.Os import java.util.Locale interface PerformanceTestBuildSpec { val type: PerformanceTestType val os: Os val withoutDependencies: Boolean fun asConfigurationId(model: CIBuildModel, bucket: String): String fun channel(): String } interface PerformanceTestProjectSpec { val type: PerformanceTestType val failsStage: Boolean fun asConfigurationId(model: CIBuildModel): String fun asName(): String fun channel(): String } data class PerformanceTestPartialTrigger( val triggerName: String, val triggerId: String, val dependencies: List<PerformanceTestCoverage> ) data class PerformanceTestCoverage( private val uuid: Int, override val type: PerformanceTestType, override val os: Os, val numberOfBuckets: Int = 40, private val oldUuid: String? = null, override val withoutDependencies: Boolean = false, override val failsStage: Boolean = true ) : PerformanceTestBuildSpec, PerformanceTestProjectSpec { override fun asConfigurationId(model: CIBuildModel, bucket: String) = "${asConfigurationId(model)}$bucket" override fun asConfigurationId(model: CIBuildModel) = "${model.projectId}_${oldUuid ?: "PerformanceTest$uuid"}" override fun asName(): String = "${type.displayName} - ${os.asName()}${if (withoutDependencies) " without dependencies" else ""}" override fun channel() = "${type.channel}${if (os == Os.LINUX) "" else "-${os.name.lowercase(Locale.US)}"}-%teamcity.build.branch%" } data class FlameGraphGeneration( private val uuid: Int, private val name: String, private val scenarios: List<PerformanceScenario> ) : PerformanceTestProjectSpec { override fun asConfigurationId(model: CIBuildModel) = "${model.projectId}_PerformanceTest$uuid" override fun asName(): String = "Flamegraphs for $name" override fun channel(): String = "adhoc-%teamcity.build.branch%" override val type: PerformanceTestType get() = PerformanceTestType.adHoc override val failsStage: Boolean get() = false val buildSpecs: List<FlameGraphGenerationBuildSpec> get() = scenarios.flatMap { scenario -> Os.values().flatMap { os -> if (os == Os.WINDOWS) { listOf("jprofiler") } else { listOf("async-profiler", "async-profiler-heap") }.map { FlameGraphGenerationBuildSpec(scenario, os, it) } } } inner class FlameGraphGenerationBuildSpec( val performanceScenario: PerformanceScenario, override val os: Os, val profiler: String ) : PerformanceTestBuildSpec { override val type: PerformanceTestType = PerformanceTestType.adHoc override val withoutDependencies: Boolean = true override fun asConfigurationId(model: CIBuildModel, bucket: String): String = "${[email protected](model)}$bucket" override fun channel(): String = [email protected]() } }
apache-2.0
af2b55e0c743698c38dc72a1e70a3ec4
29.126984
114
0.675184
4.62363
false
true
false
false
daemontus/Distributed-CTL-Model-Checker
src/test/kotlin/com/github/sybila/checker/ReachModel.kt
3
5232
package com.github.sybila.checker import com.github.sybila.checker.solver.BitSetSolver import com.github.sybila.huctl.* import java.util.* /** * Representation of n-dimensional hypercube of size s where all transitions lead * from one lower corner (0,0..) to upper corner (s-1,s-1,...), while each transition "adds" one color. * So border of upper corner can "go through" with almost all colors, while * lower corner transitions have only one color (zero) * Total number of colors is (size - 1) * dimensions + 1 * Color zero goes through the whole model, last color does not have any transitions. * * Note: All transition are increasing. * * WARNING: This implementation is hilariously inefficient. Really just use for testing. * * See: <a href="https://photos.google.com/share/AF1QipMGw9XEJiI9rMSw-u-JuOowwhKEuKuLWkWw-hAL8ZE84-QkBqkkX4d8fj2GEmkFpw?key=WnB0Vm94RDkwSGk0eU16enl4ZXAtUFNvLXM0SUN3">image</a> */ class ReachModel( private val dimensions: Int, private val dimensionSize: Int ) : Model<BitSet>, Solver<BitSet> by BitSetSolver((dimensionSize - 1) * dimensions + 2) { /** * Use these propositions in your model queries, nothing else is supported! */ enum class Prop : () -> Formula.Atom.Float { UPPER_CORNER, LOWER_CORNER, CENTER, BORDER, UPPER_HALF; override fun invoke(): Formula.Atom.Float { return when (this) { UPPER_CORNER -> "upper".asVariable() gt 0.0.asConstant() LOWER_CORNER -> "lower".asVariable() gt 0.0.asConstant() CENTER -> "center".asVariable() gt 0.0.asConstant() BORDER -> "border".asVariable() gt 0.0.asConstant() UPPER_HALF -> "upper_half".asVariable() gt 0.0.asConstant() } } } init { assert(dimensionSize > 0) assert(dimensions > 0) val size = Math.pow(dimensionSize.toDouble(), dimensions.toDouble()) if (size.toLong() > size.toInt()) throw IllegalArgumentException("Model too big: $size") } override val stateCount = pow(dimensionSize, dimensions) /** * Helper function to extract a coordinate from node id */ fun extractCoordinate(node: Int, i: Int): Int = (node / pow(dimensionSize, i)) % dimensionSize /** * Encode node coordinates into an index */ fun toStateIndex(coordinates: List<Int>): Int = coordinates.mapIndexed { i, e -> e * pow(dimensionSize, i) }.sum() private val colorCache = HashMap<Int, BitSet>() /** * Returns the set of colors that can reach upper corner from given state. Very useful ;) */ fun stateColors(state: Int): BitSet { return colorCache.computeIfAbsent(state) { val set = BitSet() set.set(0) for (dim in 0 until dimensions) { for (p in 1..extractCoordinate(state, dim)) { set.set(p + (dimensionSize - 1) * dim) } } set } } private fun step(from: Int, successors: Boolean, timeFlow: Boolean): Iterator<Transition<BitSet>> { val dim = (0 until dimensions).asSequence() val step = if (successors == timeFlow) { dim .filter { extractCoordinate(from, it) + 1 < dimensionSize } .map { it to from + pow(dimensionSize, it) } } else { dim .filter { extractCoordinate(from, it) - 1 > -1 } .map { it to from - pow(dimensionSize, it) } } val transitions = step.map { val state = it.second val dimName = it.first.toString() Transition(state, if (timeFlow) dimName.increaseProp() else dimName.decreaseProp(), stateColors(state)) } val loop = Transition(from, DirectionFormula.Atom.Loop, stateColors(from).not()) return (transitions + sequenceOf(loop)).iterator() } override fun Int.successors(timeFlow: Boolean): Iterator<Transition<BitSet>> = step(this, true, timeFlow) override fun Int.predecessors(timeFlow: Boolean): Iterator<Transition<BitSet>> = step(this, false, timeFlow) override fun Formula.Atom.Float.eval(): StateMap<BitSet> { return when (this) { Prop.CENTER() -> toStateIndex((1..dimensions).map { dimensionSize / 2 }).asStateMap(tt) Prop.UPPER_CORNER() -> toStateIndex((1..dimensions).map { dimensionSize - 1 }).asStateMap(tt) Prop.LOWER_CORNER() -> toStateIndex((1..dimensions).map { 0 }).asStateMap(tt) Prop.BORDER() -> (0 until stateCount).asSequence().filter { state -> (0 until dimensions).any { val c = extractCoordinate(state, it); c == 0 || c == dimensionSize - 1 } }.associateBy({it}, { tt }).asStateMap() Prop.UPPER_HALF() -> (0 until stateCount).asSequence().filter { state -> (0 until dimensions).all { extractCoordinate(state, it) >= dimensionSize/2 } }.associateBy({it}, { tt }).asStateMap() else -> throw IllegalStateException("Unexpected atom $this") } } override fun Formula.Atom.Transition.eval(): StateMap<BitSet> { throw UnsupportedOperationException("not implemented") } }
gpl-3.0
efb2feeebd61e2f03e94a85dcee8649c
40.204724
175
0.62156
3.993893
false
false
false
false
tonyofrancis/Fetch
fetch2fileserver/src/main/java/com/tonyodev/fetch2fileserver/provider/FetchFileResourceProvider.kt
1
14433
package com.tonyodev.fetch2fileserver.provider import android.os.Handler import com.tonyodev.fetch2core.* import com.tonyodev.fetch2core.server.FileRequest import com.tonyodev.fetch2core.server.FileResponse import com.tonyodev.fetch2core.server.FileResponse.CREATOR.CLOSE_CONNECTION import com.tonyodev.fetch2core.server.FileResponse.CREATOR.OPEN_CONNECTION import com.tonyodev.fetch2core.server.FileResourceTransporter import com.tonyodev.fetch2core.server.FetchFileResourceTransporter import com.tonyodev.fetch2fileserver.FileResolver import java.net.HttpURLConnection import java.net.Socket import java.util.* class FetchFileResourceProvider(private val client: Socket, private val fileResourceProviderDelegate: FileResourceProviderDelegate, private val logger: FetchLogger, private val ioHandler: Handler, private val progressReportingInMillis: Long, private val persistentTimeoutInMillis: Long, private val fileResolver: FileResolver) : FileResourceProvider { override val id = UUID.randomUUID().toString() private val lock = Any() private val transporter: FileResourceTransporter = FetchFileResourceTransporter(client) @Volatile private var interrupted: Boolean = false private var inputResourceWrapper: InputResourceWrapper? = null private var clientRequest: FileRequest? = null private var persistConnection = true private val persistentRunnable = Runnable { interrupted = true } private val sessionId = UUID.randomUUID().toString() private var fileResource: FileResource? = null override fun execute() { Thread { try { while (persistConnection && !interrupted) { ioHandler.postDelayed(persistentRunnable, persistentTimeoutInMillis) clientRequest = getFileResourceClientRequest() ioHandler.removeCallbacks(persistentRunnable) val request = clientRequest if (request != null && !interrupted) { persistConnection = request.persistConnection if (!interrupted && fileResourceProviderDelegate.acceptAuthorization(sessionId, request.authorization, request)) { logger.d("FetchFileServerProvider - ClientRequestAccepted - ${request.toJsonString}") logger.d("FetchFileServerProvider - Client Connected - $client") fileResourceProviderDelegate.onClientConnected(sessionId, request) if (request.extras.isNotEmpty()) { fileResourceProviderDelegate.onClientDidProvideExtras(sessionId, request.extras, request) } when (request.type) { FileRequest.TYPE_PING -> { if (!interrupted) { sendPingResponse() } } FileRequest.TYPE_CATALOG -> { if (!interrupted) { val catalog = fileResourceProviderDelegate.getCatalog(request.page, request.size) val data = catalog.toByteArray(Charsets.UTF_8) if (!interrupted) { val contentLength = (if (request.rangeEnd == -1L) data.size.toLong() else request.rangeEnd) - request.rangeStart sendCatalogResponse(contentLength, getMd5String(data)) transporter.sendRawBytes(data, request.rangeStart.toInt(), contentLength.toInt()) } } } FileRequest.TYPE_FILE -> { val fileResource = fileResourceProviderDelegate.getFileResource(request.fileResourceId) if (!interrupted) { if (fileResource != null) { this.fileResource = fileResource inputResourceWrapper = fileResourceProviderDelegate.getFileInputResourceWrapper(sessionId, request, fileResource, request.rangeStart) if (inputResourceWrapper == null) { if (fileResource.id == FileRequest.CATALOG_ID) { val catalog = fileResource.extras.getString("data", "{}").toByteArray(Charsets.UTF_8) fileResource.length = if (request.rangeEnd == -1L) catalog.size.toLong() else request.rangeEnd fileResource.md5 = getMd5String(catalog) inputResourceWrapper = fileResolver.getCatalogInputWrapper(catalog, request, fileResource) } else { inputResourceWrapper = fileResolver.getInputWrapper(fileResource) inputResourceWrapper?.setReadOffset(request.rangeStart) } } if (!interrupted) { var reportingStopTime: Long val byteArray = ByteArray(FileResourceTransporter.BUFFER_SIZE) val contentLength = (if (request.rangeEnd == -1L) fileResource.length else request.rangeEnd) - request.rangeStart var remainderBytes = contentLength sendFileResourceResponse(contentLength, fileResource.md5) var reportingStartTime = System.nanoTime() var read = inputResourceWrapper?.read(byteArray) ?: -1 var streamBytes: Int fileResourceProviderDelegate.onStarted(sessionId, request, fileResource) while (remainderBytes > 0L && read != -1 && !interrupted) { streamBytes = if (read <= remainderBytes) { read } else { read = -1 remainderBytes.toInt() } transporter.sendRawBytes(byteArray, 0, streamBytes) if (read != -1) { remainderBytes -= streamBytes reportingStopTime = System.nanoTime() val hasReportingTimeElapsed = hasIntervalTimeElapsed(reportingStartTime, reportingStopTime, progressReportingInMillis) if (hasReportingTimeElapsed && !interrupted) { val progress = calculateProgress(contentLength - remainderBytes, contentLength) fileResourceProviderDelegate.onProgress(sessionId, request, fileResource, progress) reportingStartTime = System.nanoTime() } read = inputResourceWrapper?.read(byteArray) ?: -1 } } if (remainderBytes == 0L && !interrupted) { fileResourceProviderDelegate.onProgress(sessionId, request, fileResource, 100) fileResourceProviderDelegate.onComplete(sessionId, request, fileResource) } } cleanFileStreams() } else { sendInvalidResponse(HttpURLConnection.HTTP_NO_CONTENT) } } } FileRequest.TYPE_INVALID -> { } else -> { if (!interrupted) { fileResourceProviderDelegate.onCustomRequest(sessionId, request, transporter, interruptMonitor) } } } logger.d("FetchFileServerProvider - Client Disconnected - $client") fileResourceProviderDelegate.onClientDisconnected(sessionId, request) } else if (!interrupted) { logger.d("FetchFileServerProvider - ClientRequestRejected - ${request.toJsonString}") sendInvalidResponse(HttpURLConnection.HTTP_FORBIDDEN) } } else if (!interrupted) { sendInvalidResponse(HttpURLConnection.HTTP_BAD_REQUEST) } clientRequest = null } } catch (e: Exception) { logger.e("FetchFileServerProvider - ${e.message}") try { sendInvalidResponse(HttpURLConnection.HTTP_INTERNAL_ERROR) } catch (e: Exception) { logger.e("FetchFileServerProvider - ${e.message}") } val fileResource = this.fileResource val request = this.clientRequest if (fileResource != null && request != null) { fileResourceProviderDelegate.onError(sessionId, request, fileResource, e) } } finally { if (interrupted) { try { sendInvalidResponse(HttpURLConnection.HTTP_INTERNAL_ERROR) } catch (e: Exception) { logger.e("FetchFileServerProvider - ${e.message}") } } ioHandler.removeCallbacks(persistentRunnable) transporter.close() cleanFileStreams() this.fileResource = null this.persistConnection = false this.clientRequest = null fileResourceProviderDelegate.onFinished(id) } }.start() } private fun cleanFileStreams() { try { inputResourceWrapper?.close() } catch (e: Exception) { logger.e("FetchFileServerProvider - ${e.message}") } inputResourceWrapper = null } private val interruptMonitor = object : InterruptMonitor { override val isInterrupted: Boolean get() { return interrupted } } private fun getFileResourceClientRequest(): FileRequest? { while (!interrupted) { val request = transporter.receiveFileRequest() if (request != null) { return request } } return null } private fun sendPingResponse() { val response = FileResponse(status = HttpURLConnection.HTTP_OK, type = FileRequest.TYPE_PING, connection = OPEN_CONNECTION, date = Date().time, contentLength = 0, sessionId = sessionId) transporter.sendFileResponse(response) } private fun sendInvalidResponse(status: Int) { val response = FileResponse(status = status, type = FileRequest.TYPE_INVALID, connection = CLOSE_CONNECTION, date = Date().time, contentLength = 0, sessionId = sessionId) transporter.sendFileResponse(response) interrupted = true } private fun sendCatalogResponse(contentLength: Long, md5: String) { val response = FileResponse(status = HttpURLConnection.HTTP_OK, type = FileRequest.TYPE_CATALOG, connection = OPEN_CONNECTION, date = Date().time, contentLength = contentLength, md5 = md5, sessionId = sessionId) transporter.sendFileResponse(response) } private fun sendFileResourceResponse(contentLength: Long, md5: String) { val response = FileResponse(status = HttpURLConnection.HTTP_PARTIAL, type = FileRequest.TYPE_FILE, connection = OPEN_CONNECTION, date = Date().time, contentLength = contentLength, md5 = md5, sessionId = sessionId) transporter.sendFileResponse(response) } override fun interrupt() { synchronized(lock) { interrupted = true } } override fun isServingFileResource(fileResource: FileResource): Boolean { return this.fileResource?.equals(fileResource) ?: false } }
apache-2.0
ffd1a8d6534af2fba4a704bc72cb96c6
53.882129
177
0.473706
6.94228
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/average/Game20AverageStatistic.kt
1
1018
package ca.josephroque.bowlingcompanion.statistics.impl.average import android.os.Parcel import android.os.Parcelable import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator /** * Copyright (C) 2018 Joseph Roque * * Average score in the 20th game of a series. */ class Game20AverageStatistic(total: Int = 0, divisor: Int = 0) : PerGameAverageStatistic(total, divisor) { // MARK: Overrides override val gameNumber = 20 override val titleId = Id override val id = Id.toLong() // MARK: Parcelable companion object { /** Creator, required by [Parcelable]. */ @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::Game20AverageStatistic) /** Unique ID for the statistic. */ const val Id = R.string.statistic_average_20 } /** * Construct this statistic from a [Parcel]. */ private constructor(p: Parcel): this(total = p.readInt(), divisor = p.readInt()) }
mit
268c7dfa97eb3fdd15d8347eba130f38
27.277778
106
0.687623
4.295359
false
false
false
false
duftler/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/CancelStageHandler.kt
1
4560
/* * 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.spinnaker.orca.CancellableStage import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.TaskResolver import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.StageNavigator import com.netflix.spinnaker.orca.q.CancelStage import com.netflix.spinnaker.orca.q.RescheduleExecution import com.netflix.spinnaker.orca.q.RunTask import com.netflix.spinnaker.q.Queue import org.springframework.beans.factory.annotation.Qualifier import org.springframework.stereotype.Component import java.util.concurrent.Executor @Component class CancelStageHandler( override val queue: Queue, override val repository: ExecutionRepository, override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory, override val stageNavigator: StageNavigator, @Qualifier("cancellableStageExecutor") private val executor: Executor, private val taskResolver: TaskResolver ) : OrcaMessageHandler<CancelStage>, StageBuilderAware, AuthenticationAware { override val messageType = CancelStage::class.java override fun handle(message: CancelStage) { message.withStage { stage -> /** * When an execution ends with status !SUCCEEDED, still-running stages * remain in the RUNNING state until their running tasks are dequeued * to RunTaskHandler. For tasks leveraging getDynamicBackoffPeriod(), * stages may incorrectly report as RUNNING for a considerable length * of time, unless we short-circuit their backoff time. * * For !SUCCEEDED executions, CompleteExecutionHandler enqueues CancelStage * messages for all top-level stages. For stages still RUNNING, we requeue * RunTask messages for any RUNNING tasks, for immediate execution. This * ensures prompt stage cancellation and correct handling of onFailure or * cancel conditions. This is safe as RunTaskHandler validates execution * status before processing work. RunTask messages are idempotent for * cancelled executions, though additional work is generally avoided due * to queue deduplication. * */ if (stage.status == RUNNING) { stage.tasks .filter { it.status == RUNNING } .forEach { queue.reschedule( RunTask( stage.execution.type, stage.execution.id, stage.execution.application, stage.id, it.id, it.type ) ) } } if (stage.status.isHalt) { stage.builder().let { builder -> if (builder is CancellableStage) { // for the time being we execute this off-thread as some cancel // routines may run long enough to cause message acknowledgment to // time out. executor.execute { stage.withAuth { builder.cancel(stage) } // Special case for PipelineStage to ensure prompt cancellation of // child pipelines and deployment strategies regardless of task backoff if (stage.type.equals("pipeline", true) && stage.context.containsKey("executionId")) { val childId = stage.context["executionId"] as? String if (childId != null) { val child = repository.retrieve(PIPELINE, childId) queue.push(RescheduleExecution(child)) } } } } } } } } @Suppress("UNCHECKED_CAST") private val com.netflix.spinnaker.orca.pipeline.model.Task.type get() = taskResolver.getTaskClass(implementingClass) }
apache-2.0
87c264c26f875fcae3412bd1ea9567a7
40.081081
100
0.686623
4.919094
false
false
false
false
crunchersaspire/worshipsongs
app/src/main/java/org/worshipsongs/activity/FavouriteSongsActivity.kt
1
4437
package org.worshipsongs.activity import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.preference.PreferenceManager import android.widget.FrameLayout import org.worshipsongs.CommonConstants import org.worshipsongs.R import org.worshipsongs.fragment.FavouriteSongsFragment import org.worshipsongs.fragment.HomeTabFragment import org.worshipsongs.fragment.SongContentPortraitViewFragment import org.worshipsongs.listener.SongContentViewListener import org.worshipsongs.service.FavouriteService import org.worshipsongs.service.PresentationScreenService import org.worshipsongs.service.SongService import java.util.* /** * Author: Seenivasan, Madasamy * version 1.0.0 */ class FavouriteSongsActivity : AbstractAppCompactActivity(), SongContentViewListener { private var songContentFrameLayout: FrameLayout? = null private var presentationScreenService: PresentationScreenService? = null private var preferences: SharedPreferences? = null private var favouriteService: FavouriteService? = null private var songService: SongService? = null private val favouriteName: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.home_layout) presentationScreenService = PresentationScreenService(this@FavouriteSongsActivity) preferences = PreferenceManager.getDefaultSharedPreferences(this@FavouriteSongsActivity) favouriteService = FavouriteService() songService = SongService(this@FavouriteSongsActivity) setActionBar() setContentViewFragment() setTabsFragment() displayHelpActivity() } private fun setActionBar() { setCustomActionBar() val actionBar = supportActionBar actionBar!!.setDisplayShowHomeEnabled(true) actionBar.setDisplayShowTitleEnabled(true) actionBar.setDisplayHomeAsUpEnabled(true) actionBar.title = getFavouriteName() } private fun setContentViewFragment() { songContentFrameLayout = findViewById<FrameLayout>(R.id.song_content_fragment) } private fun setTabsFragment() { val fragmentManager = supportFragmentManager val existingServiceSongsFragment = fragmentManager.findFragmentByTag(FavouriteSongsFragment::class.java.simpleName) as FavouriteSongsFragment? if (existingServiceSongsFragment == null) { val bundle = Bundle() bundle.putString(CommonConstants.SERVICE_NAME_KEY, getFavouriteName()) val serviceSongsFragment = FavouriteSongsFragment.newInstance(bundle) serviceSongsFragment.setSongContentViewListener(this) val transaction = fragmentManager.beginTransaction() transaction.replace(R.id.tabs_fragment, serviceSongsFragment, HomeTabFragment::class.java.simpleName) transaction.addToBackStack(null) transaction.commit() } } private fun getFavouriteName(): String { return favouriteName ?: intent.getStringExtra(CommonConstants.SERVICE_NAME_KEY) } private fun displayHelpActivity() { if (!preferences!!.getBoolean(CommonConstants.DISPLAY_FAVOURITE_HELP_ACTIVITY, false)) { startActivity(Intent(this, FavouriteSongsHelpActivity::class.java)) } } override fun displayContent(title: String, titleList: List<String>, position: Int) { if (songContentFrameLayout != null) { val titles = ArrayList<String>() titles.add(title) val songContentPortraitViewFragment = SongContentPortraitViewFragment.newInstance(title, titles) val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.song_content_fragment, songContentPortraitViewFragment) transaction.addToBackStack(null) transaction.commit() } } public override fun onResume() { super.onResume() presentationScreenService!!.onResume() } override fun onStop() { super.onStop() presentationScreenService!!.onStop() } override fun onPause() { super.onPause() presentationScreenService!!.onPause() } override fun onBackPressed() { super.onBackPressed() finish() } }
apache-2.0
7da0d109bd3bf2d514c73d4a036fa907
33.664063
150
0.716024
5.539326
false
false
false
false