repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
alter-ego/unisannio-reboot
app/src/main/java/solutions/alterego/android/unisannio/repository/Parser.kt
1
1007
package solutions.alterego.android.unisannio.repository import org.jsoup.nodes.Document import rx.Single import solutions.alterego.android.unisannio.models.Article interface Parser { fun parse(document: Document): Single<List<Article>> } class ArticleParser : Parser { override fun parse(document: Document): Single<List<Article>> { return Single.fromCallable { document.select("item") .asSequence() .map { Article( id = it.select("guid").first()?.text().orEmpty(), title = it.select("title").first().text(), author = it.select("author").first().text(), url = it.select("link").first().text(), body = it.select("description").first().text(), date = it.select("pubDate").first()?.text().orEmpty() ) } .toList() } } }
apache-2.0
6844d0b64f9e017c5fe2609c2b7f7a6e
33.724138
77
0.513406
4.936275
false
false
false
false
rei-m/android_hyakuninisshu
domain/src/main/java/me/rei_m/hyakuninisshu/domain/karuta/model/KarutaNo.kt
1
1309
/* * Copyright (c) 2020. Rei Matsushita * * 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 me.rei_m.hyakuninisshu.domain.karuta.model import me.rei_m.hyakuninisshu.domain.ValueObject /** * 歌の番号. * * @param value 値 * * @throws IllegalArgumentException */ data class KarutaNo @Throws(IllegalArgumentException::class) constructor( val value: Int ) : ValueObject { init { if (value < MIN_VALUE || MAX_VALUE < value) { throw IllegalArgumentException("KarutaNo is Invalid, value is $value") } } companion object { private const val MIN_VALUE = 1 private const val MAX_VALUE = 100 val MIN = KarutaNo(MIN_VALUE) val MAX = KarutaNo(MAX_VALUE) val LIST = (MIN.value..MAX.value).map { KarutaNo(it) } } }
apache-2.0
df11c582dcef3ff18580a01a172ef521
29.928571
112
0.687452
3.996923
false
false
false
false
Aptoide/aptoide-client-v8
app/src/main/java/cm/aptoide/pt/wallet/WalletAppProvider.kt
1
2761
package cm.aptoide.pt.wallet import cm.aptoide.pt.app.DownloadModel import cm.aptoide.pt.app.DownloadStateParser import cm.aptoide.pt.install.Install import cm.aptoide.pt.install.InstallManager import cm.aptoide.pt.install.InstalledRepository import cm.aptoide.pt.promotions.WalletApp import cm.aptoide.pt.view.app.AppCenter import cm.aptoide.pt.view.app.DetailedAppRequestResult import rx.Observable class WalletAppProvider(val appCenter: AppCenter, val installedRepository: InstalledRepository, val installManager: InstallManager, val downloadStateParser: DownloadStateParser) { fun getWalletApp(): Observable<WalletApp> { return appCenter.loadDetailedApp("com.appcoins.wallet", "catappult") .toObservable() .map { app -> this.mapToWalletApp(app) }.flatMap { walletApp -> val walletAppObs = Observable.just<WalletApp>(walletApp) val isWalletInstalled = installedRepository.isInstalled(walletApp.packageName) val walletDownload = installManager.getInstall(walletApp.md5sum, walletApp.packageName, walletApp.versionCode) Observable.combineLatest<WalletApp, Boolean, Install, WalletApp>(walletAppObs, isWalletInstalled, walletDownload ) { walletApp, isInstalled, walletDownload -> this.mergeToWalletApp(walletApp, isInstalled, walletDownload) } } } private fun mergeToWalletApp(walletApp: WalletApp, isInstalled: Boolean, walletDownload: Install): WalletApp { val downloadModel = mapToDownloadModel(walletDownload.type, walletDownload.progress, walletDownload.state, walletDownload.isIndeterminate, walletDownload.appSize) walletApp.downloadModel = downloadModel walletApp.isInstalled = isInstalled return walletApp } private fun mapToDownloadModel(type: Install.InstallationType, progress: Int, state: Install.InstallationStatus, isIndeterminate: Boolean, appSize: Long): DownloadModel { return DownloadModel(downloadStateParser.parseDownloadType(type, false), progress, downloadStateParser.parseDownloadState(state, isIndeterminate), appSize) } private fun mapToWalletApp(result: DetailedAppRequestResult): WalletApp { if (result.hasError() || result.isLoading) return WalletApp() val app = result.detailedApp return WalletApp(null, false, app.name, app.icon, app.id, app.packageName, app.md5, app.versionCode, app.versionName, app.path, app.pathAlt, app.obb, app.size, app.developer.name, app.stats.rating.average, app.splits, app.requiredSplits) } }
gpl-3.0
5255fc934525ae31cd318477a5a91892
45.79661
97
0.707352
4.948029
false
false
false
false
greenspand/totemz
app/src/main/java/ro/cluj/totemz/mqtt/TotemzMqttManager.kt
1
7158
package ro.cluj.totemz.mqtt /* ktlint-disable no-wildcard-imports */ import android.app.Application import android.provider.Settings import com.google.firebase.auth.FirebaseAuth import kotlinx.coroutines.experimental.channels.ConflatedBroadcastChannel import kotlinx.coroutines.experimental.launch import org.eclipse.paho.client.mqttv3.IMqttActionListener import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken import org.eclipse.paho.client.mqttv3.IMqttToken import org.eclipse.paho.client.mqttv3.MqttAsyncClient import org.eclipse.paho.client.mqttv3.MqttCallback import org.eclipse.paho.client.mqttv3.MqttConnectOptions import org.eclipse.paho.client.mqttv3.MqttException import org.eclipse.paho.client.mqttv3.MqttMessage import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence import timber.log.Timber import java.util.* import kotlin.concurrent.fixedRateTimer class TotemzMqttManager(private val application: Application, private val accountManager: FirebaseAuth) : MqttManager { private var maxNumberOfRetries = 4 private var retryInterval = 4000L private var topics: Array<String> = arrayOf() private var qos: IntArray = intArrayOf() private var timerReconnect: Timer? = null private var retryCount = 0 private var isMqttClientConnected = false private var mqttClient: MqttAsyncClient? = null private val mqttMessageChannel by lazy { ConflatedBroadcastChannel<Pair<String, MqttMessage>>() } private val mqttConnectionStateChannel by lazy { ConflatedBroadcastChannel<Boolean>() } private var explicitDisconnection = false @SuppressWarnings("HardwareIds") override fun connect(serverURI: String, topics: Array<String>, qos: IntArray) { if (isMqttClientConnected) { Timber.w("connect was called although the mqttClient is already connected") return } [email protected] = topics [email protected] = qos val clientId = "${Settings.Secure.getString(application.contentResolver, Settings.Secure.ANDROID_ID)}" mqttClient = MqttAsyncClient(serverURI, clientId, MemoryPersistence()) mqttClient?.setCallback(object : MqttCallback { @Throws(Exception::class) override fun messageArrived(topic: String, message: MqttMessage) { val msg = message.payload.toString(Charsets.UTF_8) Timber.w("Message arrived: $msg") launch { mqttMessageChannel.send(topic to message) } } override fun deliveryComplete(token: IMqttDeliveryToken?) = Unit override fun connectionLost(cause: Throwable) { isMqttClientConnected = false launch { mqttConnectionStateChannel.send(false) } mqttConnectionStateChannel.close() Timber.w(cause, "MQTT connection lost") if (!explicitDisconnection) { resetTimer() retry() } } }) val connectAction: IMqttActionListener = object : IMqttActionListener { override fun onSuccess(asyncActionToken: IMqttToken?) { isMqttClientConnected = true sendConnectionStatus(true) Timber.w("MQTT connected") mqttClient?.subscribe(topics, qos, null, object : IMqttActionListener { override fun onSuccess(asyncActionToken: IMqttToken?) { Timber.w("MQTT subscription successful") } override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable) { Timber.e(exception, "MQTT could not subscribe") } }) } override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable) { isMqttClientConnected = false mqttMessageChannel.close() mqttConnectionStateChannel.close() Timber.e(exception, "MQTT could not establish connection") if (!explicitDisconnection) { retry() } } } try { val options = MqttConnectOptions().apply { isCleanSession = true userName = accountManager.currentUser?.displayName } mqttClient?.connect(options, null, connectAction) } catch (cause: MqttException) { Timber.e(cause, "MQTT connecting issue: ") } } fun sendConnectionStatus(isConnected: Boolean) = launch { mqttConnectionStateChannel.send(isConnected) } fun sendMqttMessage(message: Pair<String, MqttMessage>) = launch { mqttMessageChannel.send(message) } override fun disconnect() { if (!isMqttClientConnected) { Timber.w("disconnect was called although the mqttClient is not connected") return } val disconnectAction: IMqttActionListener = object : IMqttActionListener { override fun onSuccess(asyncActionToken: IMqttToken?) { Timber.w("Mqtt Client disconnected") isMqttClientConnected = false explicitDisconnection = true mqttMessageChannel.close() mqttConnectionStateChannel.close() } override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable) { Timber.e(exception, "Could not disconnect MQTT client") } } try { if (mqttClient?.isConnected == true) mqttClient?.disconnect(null, disconnectAction) } catch (cause: MqttException) { if (cause.reasonCode == MqttException.REASON_CODE_CLIENT_ALREADY_DISCONNECTED.toInt()) { isMqttClientConnected = false explicitDisconnection = true Timber.e(cause, "Client is already disconnected!") } else { Timber.e(cause, "Disconnection error") } } } override fun setRetryIntervalTime(retryInterval: Long) { this.retryInterval = retryInterval } override fun setMaxNumberOfRetires(maxNumberOfRetries: Int) { this.maxNumberOfRetries = maxNumberOfRetries } private fun resetTimer() { retryCount = 0 timerReconnect?.let { it.cancel() it.purge() } timerReconnect = null } private fun retry() { if (timerReconnect == null) { timerReconnect = fixedRateTimer("mqtt_reconnect_timer", true, 0, retryInterval) { retryCount++ Timber.w("MQTT reconnect retry $retryCount") if (mqttClient?.isConnected == true || retryCount > maxNumberOfRetries) { sendConnectionStatus(isMqttClientConnected) cancel() } val loggedIn = accountManager.currentUser != null if (loggedIn) connect(mqttClient?.serverURI ?: "", topics, qos) else disconnect() } } } }
apache-2.0
52bd2412772236a110420f0127759fc6
41.360947
119
0.628108
5.476664
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/test/java/com/ichi2/anki/ActivityStartupMetaTest.kt
1
2781
/* * Copyright (c) 2020 David Allison <[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 com.ichi2.anki import android.content.pm.ActivityInfo import android.content.pm.PackageManager import androidx.test.ext.junit.runners.AndroidJUnit4 import com.ichi2.testutils.ActivityList import com.ichi2.testutils.ActivityList.ActivityLaunchParam import com.ichi2.utils.KotlinCleanup import org.hamcrest.MatcherAssert import org.hamcrest.Matchers import org.junit.Test import org.junit.runner.RunWith import java.util.* import java.util.stream.Collectors import kotlin.Throws @RunWith(AndroidJUnit4::class) class ActivityStartupMetaTest : RobolectricTest() { @Test @Throws(PackageManager.NameNotFoundException::class) @KotlinCleanup("remove throws; remove stream(), remove : String") @Suppress("deprecation") // getPackageInfo fun ensureAllActivitiesAreTested() { // if this fails, you may need to add the missing activity to ActivityList.allActivitiesAndIntents() // we can't access this in a static context val pm = targetContext.packageManager val packageInfo = pm.getPackageInfo(targetContext.packageName, PackageManager.GET_ACTIVITIES) val manifestActivities = packageInfo.activities val testedActivityClassNames = ActivityList.allActivitiesAndIntents().stream().map { obj: ActivityLaunchParam -> obj.className }.collect(Collectors.toSet()) val manifestActivityNames = Arrays.stream(manifestActivities) .map { x: ActivityInfo -> x.name } .filter { x: String -> x != "com.ichi2.anki.TestCardTemplatePreviewer" } .filter { x: String -> x != "com.ichi2.anki.AnkiCardContextMenuAction" } .filter { x: String -> x != "com.ichi2.anki.analytics.AnkiDroidCrashReportDialog" } .filter { x: String -> !x.startsWith("androidx") } .filter { x: String -> !x.startsWith("org.acra") } .filter { x: String -> !x.startsWith("leakcanary.internal") } .toArray() MatcherAssert.assertThat(testedActivityClassNames, Matchers.containsInAnyOrder(*manifestActivityNames)) } }
gpl-3.0
4ee8446909f0945ee92a490bfb87bda2
47.789474
164
0.728515
4.338534
false
true
false
false
recurly/recurly-client-android
AndroidSdk/src/main/java/com/recurly/androidsdk/data/network/RecurlyApiClient.kt
1
2024
package com.recurly.androidsdk.data.network import com.recurly.androidsdk.data.model.tokenization.TokenizationRequest import com.recurly.androidsdk.data.model.tokenization.TokenizationResponse import retrofit2.Response import retrofit2.http.Body import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.POST /** * Here should be all the calls to the api with retrofit */ interface RecurlyApiClient { @FormUrlEncoded @POST("js/v1/tokens") suspend fun recurlyTokenization( @Field(value = "first_name", encoded = true) first_name: String, @Field(value = "last_name", encoded = true) last_name: String, @Field(value = "company", encoded = true) company: String, @Field(value = "address1", encoded = true) address1: String, @Field(value = "address2", encoded = true) address2: String, @Field(value = "city", encoded = true) city: String, @Field(value = "state", encoded = true) state: String, @Field(value = "postal_code", encoded = true) postal_code: String, @Field(value = "country", encoded = true) country: String, @Field(value = "phone", encoded = true) phone: String, @Field(value = "vat_number", encoded = true) vat_number: String, @Field(value = "tax_identifier", encoded = true) tax_identifier: String, @Field(value = "tax_identifier_type", encoded = true) tax_identifier_type: String, @Field(value = "number", encoded = true) number: Long, @Field(value = "month", encoded = true) month: Int, @Field(value = "year", encoded = true) year: Int, @Field(value = "cvv", encoded = true) cvv: Int, @Field(value = "version", encoded = true) version: String, @Field(value = "key", encoded = true) key: String, @Field(value = "deviceId", encoded = true) deviceId: String, @Field(value = "sessionId", encoded = true) sessionId: String ): Response<TokenizationResponse> }
mit
07b0c9ec060ff9dd7533093287eee462
46.238095
90
0.650198
3.804511
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/text/LanternLiteralTextSerializer.kt
1
1325
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.text import net.kyori.adventure.text.serializer.ComponentSerializer import org.lanternpowered.api.Lantern import org.lanternpowered.api.text.Text import org.lanternpowered.api.text.serializer.TextSerializer import org.spongepowered.api.util.locale.Locales import java.util.Locale open class LanternLiteralTextSerializer( private val serializer: ComponentSerializer<Text, out Text, String> ) : TextSerializer { private val renderer = LiteralTextRenderer(Translators.GlobalAndMinecraft) override fun serialize(text: Text): String = this.serialize(text, Locales.DEFAULT) override fun serialize(text: Text, locale: Locale): String { val rendered = this.renderer.render(text, FormattedTextRenderContext(locale, scoreboard = Lantern.server.serverScoreboard.get())) return this.serializer.serialize(rendered) } override fun deserialize(input: String): Text = this.serializer.deserialize(input) }
mit
e8f1b8b118b82eefe1c8641ae2e069ba
35.805556
103
0.750189
4.301948
false
false
false
false
ratabb/Hishoot2i
template/src/main/java/template/TemplateFactoryManagerImpl.kt
1
3587
package template import android.content.Context import androidx.annotation.WorkerThread import androidx.core.util.lruCache import common.FileConstants import template.Template.Default import template.Template.Version1 import template.Template.Version2 import template.Template.Version3 import template.Template.VersionHtz import template.TemplateConstants.DEFAULT_TEMPLATE_ID import template.TemplateConstants.TEMPLATE_CFG import template.converter.HtzConverter import template.converter.HtzConverterImpl import template.factory.DefaultFactory import template.factory.Factory import template.factory.Version1Factory import template.factory.Version2Factory import template.factory.Version3Factory import template.factory.VersionHtzFactory import template.model.ModelHtz import template.serialize.ModelSerialize import template.serialize.ModelSerializeImpl import java.io.File import java.util.Locale import java.util.zip.ZipFile @WorkerThread class TemplateFactoryManagerImpl constructor( private val appContext: Context, fileConstants: FileConstants ) : TemplateFactoryManager, ModelSerialize by ModelSerializeImpl { private val cache = lruCache<String, Template>(maxSize = 64) private val htzDir: () -> File = (fileConstants::htzDir) private val savedDir: () -> File = (fileConstants::savedDir) private val htzConverter: HtzConverter by lazy { HtzConverterImpl(appContext, htzDir, ::encodeModelHtz) } override fun default(): Default = DEFAULT_TEMPLATE_ID cacheOrNewBy DefaultFactory(appContext) override fun version1(name: String, installed: Long): Version1 = name cacheOrNewBy Version1Factory(appContext, name, installed, ::decodeModelV1) override fun version2(name: String, installed: Long): Version2 = name cacheOrNewBy Version2Factory(appContext, name, installed, ::decodeModelV2) override fun version3(name: String, installed: Long): Version3 = name cacheOrNewBy Version3Factory(appContext, name, installed, ::decodeModelV3) override fun versionHtz(path: String, installed: Long): VersionHtz = path cacheOrNewBy VersionHtzFactory(htzDir(), path, installed, ::decodeModelHtz) override fun importHtz(file: File): VersionHtz { val id = ZipFile(file).entryInputStream(TEMPLATE_CFG) .use(::decodeModelHtz).run { generatorHtzId(this) } decompressHtz(file, File(htzDir(), id)) return versionHtz(id, System.currentTimeMillis()) } override fun convertHtz(template: Template): VersionHtz { val id = htzConverter.convert(template, ::generatorHtzId) return versionHtz(id, System.currentTimeMillis()) } override fun exportHtz(versionHtz: VersionHtz): File { val src = File(htzDir(), versionHtz.id) check(src.exists() && src.isDirectory) { "src must exist and its dir, ${src.absolutePath}" } val dst = File(savedDir(), "${versionHtz.name}.htz") compressHtz(src, dst) return dst } override fun removeHtz(versionHtz: VersionHtz): String { File(htzDir(), versionHtz.id).deleteRecursively() return versionHtz.name } private fun generatorHtzId(modelHtz: ModelHtz): String = modelHtz.run { "${author.hashCode()}_${name.toLowerCase(Locale.ROOT)}" .replace("[^\\w]".toRegex(), "") // removing non word char .trim().take(32) // limit } private inline infix fun <reified T : Template> String.cacheOrNewBy(factory: Factory<T>): T = cache.get(this) as? T? ?: factory.newTemplate().also { cache.put(this, it) } }
apache-2.0
adbebd6f6584953ae508832777bcba5c
38.855556
100
0.735991
4.406634
false
false
false
false
andersonlucasg3/SpriteKit-Android
SpriteKitLib/src/main/java/br/com/insanitech/spritekit/actions/SKAction.kt
1
5713
package br.com.insanitech.spritekit.actions import android.content.Context import android.support.annotation.IdRes import br.com.insanitech.spritekit.SKNode import br.com.insanitech.spritekit.SKTexture import br.com.insanitech.spritekit.core.SKBlock import br.com.insanitech.spritekit.graphics.SKPoint import br.com.insanitech.spritekit.graphics.SKSize import java.util.* abstract class SKAction { private var started = false internal var key = "" internal var completion: SKBlock? = null internal var startedTime: Long = 0 private set var speed = 1f var duration: Long = 1000 var timingMode = defaultTiming internal fun start(node: SKNode) { if (!this.started) { this.started = true this.startedTime = System.currentTimeMillis() this.computeStart(node) } } protected fun restart() { this.started = false } internal abstract fun computeStart(node: SKNode) internal abstract fun computeAction(node: SKNode, elapsed: Long) internal abstract fun computeFinish(node: SKNode) internal open fun hasCompleted(elapsed: Long) : Boolean = elapsed >= this.duration internal fun dispatchCompletion() { this.completion?.invoke() } companion object { private var defaultTiming = SKActionTimingMode.EaseOut fun moveBy(deltaPosition: SKPoint, duration: Long): SKAction = moveBy(deltaPosition.x, deltaPosition.y, duration) fun moveBy(deltaX: Float, deltaY: Float, duration: Long): SKAction { val action = SKActionMoveBy(SKPoint(deltaX, deltaY)) action.duration = duration return action } fun moveTo(toX: Float, toY: Float, duration: Long): SKAction = moveTo(SKPoint(toX, toY), duration) fun moveTo(position: SKPoint, duration: Long): SKAction { val action = SKActionMoveTo(position) action.duration = duration return action } fun rotateBy(radians: Float, duration: Long): SKAction { val action = SKActionRotateBy(radians) action.duration = duration return action } fun rotateTo(radians: Float, duration: Long): SKAction { val action = SKActionRotateTo(radians) action.duration = duration return action } fun resizeBy(width: Float, height: Float, duration: Long): SKAction = resizeBy(SKSize(width, height), duration) fun resizeBy(size: SKSize, duration: Long): SKAction { val action = SKActionResizeBy(size) action.duration = duration return action } fun resizeTo(width: Float, height: Float, duration: Long): SKAction = resizeTo(SKSize(width, height), duration) fun resizeTo(size: SKSize, duration: Long): SKAction { val action = SKActionResizeTo(size) action.duration = duration return action } fun playSoundFile(context: Context, @IdRes resId: Int): SKAction { val action = SKActionPlaySoundFile(context, resId) action.duration = 0 return action } fun sequence(sequence: List<SKAction>): SKAction = SKActionSequence(LinkedList(sequence)) fun group(group: List<SKAction>): SKAction = SKActionGroup(ArrayList(group)) fun waitFor(duration: Long): SKAction { val action = SKActionWaitFor() action.duration = duration return action } fun waitFor(duration: Long, range: Long): SKAction { val action = SKActionWaitFor() val random = Random() val sum = random.nextInt(range.toInt()).toLong() action.duration = duration + sum return action } fun fadeIn(duration: Long): SKAction { val action = SKActionFadeIn() action.duration = duration return action } fun fadeOut(duration: Long): SKAction { val action = SKActionFadeOut() action.duration = duration return action } fun fadeAlphaTo(alpha: Float, duration: Long): SKAction { val action = SKActionFadeAlphaTo(alpha) action.duration = duration return action } fun fadeAlphaBy(alpha: Float, duration: Long): SKAction { val action = SKActionFadeAlphaBy(alpha) action.duration = duration return action } fun scaleTo(scale: Float, duration: Long): SKAction = scaleTo(scale, scale, duration) fun scaleTo(x: Float, y: Float, duration: Long): SKAction { val action = SKActionScaleTo(x, y) action.duration = duration return action } fun scaleBy(scale: Float, duration: Long): SKAction = scaleBy(scale, scale, duration) fun scaleBy(x: Float, y: Float, duration: Long): SKAction { val action = SKActionScaleBy(x, y) action.duration = duration return action } fun setTexture(texture: SKTexture): SKAction { val action = SKActionSetTexture(texture) action.duration = 0 return action } fun run(completion: SKBlock): SKAction { val action = SKActionRun(completion) action.duration = 0 return action } fun removeFromParent(): SKAction { val action = SKActionRemoveFromParent() action.duration = 0 return action } } }
bsd-3-clause
eafb33f9aa37db2ec8137f137caadfef
30.395604
97
0.603536
4.912296
false
false
false
false
debop/debop4k
debop4k-units/src/main/kotlin/debop4k/units/Lengths.kt
1
4647
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ @file:JvmName("Lengths") package debop4k.units import java.io.Serializable const val MILLIMETER_IN_METER = 1.0e-3 const val CENTIMETER_IN_METER = 1.0e-2 const val METER_IN_METER = 1.0 const val KILOMETER_IN_METER = 1.0e3 const val INCH_IN_METER = 39.37 const val FEET_IN_METER = 3.2809 const val YARD_IN_METER = 1.0936 const val MILE_IN_METER = 1609.344 fun Double.millimeter(): Length = Length.of(this, LengthUnit.MILLIMETER) fun Double.centimeter(): Length = Length.of(this, LengthUnit.CENTIMETER) fun Double.meter(): Length = Length.of(this) fun Double.kilometer(): Length = Length.of(this, LengthUnit.KILOMETER) //fun Double.inch(): Length = Length.of(this, LengthUnit.INCH) //fun Double.feet(): Length = Length.of(this, LengthUnit.FEET) //fun Double.yard(): Length = Length.of(this, LengthUnit.YARD) //fun Double.mile(): Length = Length.of(this, LengthUnit.MILE) /** * 길이(Length)의 단위 */ enum class LengthUnit(val unitName: String, val factor: Double) { MILLIMETER("mm", MILLIMETER_IN_METER), CENTIMETER("cm", CENTIMETER_IN_METER), METER("m", METER_IN_METER), KILOMETER("km", KILOMETER_IN_METER); // INCH("inch", INCH_IN_METER), // FEET("ft", FEET_IN_METER), // YARD("yd", YARD_IN_METER), // MILE("ml", MILE_IN_METER); companion object { @JvmStatic fun parse(str: String): LengthUnit { val lower = str.toLowerCase() return LengthUnit.values().find { it.unitName == lower } ?: throw UnsupportedOperationException("Unknwon Length unit string. str=$str") } } } /** * 길이를 나타내는 클래스 */ data class Length(val meter: Double = 0.0) : Comparable<Length>, Serializable { operator final fun plus(other: Length): Length = Length(meter + other.meter) operator final fun minus(other: Length): Length = Length(meter - other.meter) operator final fun times(scalar: Double): Length = Length(meter * scalar) operator final fun times(other: Length): Area = Area(meter * other.meter) operator final fun div(scalar: Double): Length = Length(meter / scalar) operator final fun unaryMinus(): Length = Length(-meter) fun inMillimeter(): Double = meter / LengthUnit.MILLIMETER.factor fun inCentimeter(): Double = meter / LengthUnit.CENTIMETER.factor fun inMeter(): Double = meter fun inKilometer(): Double = meter / LengthUnit.KILOMETER.factor // fun inInch(): Double = meter / LengthUnit.INCH.factor // fun inFeet(): Double = meter / LengthUnit.FEET.factor // fun inYard(): Double = meter / LengthUnit.YARD.factor // fun inMile(): Double = meter / LengthUnit.MILE.factor override fun compareTo(other: Length): Int = meter.compareTo(other.meter) override fun toString(): String = "%.1f %s".format(meter, LengthUnit.METER.factor) fun toHuman(): String { val value = Math.abs(meter) val displayUnit = LengthUnit.values().last { value / it.factor > 1.0 } return "%.1f %s".format(meter / displayUnit.factor, displayUnit.unitName) } fun toHuman(unit: LengthUnit): String { return "%.1f %s".format(meter / unit.factor, unit.unitName) } companion object { @JvmField val ZERO = Length(0.0) @JvmField val MIN_VALUE = Length(Double.MIN_VALUE) @JvmField val MAX_VALUE = Length(Double.MAX_VALUE) @JvmField val POSITIVE_INF = Length(Double.POSITIVE_INFINITY) @JvmField val NEGATIVE_INF = Length(Double.NEGATIVE_INFINITY) @JvmField val NaN = Length(Double.NaN) @JvmOverloads @JvmStatic fun of(length: Double = 0.0, unit: LengthUnit = LengthUnit.METER): Length = Length(length * unit.factor) /** * 문자열을 파싱하여 [Length] 인스턴스를 빌드합니다 */ @JvmStatic fun parse(str: String?): Length { if (str.isNullOrBlank()) { return ZERO } try { val (length, unit) = str!!.split(" ", limit = 2) return of(length.toDouble(), LengthUnit.parse(unit)) } catch(e: Exception) { throw NumberFormatException("Invalid Length string. str=$str") } } } }
apache-2.0
6c45804fbeef5b0d4480b1c4e55a3ba4
33.19403
91
0.686313
3.531997
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/editor/postfix/LatexPostfixTemplateFromPackageProvider.kt
1
2122
package nl.hannahsten.texifyidea.editor.postfix import com.intellij.codeInsight.template.postfix.templates.PostfixTemplate import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateProvider import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiFile import nl.hannahsten.texifyidea.lang.LatexPackage import nl.hannahsten.texifyidea.util.insertUsepackage abstract class LatexPostfixTemplateFromPackageProvider(private val pack: LatexPackage) : PostfixTemplateProvider { abstract override fun getTemplates(): MutableSet<PostfixTemplate> override fun isTerminalSymbol(currentChar: Char): Boolean = (currentChar == '.' || currentChar == ',') override fun afterExpand(file: PsiFile, editor: Editor) { file.insertUsepackage(pack) } override fun preCheck(copyFile: PsiFile, realEditor: Editor, currentOffset: Int): PsiFile = copyFile override fun preExpand(file: PsiFile, editor: Editor) {} companion object { fun getProvider(pack: LatexPackage?): PostfixTemplateProvider { return when (pack) { LatexPackage.AMSMATH -> LatexPostfixTemplateFromAmsMathProvider LatexPackage.AMSFONTS -> LatexPostfixTemplateFromAmsFontsProvider LatexPackage.BM -> LatexPostfixTemplateFromBmProvider else -> LatexPostFixTemplateProvider } } } } object LatexPostfixTemplateFromAmsMathProvider : LatexPostfixTemplateFromPackageProvider(LatexPackage.AMSMATH) { override fun getTemplates(): MutableSet<PostfixTemplate> = mutableSetOf( LatexWrapWithTextPostfixTemplate ) } object LatexPostfixTemplateFromAmsFontsProvider : LatexPostfixTemplateFromPackageProvider(LatexPackage.AMSFONTS) { override fun getTemplates(): MutableSet<PostfixTemplate> = mutableSetOf( LatexWrapWithMathbbPostfixTemplate ) } object LatexPostfixTemplateFromBmProvider : LatexPostfixTemplateFromPackageProvider(LatexPackage.BM) { override fun getTemplates(): MutableSet<PostfixTemplate> = mutableSetOf( LatexWrapWithBmPostfixTemplate ) }
mit
d9aa9be598816d1acd5dc4f0dbf2b86a
36.245614
114
0.762017
5.584211
false
false
false
false
debop/debop4k
debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/calendars/CalendarPeriodCollector.kt
1
6398
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.timeperiod.calendars import debop4k.core.kodatimes.asDate import debop4k.core.loggerOf import debop4k.timeperiod.* import debop4k.timeperiod.timeranges.* /** * Created by debop */ open class CalendarPeriodCollector @JvmOverloads constructor( filter: CalendarPeriodCollectorFilter, limits: ITimePeriod, seekDir: SeekDirection = SeekDirection.Forward, calendar: ITimeCalendar = DefaultTimeCalendar) : CalendarVisitor<CalendarPeriodCollectorFilter, CalendarPeriodCollectorContext>( filter, limits, seekDir, calendar) { private val log = loggerOf(javaClass) companion object { @JvmStatic @JvmOverloads fun of(filter: CalendarPeriodCollectorFilter, limits: ITimePeriod, seekDir: SeekDirection = SeekDirection.Forward, calendar: ITimeCalendar = DefaultTimeCalendar): CalendarPeriodCollector { return CalendarPeriodCollector(filter, limits, seekDir, calendar) } } val periods: ITimePeriodCollection = TimePeriodCollection() fun collectYears(): Unit = collectByScope(CollectKind.Year) fun collectMonths(): Unit = collectByScope(CollectKind.Month) fun collectDays(): Unit = collectByScope(CollectKind.Day) fun collectHours(): Unit = collectByScope(CollectKind.Hour) fun collectMinutes(): Unit = collectByScope(CollectKind.Minute) private fun collectByScope(scope: CollectKind): Unit { val context = CalendarPeriodCollectorContext(scope) startPeriodVisit(context) } override fun enterYears(years: YearRangeCollection, context: CalendarPeriodCollectorContext): Boolean { return context.scope.value > CollectKind.Year.value } override fun enterMonths(year: YearRange, context: CalendarPeriodCollectorContext): Boolean { return context.scope.value > CollectKind.Month.value } override fun enterDays(month: MonthRange, context: CalendarPeriodCollectorContext): Boolean { return context.scope.value > CollectKind.Day.value } override fun enterHours(day: DayRange, context: CalendarPeriodCollectorContext): Boolean { return context.scope.value > CollectKind.Hour.value } override fun enterMinutes(hour: HourRange, context: CalendarPeriodCollectorContext): Boolean { return context.scope.value > CollectKind.Minute.value } override fun onVisitYears(years: YearRangeCollection, context: CalendarPeriodCollectorContext): Boolean { log.trace("visit years ... years={}, context={}", years, context) if (context.scope != CollectKind.Year) { return true } years.years() .filter { isMatchingYear(it, context) && checkLimits(it) } .forEach { periods.add(it) } return false } override fun onVisitYear(year: YearRange, context: CalendarPeriodCollectorContext): Boolean { log.trace("visit year ... year={}, context={}", year, context) if (context.scope != CollectKind.Month) { return true } val monthFilter: (MonthRange) -> Boolean = { isMatchingMonth(it, context) && checkLimits(it) } if (filter.collectingMonths.isEmpty) { year.months().filter(monthFilter).forEach { periods.add(it) } } else { filter.collectingMonths.forEach { m -> if (m.isSingleMonth) { val mr = MonthRange(asDate(year.year, m.startMonthOfYear), year.calendar) if (monthFilter(mr)) { periods.add(mr) } } else { val mc = MonthRangeCollection(year.year, m.startMonthOfYear, m.endMonthOfYear - m.startMonthOfYear, year.calendar) val months = mc.months() val isMatch = months.all { isMatchingMonth(it, context) } if (isMatch && checkLimits(mc)) { periods.addAll(months) } } } } return false } override fun onVisitMonth(month: MonthRange, context: CalendarPeriodCollectorContext): Boolean { log.trace("visit month... month={}, context={}", month, context) if (context.scope != CollectKind.Day) { return true } val dayFilter: (DayRange) -> Boolean = { isMatchingDay(it, context) && checkLimits(it) } if (filter.collectingDays.isEmpty) { month.days().filter(dayFilter).forEach { periods.add(it) } } else { filter.collectingDays.forEach { day -> val startTime = asDate(month.year, month.monthOfYear, day.startDayOfMonth) if (day.isSingleDay) { val dayRange = DayRange(startTime, month.calendar) if (dayFilter(dayRange)) { periods.add(dayRange) } } else { val dc = DayRangeCollection(startTime, day.endDayOfMonth - day.startDayOfMonth, month.calendar) val days = dc.days() val isMatch = days.all { isMatchingDay(it, context) } if (isMatch && checkLimits(dc)) { periods.addAll(days) } } } } return false } override fun onVisitDay(day: DayRange, context: CalendarPeriodCollectorContext): Boolean { log.trace("visit day... day={}, context={}", day, context) if (filter.collectingHours.isEmpty) { day.hours() .filter { isMatchingHour(it, context) && checkLimits(it) } .forEach { periods.add(it) } } else if (isMatchingDay(day, context)) { filter.collectingHours.forEach { h -> val start = h.start.toDateTime(day.start) val end = h.endExclusive.toDateTime(day.start) val hc = CalendarTimeRange(start, end, day.calendar) if (checkExcludePeriods(hc) && checkLimits(hc)) { periods.add(hc) } } } return false } }
apache-2.0
36087cdcc56a9cf36791173fd4a7bfbf
33.589189
107
0.660988
4.55698
false
false
false
false
ziggy42/Blum
app/src/main/java/com/andreapivetta/blu/ui/login/LoginActivity.kt
1
1649
package com.andreapivetta.blu.ui.login import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.Toast import com.andreapivetta.blu.R import com.andreapivetta.blu.common.settings.AppSettingsFactory import com.andreapivetta.blu.ui.main.MainActivity import kotlinx.android.synthetic.main.activity_login.* class LoginActivity : AppCompatActivity(), LoginMvpView { private val presenter = LoginPresenter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) presenter.attachView(this) loginButton.setOnClickListener { presenter.performLogin() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == LoginPresenter.CODE_OAUTH) if (resultCode == RESULT_OK) presenter.onResultOk() else presenter.onResultCanceled() } override fun showOauthActivity(requestCode: Int) { startActivityForResult(Intent(this, TwitterOAuthActivity::class.java), requestCode) } override fun showLoginError() { Toast.makeText(this, getString(R.string.error), Toast.LENGTH_LONG).show() } override fun showLoginCanceled() { Toast.makeText(this, getString(R.string.cancellation), Toast.LENGTH_LONG).show() } override fun moveOn() { startActivity(Intent(this, MainActivity::class.java)) finish() } override fun isUserLoggedIn() = AppSettingsFactory.getAppSettings(this).isUserLoggedIn() }
apache-2.0
42c161542879596db7aa7164b995b79e
31.333333
92
0.713766
4.64507
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/intro/slides/ActionItemsSlide.kt
1
2306
package com.pr0gramm.app.ui.intro.slides import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ListView import android.widget.TextView import androidx.annotation.ColorRes import com.pr0gramm.app.R import com.pr0gramm.app.ui.base.BaseFragment import com.pr0gramm.app.util.find import com.pr0gramm.app.util.findOptional /** */ abstract class ActionItemsSlide(name: String) : BaseFragment(name) { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater.inflate(layoutId, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val titleView = view.findOptional<TextView>(R.id.title) titleView?.text = introTitle val descriptionView = view.findOptional<TextView>(R.id.description) descriptionView?.text = introDescription val actionItems = introActionItems val listView = view.find<ListView>(R.id.recycler_view) listView.choiceMode = if (singleChoice) ListView.CHOICE_MODE_SINGLE else ListView.CHOICE_MODE_MULTIPLE listView.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_list_item_multiple_choice, android.R.id.text1, actionItems) listView.setOnItemClickListener { _, _, position, _ -> val item = actionItems[position] if (listView.isItemChecked(position)) { item.activate() } else { item.deactivate() } } for (idx in actionItems.indices) { if (actionItems[idx].enabled()) { listView.setItemChecked(idx, true) } } introBackgroundResource?.let { res -> view.setBackgroundResource(res) } } open val singleChoice: Boolean = false open val layoutId: Int = R.layout.intro_fragment_items @ColorRes open val introBackgroundResource: Int? = null abstract val introTitle: String abstract val introDescription: String abstract val introActionItems: List<ActionItem> }
mit
badf9f1d65c7d1035651ed48e758851c
31.027778
110
0.677797
4.584493
false
false
false
false
cout970/Statistics
src/main/kotlin/com/cout970/statistics/tileentity/TileInventoryConnector.kt
1
4065
package com.cout970.statistics.tileentity import com.cout970.statistics.block.BlockCable import com.cout970.statistics.block.BlockController import net.minecraft.item.ItemStack import net.minecraft.util.EnumFacing import net.minecraft.util.ITickable import net.minecraft.util.math.BlockPos import net.minecraftforge.common.capabilities.Capability import net.minecraftforge.items.CapabilityItemHandler import net.minecraftforge.items.IItemHandler import java.util.* /** * Created by cout970 on 05/08/2016. */ class TileInventoryConnector : TileBase(), ITickable { val inventory = Inventory() override fun update() { if ((worldObj.totalWorldTime + pos.hashCode()) % 20 == 0L) { inventory.subInventories.clear() inventory.subInventories.addAll(getInventories().filter { it !is Inventory }) } } override fun getInventories(): List<IItemHandler> { val list = mutableSetOf<IItemHandler>() val forbiden = setOf(pos.offset(EnumFacing.DOWN), pos.offset(EnumFacing.UP), pos.offset(EnumFacing.NORTH), pos.offset(EnumFacing.SOUTH), pos.offset(EnumFacing.EAST), pos.offset(EnumFacing.WEST)) val queue = LinkedList<Pair<BlockPos, EnumFacing>>() val map = HashSet<Pair<BlockPos, EnumFacing>>() for (dir in EnumFacing.VALUES) { queue.add(pos to dir) map.add(pos to dir) } while (!queue.isEmpty()) { val pair = queue.pop() val pos = pair.first.offset(pair.second) val block = worldObj.getBlockState(pos).block if (block == BlockCable || block == BlockController) { for (dir in EnumFacing.VALUES) { if ((pos to dir) !in map) { queue.add(pos to dir) map.add(pos to dir) } } } else if (pos !in forbiden) { val tile = worldObj.getTileEntity(pos) if (tile != null) { val inventory = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, pair.second.opposite) if (inventory != null) { list.add(inventory) } } } } return LinkedList(list) } override fun <T : Any?> getCapability(capability: Capability<T>?, facing: EnumFacing?): T { @Suppress("UNCHECKED_CAST") if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) return inventory as T return super.getCapability(capability, facing) } override fun hasCapability(capability: Capability<*>?, facing: EnumFacing?): Boolean { if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) return true return super.hasCapability(capability, facing) } inner class Inventory : IItemHandler { val subInventories = mutableListOf<IItemHandler>() fun getSlot(index: Int): Pair<Int, IItemHandler>? { var acum = 0 for (i in subInventories) { val slots = i.slots if (index >= acum + slots) { acum += i.slots } else { return (index - acum) to i } } return null } override fun getStackInSlot(slot: Int): ItemStack? { val pair = getSlot(slot) ?: return null return pair.second.getStackInSlot(pair.first) } override fun insertItem(slot: Int, stack: ItemStack?, simulate: Boolean): ItemStack? { val pair = getSlot(slot) ?: return stack return pair.second.insertItem(pair.first, stack, simulate) } override fun getSlots(): Int = subInventories.sumBy { it.slots } override fun extractItem(slot: Int, amount: Int, simulate: Boolean): ItemStack? { val pair = getSlot(slot) ?: return null return pair.second.extractItem(pair.first, amount, simulate) } } }
gpl-3.0
7d0dd4e12299555eb4df25b103c44659
35.963636
144
0.596064
4.661697
false
false
false
false
ademar111190/Studies
Projects/Reddit/core/src/main/java/ademar/study/reddit/core/model/internal/Comment.kt
1
556
package ademar.study.reddit.core.model.internal import com.bluelinelabs.logansquare.annotation.JsonField import com.bluelinelabs.logansquare.annotation.JsonObject @JsonObject class Comment { @JsonField(name = arrayOf("replies")) var replies: PostDetailDataReply? = null @JsonField(name = arrayOf("author")) lateinit var author: String @JsonField(name = arrayOf("body")) lateinit var text: String @JsonField(name = arrayOf("downs")) var downs: Long = 0L @JsonField(name = arrayOf("ups")) var ups: Long = 0L }
mit
69b221bff1b0029b0ece02d0a70c9bc0
22.166667
57
0.708633
3.943262
false
false
false
false
michaelgallacher/intellij-community
platform/projectModel-api/src/org/jetbrains/concurrency/AsyncPromise.kt
2
8700
/* * Copyright 2000-2016 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.concurrency import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Getter import com.intellij.util.Consumer import com.intellij.util.Function import org.jetbrains.concurrency.Promise.State import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import java.util.concurrent.atomic.AtomicReference private val LOG = Logger.getInstance(AsyncPromise::class.java) open class AsyncPromise<T> : Promise<T>, Getter<T> { private val doneRef = AtomicReference<Consumer<in T>?>() private val rejectedRef = AtomicReference<Consumer<in Throwable>?>() private val stateRef = AtomicReference(State.PENDING) // result object or error message @Volatile private var result: Any? = null override fun getState() = stateRef.get()!! override fun done(done: Consumer<in T>): Promise<T> { if (isObsolete(done)) { return this } when (state) { State.PENDING -> { setHandler(doneRef, done, State.FULFILLED) } State.FULFILLED -> { @Suppress("UNCHECKED_CAST") done.consume(result as T?) } State.REJECTED -> { } } return this } override fun rejected(rejected: Consumer<Throwable>): Promise<T> { if (isObsolete(rejected)) { return this } when (state) { State.PENDING -> { setHandler(rejectedRef, rejected, State.REJECTED) } State.FULFILLED -> { } State.REJECTED -> { rejected.consume(result as Throwable?) } } return this } @Suppress("UNCHECKED_CAST") override fun get() = if (state == State.FULFILLED) result as T? else null override fun <SUB_RESULT> then(handler: Function<in T, out SUB_RESULT>): Promise<SUB_RESULT> { @Suppress("UNCHECKED_CAST") when (state) { State.PENDING -> { } State.FULFILLED -> return DonePromise<SUB_RESULT>( handler.`fun`(result as T?)) State.REJECTED -> return rejectedPromise(result as Throwable) } val promise = AsyncPromise<SUB_RESULT>() addHandlers(Consumer({ result -> promise.catchError { if (handler is Obsolescent && handler.isObsolete) { promise.cancel() } else { promise.setResult(handler.`fun`(result)) } } }), Consumer({ promise.setError(it) })) return promise } override fun notify(child: AsyncPromise<in T>) { LOG.assertTrue(child !== this) when (state) { State.PENDING -> { addHandlers(Consumer({ child.catchError { child.setResult(it) } }), Consumer({ child.setError(it) })) } State.FULFILLED -> { @Suppress("UNCHECKED_CAST") child.setResult(result as T) } State.REJECTED -> { child.setError((result as Throwable?)!!) } } } override fun <SUB_RESULT> thenAsync(handler: Function<in T, Promise<SUB_RESULT>>): Promise<SUB_RESULT> { @Suppress("UNCHECKED_CAST") when (state) { State.PENDING -> { } State.FULFILLED -> return handler.`fun`(result as T?) State.REJECTED -> return rejectedPromise(result as Throwable) } val promise = AsyncPromise<SUB_RESULT>() val rejectedHandler = Consumer<Throwable>({ promise.setError(it) }) addHandlers(Consumer({ promise.catchError { handler.`fun`(it) .done { promise.catchError { promise.setResult(it) } } .rejected(rejectedHandler) } }), rejectedHandler) return promise } override fun processed(fulfilled: AsyncPromise<in T>): Promise<T> { when (state) { State.PENDING -> { addHandlers(Consumer({ result -> fulfilled.catchError { fulfilled.setResult(result) } }), Consumer({ fulfilled.setError(it) })) } State.FULFILLED -> { @Suppress("UNCHECKED_CAST") fulfilled.setResult(result as T) } State.REJECTED -> { fulfilled.setError((result as Throwable?)!!) } } return this } private fun addHandlers(done: Consumer<T>, rejected: Consumer<Throwable>) { setHandler(doneRef, done, State.FULFILLED) setHandler(rejectedRef, rejected, State.REJECTED) } fun setResult(result: T?) { if (!stateRef.compareAndSet(State.PENDING, State.FULFILLED)) { return } this.result = result val done = doneRef.getAndSet(null) rejectedRef.set(null) if (done != null && !isObsolete(done)) { done.consume(result) } } fun setError(error: String) = setError(createError(error)) fun cancel() { setError(OBSOLETE_ERROR) } open fun setError(error: Throwable): Boolean { if (!stateRef.compareAndSet(State.PENDING, State.REJECTED)) { return false } result = error val rejected = rejectedRef.getAndSet(null) doneRef.set(null) if (rejected == null) { LOG.errorIfNotMessage(error) } else if (!isObsolete(rejected)) { rejected.consume(error) } return true } override fun processed(processed: Consumer<in T>): Promise<T> { done(processed) rejected { processed.consume(null) } return this } override fun blockingGet(timeout: Int, timeUnit: TimeUnit): T? { val latch = CountDownLatch(1) processed { latch.countDown() } if (!latch.await(timeout.toLong(), timeUnit)) { throw TimeoutException() } @Suppress("UNCHECKED_CAST") if (isRejected) { throw (result as Throwable) } else { return result as T? } } private fun <T> setHandler(ref: AtomicReference<Consumer<in T>?>, newConsumer: Consumer<in T>, targetState: State) { while (true) { val oldConsumer = ref.get() val newEffectiveConsumer = when (oldConsumer) { null -> newConsumer is CompoundConsumer<*> -> { @Suppress("UNCHECKED_CAST") val compoundConsumer = oldConsumer as CompoundConsumer<T> var executed = true synchronized(compoundConsumer) { compoundConsumer.consumers?.let { it.add(newConsumer) executed = false } } // clearHandlers was called - just execute newConsumer if (executed) { if (state == targetState) { @Suppress("UNCHECKED_CAST") newConsumer.consume(result as T?) } return } compoundConsumer } else -> CompoundConsumer(oldConsumer, newConsumer) } if (ref.compareAndSet(oldConsumer, newEffectiveConsumer)) { break } } if (state == targetState) { ref.getAndSet(null)?.let { @Suppress("UNCHECKED_CAST") it.consume(result as T?) } } } } private class CompoundConsumer<T>(c1: Consumer<in T>, c2: Consumer<in T>) : Consumer<T> { var consumers: MutableList<Consumer<in T>>? = ArrayList() init { synchronized(this) { consumers!!.add(c1) consumers!!.add(c2) } } override fun consume(t: T) { val list = synchronized(this) { val list = consumers consumers = null list } ?: return for (consumer in list) { if (!isObsolete(consumer)) { consumer.consume(t) } } } fun add(consumer: Consumer<in T>) { synchronized(this) { consumers.let { if (it == null) { // it means that clearHandlers was called } consumers?.add(consumer) } } } } internal fun isObsolete(consumer: Consumer<*>?) = consumer is Obsolescent && consumer.isObsolete inline fun <T> AsyncPromise<*>.catchError(runnable: () -> T): T? { try { return runnable() } catch (e: Throwable) { setError(e) return null } }
apache-2.0
9b1e990de1a0907a2f6142003cad096e
26.275862
135
0.599655
4.438776
false
false
false
false
nemerosa/ontrack
ontrack-extension-scm/src/main/java/net/nemerosa/ontrack/extension/scm/catalog/api/GQLRootQuerySCMCatalogTeamStats.kt
1
2308
package net.nemerosa.ontrack.extension.scm.catalog.api import graphql.schema.GraphQLFieldDefinition import graphql.schema.GraphQLObjectType import net.nemerosa.ontrack.extension.scm.catalog.SCMCatalog import net.nemerosa.ontrack.graphql.schema.GQLRootQuery import net.nemerosa.ontrack.graphql.schema.GQLType import net.nemerosa.ontrack.graphql.schema.GQLTypeCache import net.nemerosa.ontrack.graphql.support.intField import net.nemerosa.ontrack.graphql.support.listType import org.springframework.stereotype.Component @Component class GQLRootQuerySCMCatalogTeamStats( private val scmCatalog: SCMCatalog, private val gqlTypeSCMCatalogTeamStats: GQLTypeSCMCatalogTeamStats ) : GQLRootQuery { override fun getFieldDefinition(): GraphQLFieldDefinition = GraphQLFieldDefinition.newFieldDefinition() .name("scmCatalogTeamStats") .description("Counts of SCM catalog entries having N teams") .type(listType(gqlTypeSCMCatalogTeamStats.typeRef)) .dataFetcher { // Collecting team counts val teamCounts = mutableMapOf<Int, Int>() scmCatalog.catalogEntries.forEach { entry -> val teamCount = entry.teams?.size ?: 0 val currentCount = teamCounts[teamCount] if (currentCount != null) { teamCounts[teamCount] = currentCount + 1 } else { teamCounts[teamCount] = 1 } } // OK teamCounts.map { (teamCount, entryCount) -> SCMCatalogTeamStats(teamCount, entryCount) }.sortedByDescending { it.teamCount } } .build() } @Component class GQLTypeSCMCatalogTeamStats : GQLType { override fun getTypeName(): String = SCMCatalogTeamStats::class.java.simpleName override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(typeName) .description("Number of entries in the SCM catalog having this number of teams") .intField(SCMCatalogTeamStats::teamCount, "Number of teams") .intField(SCMCatalogTeamStats::entryCount, "Number of entries having this number of teams") .build() } data class SCMCatalogTeamStats( val teamCount: Int, val entryCount: Int, )
mit
3fdcaa33704257425b5e42876b8a6700
37.466667
107
0.696274
5.186517
false
false
false
false
blakelee/CoinProfits
app/src/main/java/net/blakelee/coinprofits/tools/Utils.kt
1
1398
package net.blakelee.coinprofits.tools import android.content.Context import android.content.res.Resources import android.graphics.Paint import android.graphics.Rect import android.graphics.Typeface import java.text.NumberFormat val Int.dp: Float get() = (this / Resources.getSystem().displayMetrics.density + 0.5f) val Int.px: Float get() = (this * Resources.getSystem().displayMetrics.density + 0.5f) //Round to ceil fun textDim(text: String, context: Context, textSize: Float = 16f): Int { val bounds = Rect() val textPaint = Paint() textPaint.typeface = Typeface.DEFAULT textPaint.textSize = textSize textPaint.getTextBounds(text, 0, text.length, bounds) return bounds.width() * context.resources.displayMetrics.density.toInt() } fun decimalFormat(number: Double): String { val format = NumberFormat.getInstance() val splitter = "%f".format(number).split("\\.") format.minimumFractionDigits = 2 if (number > 1) format.maximumFractionDigits = 2 else { var places = 0 if (splitter[0].length > 2) for(char in splitter[0]) { if (char != '0' && places >= 2) { break } places++ } else { places = 2 } format.maximumFractionDigits = places } return format.format(number) }
mit
82b8fc1ba25d38138d74324b6e95c5ef
26.431373
92
0.628755
4.24924
false
false
false
false
goodwinnk/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/testCases/PluginTestCase.kt
2
5092
/* * 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.testGuiFramework.testCases import com.intellij.testGuiFramework.fixtures.JDialogFixture import com.intellij.testGuiFramework.framework.Timeouts import com.intellij.testGuiFramework.framework.Timeouts.seconds05 import com.intellij.testGuiFramework.impl.* import com.intellij.testGuiFramework.impl.GuiTestUtilKt.ignoreComponentLookupException import com.intellij.testGuiFramework.impl.GuiTestUtilKt.waitProgressDialogUntilGone import com.intellij.testGuiFramework.launcher.GuiTestOptions import com.intellij.testGuiFramework.remote.transport.MessageType import com.intellij.testGuiFramework.remote.transport.RestartIdeAndResumeContainer import com.intellij.testGuiFramework.remote.transport.RestartIdeCause import com.intellij.testGuiFramework.remote.transport.TransportMessage import org.fest.swing.exception.WaitTimedOutError import java.io.File import javax.swing.JDialog open class PluginTestCase : GuiTestCase() { val getEnv: String by lazy { File(System.getenv("WEBSTORM_PLUGINS") ?: throw IllegalArgumentException("WEBSTORM_PLUGINS env variable isn't specified")).absolutePath } fun findPlugin(pluginName: String): String { val f = File(getEnv) return f.listFiles { _, name -> name.startsWith(pluginName) }[0].toString() } fun installPluginAndRestart(installPluginsFunction: () -> Unit) { if (guiTestRule.getTestName() == GuiTestOptions.resumeTestName && GuiTestOptions.resumeInfo == PLUGINS_INSTALLED) { } else { //if plugins are not installed yet installPluginsFunction() //send restart message and resume this test to the server GuiTestThread.client?.send(TransportMessage(MessageType.RESTART_IDE_AND_RESUME, RestartIdeAndResumeContainer(RestartIdeCause.PLUGIN_INSTALLED))) ?: throw Exception( "Unable to get the client instance to send message.") //wait until IDE is going to restart GuiTestUtilKt.waitUntil("IDE will be closed", timeout = Timeouts.defaultTimeout) { false } } } fun installPlugins(vararg pluginNames: String) { welcomeFrame { actionLink("Configure").click() popupMenu("Plugins").clickSearchedItem() dialog("Plugins") { button("Install JetBrains plugin...").click() dialog("Browse JetBrains Plugins ") browsePlugins@ { pluginNames.forEach { [email protected](it) } button("Close").click() } button("OK") ensureButtonOkHasPressed(this@PluginTestCase) } message("IDE and Plugin Updates") { button("Postpone").click() } } } fun installPluginFromDisk(pluginPath: String, pluginName: String) { welcomeFrame { actionLink("Configure").click() popupMenu("Plugins").clickSearchedItem() pluginDialog { showInstalledPlugins() if (isPluginInstalled(pluginName).not()) { showInstallPluginFromDiskDialog() installPluginFromDiskDialog { setPath(pluginPath) clickOk() ignoreComponentLookupException { dialog(title = "Warning", timeout = seconds05) { message("Warning") { button("OK").click() } } } } } button("OK").click() ignoreComponentLookupException { dialog(title = "IDE and Plugin Updates", timeout = seconds05) { button("Postpone").click() } } } } } private fun ensureButtonOkHasPressed(guiTestCase: GuiTestCase) { val dialogTitle = "Plugins" try { GuiTestUtilKt.waitUntilGone(robot = guiTestCase.robot(), timeout = seconds05, matcher = GuiTestUtilKt.typeMatcher( JDialog::class.java) { it.isShowing && it.title == dialogTitle }) } catch (timeoutError: WaitTimedOutError) { with(guiTestCase) { val dialog = JDialogFixture.find(guiTestCase.robot(), dialogTitle) with(dialog) { button("OK").clickWhenEnabled() } } } } private fun JDialogFixture.installPlugin(pluginName: String) { table(pluginName).cell(pluginName).click() button("Install").click() waitProgressDialogUntilGone(robot(), "Downloading Plugins") println("$pluginName plugin has been installed") } companion object { const val PLUGINS_INSTALLED = "PLUGINS_INSTALLED" } }
apache-2.0
4d74f8c932fd874dd4169f5dcc3fe6b0
35.905797
170
0.681461
5.041584
false
true
false
false
material-components/material-components-android-examples
Owl/app/src/main/java/com/materialstudies/owl/ui/mycourses/MyCoursesAdapter.kt
1
3004
/* * Copyright (c) 2019 Google 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.materialstudies.owl.ui.mycourses import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.findNavController import androidx.navigation.fragment.FragmentNavigatorExtras import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.materialstudies.owl.R import com.materialstudies.owl.databinding.CourseItemBinding import com.materialstudies.owl.model.Course import com.materialstudies.owl.model.CourseDiff import com.materialstudies.owl.model.CourseId import com.materialstudies.owl.util.ShapeAppearanceTransformation class MyCoursesAdapter : ListAdapter<Course, MyCourseViewHolder>(CourseDiff) { private object onClick : CourseViewClick { override fun onClick(view: View, courseId: CourseId) { val extras = FragmentNavigatorExtras( view to "shared_element" ) val action = MyCoursesFragmentDirections.actionMycoursesToLearn(courseId) view.findNavController().navigate(action, extras) } } private val shapeTransform = ShapeAppearanceTransformation(R.style.ShapeAppearance_Owl_SmallComponent) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyCourseViewHolder { return MyCourseViewHolder( CourseItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: MyCourseViewHolder, position: Int) { holder.bind(getItem(position), shapeTransform, onClick) } } interface CourseViewClick { fun onClick(view: View, courseId: CourseId) } class MyCourseViewHolder( private val binding: CourseItemBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind( course: Course, imageTransform: ShapeAppearanceTransformation, onClick: CourseViewClick ) { binding.run { this.course = course this.clickHandler = onClick Glide.with(courseImage) .load(course.thumbUrl) .placeholder(R.drawable.stroked_course_image_placeholder) .transform(imageTransform) .into(courseImage) executePendingBindings() } } }
apache-2.0
49b7884c7876a1216ac88203cf496fcf
33.528736
102
0.705726
4.73817
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/ui/UIVerticalList.kt
1
4185
package com.soywiz.korge.ui import com.soywiz.kmem.* import com.soywiz.korge.annotations.* import com.soywiz.korge.render.* import com.soywiz.korge.view.* import com.soywiz.korma.geom.* @KorgeExperimental inline fun Container.uiVerticalList( provider: UIVerticalList.Provider, width: Double = 256.0, block: @ViewDslMarker Container.(UIVerticalList) -> Unit = {} ): UIVerticalList = UIVerticalList(provider, width) .addTo(this).also { block(it) } @KorgeExperimental open class UIVerticalList(provider: Provider, width: Double = 200.0) : UIView(width) { interface Provider { val numItems: Int val fixedHeight: Double? fun getItemY(index: Int): Double = (fixedHeight ?: 20.0) * index fun getItemHeight(index: Int): Double fun getItemView(index: Int): View } private var dirty = false private val viewsByIndex = LinkedHashMap<Int, View>() private val lastArea = Rectangle() private val lastPoint = Point() private val tempRect = Rectangle() private val tempPoint = Point() var provider: Provider = provider set(value) { field = value dirty = true updateList() } init { updateList() addUpdater { updateList() } } override fun renderInternal(ctx: RenderContext) { updateList() super.renderInternal(ctx) } private fun getIndexAtY(y: Double): Int { val index = y / (provider.fixedHeight?.toDouble() ?: 20.0) return index.toInt() } fun invalidateList() { dirty = true removeChildren() viewsByIndex.clear() updateList() } private val tempTransform = Matrix.Transform() fun updateList() { if (parent == null) return val area = getVisibleWindowArea(tempRect) val point = globalXY(tempPoint) val numItems = provider.numItems if (area != lastArea || point != lastPoint) { dirty = false lastArea.copyFrom(area) lastPoint.copyFrom(point) //val nheight = provider.fixedHeight?.toDouble() ?: 20.0 //val nItems = (area.height / nheight).toIntCeil() //println(nItems) //removeChildren() //val fromIndex = (startIndex).clamp(0, numItems - 1) //val toIndex = (startIndex + nItems).clamp(0, numItems - 1) //println("----") //println("point=$point") val transform = parent!!.globalMatrix.toTransform(tempTransform) //println("transform=${transform.scaleAvg}") val fromIndex = getIndexAtY((-point.y + tempRect.top) / transform.scaleY).clamp(0, numItems - 1) var toIndex = fromIndex for (index in fromIndex until numItems) { val view = viewsByIndex.getOrPut(index) { val itemHeight = provider.getItemHeight(index) provider.getItemView(index) .also { addChild(it) } .position(0.0, provider.getItemY(index)) .size(width, itemHeight.toDouble()) } toIndex = index //val localViewY = view.localToGlobalY(0.0, view.height) if (view.localToRenderY(0.0, view.height) >= area.bottom) { //println("localViewY=localViewY, globalY=${view.localToGlobalY(0.0, view.height)}") break } } //println("area=$area, point=$point, nItems=${toIndex - fromIndex}, fromIndex=$fromIndex, toIndex=$toIndex, globalBounds=${this.globalBounds}") val removeIndices = viewsByIndex.keys.filter { it !in fromIndex .. toIndex }.toSet() viewsByIndex.forEach { (index, view) -> if (index in removeIndices) { view.removeFromParent() } } for (index in removeIndices) viewsByIndex.remove(index) } setSize(width, provider.getItemY(numItems - 1) + provider.getItemHeight(numItems - 1)) //println("height=$height") } }
apache-2.0
35d665c586b0e5a720ad18571dab408c
33.02439
155
0.578495
4.524324
false
false
false
false
pr0ves/PokemonGoBot
src/main/kotlin/ink/abb/pogo/scraper/tasks/CatchOneNearbyPokemon.kt
2
9224
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.tasks import POGOProtos.Networking.Responses.CatchPokemonResponseOuterClass.CatchPokemonResponse import POGOProtos.Networking.Responses.DiskEncounterResponseOuterClass import POGOProtos.Networking.Responses.EncounterResponseOuterClass import POGOProtos.Networking.Responses.EncounterResponseOuterClass.EncounterResponse.Status import ink.abb.pogo.api.cache.MapPokemon import ink.abb.pogo.scraper.Bot import ink.abb.pogo.scraper.Context import ink.abb.pogo.scraper.Settings import ink.abb.pogo.scraper.Task import ink.abb.pogo.scraper.util.Log import ink.abb.pogo.scraper.util.directions.getAltitude import ink.abb.pogo.scraper.util.pokemon.* import java.util.concurrent.atomic.AtomicInteger class CatchOneNearbyPokemon : Task { override fun run(bot: Bot, ctx: Context, settings: Settings) { // STOP WALKING ctx.pauseWalking.set(true) val pokemon = ctx.api.map.getPokemon(ctx.api.latitude, ctx.api.longitude, settings.initialMapSize).filter { !ctx.blacklistedEncounters.contains(it.encounterId) && it.inRange } val hasPokeballs = ctx.api.inventory.hasPokeballs /*Pokeball.values().forEach { Log.yellow("${it.ballType}: ${ctx.api.cachedInventories.itemBag.getItem(it.ballType).count}") }*/ if (!hasPokeballs) { ctx.pauseWalking.set(false) return } if (pokemon.isNotEmpty()) { val catchablePokemon = pokemon.first() if (settings.obligatoryTransfer.contains(catchablePokemon.pokemonId) && settings.desiredCatchProbabilityUnwanted == -1.0 || settings.neverCatchPokemon.contains(catchablePokemon.pokemonId)) { ctx.blacklistedEncounters.add(catchablePokemon.encounterId) Log.normal("Found pokemon ${catchablePokemon.pokemonId}; blacklisting because it's unwanted") ctx.pauseWalking.set(false) return } Log.green("Found pokemon ${catchablePokemon.pokemonId}") ctx.api.setLocation(ctx.lat.get(), ctx.lng.get(), getAltitude(ctx.lat.get(), ctx.lng.get(), ctx)) val encounter = catchablePokemon.encounter() val encounterResult = encounter.toBlocking().first().response val wasFromLure = catchablePokemon.encounterKind == MapPokemon.EncounterKind.DISK if ((encounterResult is DiskEncounterResponseOuterClass.DiskEncounterResponse && encounterResult.result == DiskEncounterResponseOuterClass.DiskEncounterResponse.Result.SUCCESS) || (encounterResult is EncounterResponseOuterClass.EncounterResponse && encounterResult.status == Status.ENCOUNTER_SUCCESS)) { val pokemonData = if (encounterResult is DiskEncounterResponseOuterClass.DiskEncounterResponse) { encounterResult.pokemonData } else if (encounterResult is EncounterResponseOuterClass.EncounterResponse) { encounterResult.wildPokemon.pokemonData } else { // TODO ugly null }!! Log.green("Encountered pokemon ${catchablePokemon.pokemonId} " + "with CP ${pokemonData.cp} and IV ${pokemonData.getIvPercentage()}%") // TODO wrong parameters val (shouldRelease, reason) = pokemonData.shouldTransfer(settings, hashMapOf<String, Int>(), AtomicInteger(0)) val desiredCatchProbability = if (shouldRelease) { Log.yellow("Using desired_catch_probability_unwanted because $reason") settings.desiredCatchProbabilityUnwanted } else { settings.desiredCatchProbability } if (desiredCatchProbability == -1.0) { ctx.blacklistedEncounters.add(catchablePokemon.encounterId) Log.normal("CP/IV of encountered pokemon ${catchablePokemon.pokemonId} turns out to be too low; blacklisting encounter") ctx.pauseWalking.set(false) return } val isBallCurved = (Math.random() < settings.desiredCurveRate) val captureProbability = if (encounterResult is DiskEncounterResponseOuterClass.DiskEncounterResponse) { encounterResult.captureProbability } else if (encounterResult is EncounterResponseOuterClass.EncounterResponse) { encounterResult.captureProbability } else { // TODO ugly null }!! // TODO: Give settings object to the catch function instead of the seperate values val catch = catchablePokemon.catch( captureProbability, ctx.api.inventory, desiredCatchProbability, isBallCurved, !settings.neverUseBerries, settings.randomBallThrows, settings.waitBetweenThrows, -1) val catchResult = catch.toBlocking().first() if (catchResult == null) { // prevent trying it in the next iteration ctx.blacklistedEncounters.add(catchablePokemon.encounterId) Log.red("No Pokeballs in your inventory; blacklisting Pokemon") ctx.pauseWalking.set(false) return } val result = catchResult.response // TODO: temp fix for server timing issues regarding GetMapObjects ctx.blacklistedEncounters.add(catchablePokemon.encounterId) if (result.status == CatchPokemonResponse.CatchStatus.CATCH_SUCCESS) { ctx.pokemonStats.first.andIncrement if (wasFromLure) { ctx.luredPokemonStats.andIncrement } var message = "Caught a " if (settings.displayIfPokemonFromLure) { if (wasFromLure) message += "lured " else message += "wild " } message += "${catchablePokemon.pokemonId} with CP ${pokemonData.cp} and IV" + " (${pokemonData.individualAttack}-${pokemonData.individualDefense}-${pokemonData.individualStamina}) ${pokemonData.getIvPercentage()}%" if (settings.displayPokemonCatchRewards) { message += ": [${result.captureAward.xpList.sum()}x XP, ${result.captureAward.candyList.sum()}x " + "Candy, ${result.captureAward.stardustList.sum()}x Stardust]" } Log.cyan(message) ctx.server.newPokemon(catchablePokemon.latitude, catchablePokemon.longitude, pokemonData) ctx.server.sendProfile() } else { Log.red("Capture of ${catchablePokemon.pokemonId} failed with status : ${result.status}") if (result.status == CatchPokemonResponse.CatchStatus.CATCH_ERROR) { Log.red("Blacklisting pokemon to prevent infinite loop") } } } else { if (encounterResult is DiskEncounterResponseOuterClass.DiskEncounterResponse) { Log.red("Encounter failed with result: ${encounterResult.result}") if (encounterResult.result == DiskEncounterResponseOuterClass.DiskEncounterResponse.Result.ENCOUNTER_ALREADY_FINISHED) { ctx.blacklistedEncounters.add(catchablePokemon.encounterId) } } else if (encounterResult is EncounterResponseOuterClass.EncounterResponse) { Log.red("Encounter failed with result: ${encounterResult.status}") if (encounterResult.status == Status.ENCOUNTER_CLOSED) { ctx.blacklistedEncounters.add(catchablePokemon.encounterId) } } if ((encounterResult is DiskEncounterResponseOuterClass.DiskEncounterResponse && encounterResult.result == DiskEncounterResponseOuterClass.DiskEncounterResponse.Result.POKEMON_INVENTORY_FULL) || (encounterResult is EncounterResponseOuterClass.EncounterResponse && encounterResult.status == Status.POKEMON_INVENTORY_FULL)) { Log.red("Inventory is full, temporarily disabling catching of pokemon") ctx.pokemonInventoryFullStatus.set(true) } } ctx.pauseWalking.set(false) } } }
gpl-3.0
0b5f292368090349afecbc66e95db2fb
54.90303
210
0.610906
5.690315
false
false
false
false
cashapp/sqldelight
sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/lang/psi/StmtIdentifierMixin.kt
1
2359
package app.cash.sqldelight.core.lang.psi import app.cash.sqldelight.core.lang.SqlDelightQueriesFile import app.cash.sqldelight.core.psi.SqlDelightStmtIdentifier import app.cash.sqldelight.core.psi.SqlDelightStmtIdentifierClojure import com.alecstrong.sql.psi.core.SqlAnnotationHolder import com.alecstrong.sql.psi.core.SqlParser import com.alecstrong.sql.psi.core.SqlParserDefinition import com.alecstrong.sql.psi.core.psi.SqlAnnotatedElement import com.alecstrong.sql.psi.core.psi.SqlIdentifier import com.alecstrong.sql.psi.core.psi.SqlTypes import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.lang.LanguageParserDefinitions import com.intellij.lang.PsiBuilderFactory import com.intellij.lang.parser.GeneratedParserUtilBase import com.intellij.psi.PsiElement import com.intellij.psi.impl.GeneratedMarkerVisitor import com.intellij.psi.impl.source.tree.TreeElement abstract class StmtIdentifierMixin( node: ASTNode, ) : ASTWrapperPsiElement(node), SqlDelightStmtIdentifier, SqlDelightStmtIdentifierClojure, SqlAnnotatedElement { override fun getName() = identifier()?.text override fun setName(name: String): PsiElement { val parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(language) as SqlParserDefinition var builder = PsiBuilderFactory.getInstance().createBuilder( project, node, parserDefinition.createLexer(project), language, name, ) builder = GeneratedParserUtilBase.adapt_builder_( SqlTypes.IDENTIFIER, builder, SqlParser(), SqlParser.EXTENDS_SETS_, ) GeneratedParserUtilBase.ErrorState.get(builder).currentFrame = GeneratedParserUtilBase.Frame() SqlParser.identifier_real(builder, 0) val element = builder.treeBuilt (element as TreeElement).acceptTree(GeneratedMarkerVisitor()) node.replaceChild(identifier()!!.node, element) return this } override fun annotate(annotationHolder: SqlAnnotationHolder) { if (name != null && (containingFile as SqlDelightQueriesFile).sqlStatements() .filterNot { it.identifier == this } .any { it.identifier.name == name } ) { annotationHolder.createErrorAnnotation(this, "Duplicate SQL identifier") } } override fun identifier() = children.filterIsInstance<SqlIdentifier>().singleOrNull() }
apache-2.0
5c8b8b0086234b8ae804b4d7f8f32c66
36.444444
106
0.780839
4.580583
false
false
false
false
edvin/tornadofx
src/main/java/tornadofx/VectorMath.kt
1
6234
package tornadofx import javafx.geometry.Point2D import javafx.geometry.Point3D typealias Vector2D = Point2D fun Point2D(value: Double): Point2D = Point2D(value, value) fun Vector2D(value: Double): Vector2D = Vector2D(value, value) operator fun Point2D.plus(other: Point2D): Point2D = this.add(other) operator fun Point2D.plus(value: Double): Point2D = this.add(value, value) operator fun Double.plus(point: Point2D): Point2D = point.add(this, this) operator fun Point2D.minus(other: Point2D): Point2D = this.subtract(other) operator fun Point2D.minus(value: Double): Point2D = this.subtract(value, value) operator fun Point2D.times(factor: Double): Point2D = this.multiply(factor) operator fun Double.times(point: Point2D): Point2D = point.multiply(this) operator fun Point2D.div(divisor: Double): Point2D = this.multiply(1.0 / divisor) operator fun Point2D.unaryMinus(): Point2D = this.multiply(-1.0) infix fun Point2D.dot(other: Point2D): Double = this.dotProduct(other) infix fun Point2D.cross(other: Point2D): Point3D = this.crossProduct(other) infix fun Point2D.angle(other: Point2D): Double = this.angle(other) infix fun Point2D.distance(other: Point2D): Double = this.distance(other) infix fun Point2D.midPoint(other: Point2D): Point2D = this.midpoint(other) /** * Returns the squared length of the vector/point. */ fun Point2D.magnitude2(): Double = this.x * this.x + this.y * this.y typealias Vector3D = Point3D fun Point3D(value: Double): Point3D = Point3D(value, value, value) fun Point3D(point: Point2D, z: Double): Point3D = Point3D(point.x, point.y, z) fun Point3D(x: Double, point: Point2D): Point3D = Point3D(x, point.x, point.y) fun Vector3D(value: Double): Vector3D = Vector3D(value, value, value) fun Vector3D(point: Point2D, z: Double): Vector3D = Vector3D(point.x, point.y, z) fun Vector3D(x: Double, point: Point2D): Vector3D = Vector3D(x, point.x, point.y) operator fun Point3D.plus(other: Point3D): Point3D = this.add(other) operator fun Point3D.plus(value: Double): Point3D = this.add(value, value, value) operator fun Double.plus(point: Point3D): Point3D = point.add(this, this, this) operator fun Point3D.minus(other: Point3D): Point3D = this.subtract(other) operator fun Point3D.minus(value: Double): Point3D = this.subtract(value, value, value) operator fun Point3D.times(factor: Double): Point3D = this.multiply(factor) operator fun Double.times(point: Point3D): Point3D = point.multiply(this) operator fun Point3D.div(divisor: Double): Point3D = this.multiply(1.0 / divisor) operator fun Point3D.unaryMinus(): Point3D = this.multiply(-1.0) infix fun Point3D.dot(other: Point3D): Double = this.dotProduct(other) infix fun Point3D.cross(other: Point3D): Point3D = this.crossProduct(other) infix fun Point3D.angle(other: Point3D): Double = this.angle(other) infix fun Point3D.distance(other: Point3D): Double = this.distance(other) infix fun Point3D.midPoint(other: Point3D): Point3D = this.midpoint(other) /** * Returns the squared length of the vector/point. */ fun Point3D.magnitude2(): Double = this.x * this.x + this.y * this.y + this.z * this.z // All them swizzles... :P val Point2D.xx: Point2D get() = Point2D(this.x, this.x) val Point2D.xy: Point2D get() = Point2D(this.x, this.y) val Point2D.yx: Point2D get() = Point2D(this.y, this.x) val Point2D.yy: Point2D get() = Point2D(this.y, this.y) val Point2D.xxx: Point3D get() = Point3D(this.x, this.x, this.x) val Point2D.xxy: Point3D get() = Point3D(this.x, this.x, this.y) val Point2D.xyx: Point3D get() = Point3D(this.x, this.y, this.x) val Point2D.xyy: Point3D get() = Point3D(this.x, this.y, this.y) val Point2D.yxx: Point3D get() = Point3D(this.y, this.x, this.x) val Point2D.yxy: Point3D get() = Point3D(this.y, this.x, this.y) val Point2D.yyx: Point3D get() = Point3D(this.y, this.y, this.x) val Point2D.yyy: Point3D get() = Point3D(this.y, this.y, this.y) val Point3D.xx: Point2D get() = Point2D(this.x, this.x) val Point3D.yx: Point2D get() = Point2D(this.y, this.x) val Point3D.zx: Point2D get() = Point2D(this.z, this.x) val Point3D.xy: Point2D get() = Point2D(this.x, this.y) val Point3D.yy: Point2D get() = Point2D(this.y, this.y) val Point3D.zy: Point2D get() = Point2D(this.z, this.y) val Point3D.xz: Point2D get() = Point2D(this.x, this.z) val Point3D.yz: Point2D get() = Point2D(this.y, this.z) val Point3D.zz: Point2D get() = Point2D(this.z, this.z) val Point3D.xxx: Point3D get() = Point3D(this.x, this.x, this.x) val Point3D.yxx: Point3D get() = Point3D(this.y, this.x, this.x) val Point3D.zxx: Point3D get() = Point3D(this.z, this.x, this.x) val Point3D.xyx: Point3D get() = Point3D(this.x, this.y, this.x) val Point3D.yyx: Point3D get() = Point3D(this.y, this.y, this.x) val Point3D.zyx: Point3D get() = Point3D(this.z, this.y, this.x) val Point3D.xzx: Point3D get() = Point3D(this.x, this.z, this.x) val Point3D.yzx: Point3D get() = Point3D(this.y, this.z, this.x) val Point3D.zzx: Point3D get() = Point3D(this.z, this.z, this.x) val Point3D.xxy: Point3D get() = Point3D(this.x, this.x, this.y) val Point3D.yxy: Point3D get() = Point3D(this.y, this.x, this.y) val Point3D.zxy: Point3D get() = Point3D(this.z, this.x, this.y) val Point3D.xyy: Point3D get() = Point3D(this.x, this.y, this.y) val Point3D.yyy: Point3D get() = Point3D(this.y, this.y, this.y) val Point3D.zyy: Point3D get() = Point3D(this.z, this.y, this.y) val Point3D.xzy: Point3D get() = Point3D(this.x, this.z, this.y) val Point3D.yzy: Point3D get() = Point3D(this.y, this.z, this.y) val Point3D.zzy: Point3D get() = Point3D(this.z, this.z, this.y) val Point3D.xxz: Point3D get() = Point3D(this.x, this.x, this.z) val Point3D.yxz: Point3D get() = Point3D(this.y, this.x, this.z) val Point3D.zxz: Point3D get() = Point3D(this.z, this.x, this.z) val Point3D.xyz: Point3D get() = Point3D(this.x, this.y, this.z) val Point3D.yyz: Point3D get() = Point3D(this.y, this.y, this.z) val Point3D.zyz: Point3D get() = Point3D(this.z, this.y, this.z) val Point3D.xzz: Point3D get() = Point3D(this.x, this.z, this.z) val Point3D.yzz: Point3D get() = Point3D(this.y, this.z, this.z) val Point3D.zzz: Point3D get() = Point3D(this.z, this.z, this.z)
apache-2.0
d7f12e0dd0dfd415a3fbfc02e06fb343
27.59633
87
0.711902
2.373953
false
false
false
false
panpf/sketch
sample/src/main/java/com/github/panpf/sketch/sample/ui/photo/pexels/PhotoList.kt
1
7264
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.sample.ui.photo.pexels import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.unit.dp import androidx.paging.LoadState import androidx.paging.PagingData import androidx.paging.compose.collectAsLazyPagingItems import com.github.panpf.sketch.request.DisplayRequest import com.github.panpf.sketch.request.PauseLoadWhenScrollingDrawableDecodeInterceptor import com.github.panpf.sketch.sample.R import com.github.panpf.sketch.sample.R.color import com.github.panpf.sketch.sample.R.drawable import com.github.panpf.sketch.sample.image.ImageType.LIST import com.github.panpf.sketch.sample.image.setApplySettings import com.github.panpf.sketch.sample.model.Photo import com.github.panpf.sketch.sample.ui.common.compose.AppendState import com.github.panpf.sketch.stateimage.IconStateImage import com.github.panpf.sketch.stateimage.ResColor import com.github.panpf.sketch.stateimage.saveCellularTrafficError import com.github.panpf.tools4a.toast.ktx.showLongToast import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.SwipeRefreshState import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch @Composable fun PhotoListContent( photoPagingFlow: Flow<PagingData<Photo>>, restartImageFlow: Flow<Any>, reloadFlow: Flow<Any>, onClick: (items: List<Photo>, photo: Photo, index: Int) -> Unit ) { val lazyPagingItems = photoPagingFlow.collectAsLazyPagingItems() val scope = rememberCoroutineScope() LaunchedEffect(key1 = reloadFlow) { scope.launch { reloadFlow.collect { lazyPagingItems.refresh() } } } val context = LocalContext.current LaunchedEffect(key1 = reloadFlow) { scope.launch { restartImageFlow.collect { // todo Look for ways to actively discard the old state redraw, and then listen for restartImageFlow to perform the redraw context.showLongToast("You need to scroll through the list manually to see the changes") } } } SwipeRefresh( state = SwipeRefreshState(lazyPagingItems.loadState.refresh is LoadState.Loading), onRefresh = { lazyPagingItems.refresh() } ) { val lazyGridState = rememberLazyGridState() if (lazyGridState.isScrollInProgress) { DisposableEffect(Unit) { PauseLoadWhenScrollingDrawableDecodeInterceptor.scrolling = true onDispose { PauseLoadWhenScrollingDrawableDecodeInterceptor.scrolling = false } } } LazyVerticalGrid( columns = GridCells.Adaptive(minSize = 100.dp), state = lazyGridState, contentPadding = PaddingValues(dimensionResource(id = R.dimen.grid_divider)), horizontalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.grid_divider)), verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.grid_divider)), ) { items( count = lazyPagingItems.itemCount, key = { lazyPagingItems.peek(it)?.diffKey ?: "" }, contentType = { 1 } ) { index -> val item = lazyPagingItems[index] item?.let { PhotoContent(index, it) { photo, index -> onClick(lazyPagingItems.itemSnapshotList.items, photo, index) } } } if (lazyPagingItems.itemCount > 0) { item( key = "AppendState", span = { GridItemSpan(this.maxLineSpan) }, contentType = 2 ) { AppendState(lazyPagingItems.loadState.append) { lazyPagingItems.retry() } } } } } } @Composable fun PhotoContent( index: Int, photo: Photo, onClick: (photo: Photo, index: Int) -> Unit ) { val modifier = Modifier .fillMaxWidth() .aspectRatio(1f) .clickable { onClick(photo, index) } val configBlock: (DisplayRequest.Builder.() -> Unit) = { setApplySettings(LIST) placeholder(IconStateImage(drawable.ic_image_outline, ResColor(color.placeholder_bg))) error(IconStateImage(drawable.ic_error, ResColor(color.placeholder_bg))) { saveCellularTrafficError( IconStateImage(drawable.ic_signal_cellular, ResColor(color.placeholder_bg)) ) } crossfade() resizeApplyToDrawable() } when (index % 3) { 0 -> { com.github.panpf.sketch.compose.AsyncImage( imageUri = photo.listThumbnailUrl, modifier = modifier, contentScale = ContentScale.Crop, contentDescription = "", configBlock = configBlock ) } 1 -> { com.github.panpf.sketch.compose.SubcomposeAsyncImage( imageUri = photo.listThumbnailUrl, modifier = modifier, contentScale = ContentScale.Crop, contentDescription = "", configBlock = configBlock ) } else -> { Image( painter = com.github.panpf.sketch.compose.rememberAsyncImagePainter( imageUri = photo.listThumbnailUrl, configBlock = configBlock ), modifier = modifier, contentScale = ContentScale.Crop, contentDescription = "" ) } } }
apache-2.0
c75a2b34859763dc707bf68477b44f74
38.05914
138
0.655011
4.934783
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/DirectMessageOnLinkClickHandler.kt
1
2646
/* * 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.content.Context import android.content.SharedPreferences import android.net.Uri import android.os.Bundle import android.support.v4.app.FragmentActivity import org.mariotaku.kpreferences.get import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_URI import de.vanita5.twittnuker.constant.phishingLinksWaringKey import de.vanita5.twittnuker.fragment.PhishingLinkWarningDialogFragment import de.vanita5.twittnuker.model.UserKey class DirectMessageOnLinkClickHandler( context: Context, manager: MultiSelectManager?, preferences: SharedPreferences ) : OnLinkClickHandler(context, manager, preferences) { override fun openLink(accountKey: UserKey?, link: String) { if (manager != null && manager.isActive) return if (!hasShortenedLinks(link)) { super.openLink(accountKey, link) return } if (context is FragmentActivity && preferences[phishingLinksWaringKey]) { val fm = context.supportFragmentManager val fragment = PhishingLinkWarningDialogFragment() val args = Bundle() args.putParcelable(EXTRA_URI, Uri.parse(link)) fragment.arguments = args fragment.show(fm, "phishing_link_warning") } else { super.openLink(accountKey, link) } } private fun hasShortenedLinks(link: String): Boolean { for (shortLinkService in SHORT_LINK_SERVICES) { if (link.contains(shortLinkService)) return true } return false } companion object { private val SHORT_LINK_SERVICES = arrayOf("bit.ly", "ow.ly", "tinyurl.com", "goo.gl", "k6.kz", "is.gd", "tr.im", "x.co", "weepp.ru") } }
gpl-3.0
de239aeebca52fc821229ef9f6ce9504
35.763889
140
0.702192
4.254019
false
false
false
false
Cleverdesk/cleverdesk
src/main/java/net/cleverdesk/cleverdesk/Configuration.kt
1
2189
/** * 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 net.cleverdesk.cleverdesk import net.cleverdesk.cleverdesk.database.DatabaseObject import net.cleverdesk.cleverdesk.plugin.Page import net.cleverdesk.cleverdesk.plugin.Plugin import net.cleverdesk.cleverdesk.plugin.Response import net.cleverdesk.cleverdesk.ui.Alert import net.cleverdesk.cleverdesk.ui.UI import net.cleverdesk.cleverdesk.ui.form.InputField /** * Created by schulerlabor on 22.06.16. */ public open class Configuration(override val plugin: Plugin, override val name: String) : DatabaseObject(), Page { public fun refreshContent() { plugin.database?.download(this, this) plugin.database?.upload(this) } @Database public var content: MutableMap<String, String?> = mutableMapOf() @Database public var identifer: String = name override val indices: Map<String, Any?>? get() = mutableMapOf(Pair("identifer", identifer)) override fun response(user: User?, request: UIRequest): Response { if (request.attributes.size > 0) { refreshContent() content.putAll(request.attributes as Map<out String, String?>) plugin.database?.upload(this) refreshContent() return Alert("Saved") } refreshContent() val ui = UI() for (key in content.keys) { val field = InputField() field.label = key field.value = content.get(key) field.identifer = key ui.addComponent(field) } return ui } }
gpl-3.0
e1fddeb5ba3345367724b4f174b82972
31.205882
114
0.68159
4.360558
false
false
false
false
AndroidX/androidx
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/window/DialogScreenshotTest.kt
3
3280
/* * 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.ui.window import android.os.Build import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.testutils.assertAgainstGolden import androidx.compose.ui.GOLDEN_UI import androidx.compose.ui.Modifier import androidx.compose.ui.background import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.isDialog import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.filters.SdkSuppress import androidx.test.screenshot.AndroidXScreenshotTestRule import androidx.test.screenshot.matchers.MSSIMMatcher import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) class DialogScreenshotTest { @get:Rule val rule = createComposeRule() @get:Rule val screenshotRule = AndroidXScreenshotTestRule(GOLDEN_UI) @Test fun dialogWithNoElevation() { rule.setContent { Dialog(onDismissRequest = {}) { Box( Modifier .graphicsLayer(shape = RoundedCornerShape(percent = 15), clip = true) .size(200.dp) .background(Color(0xFFA896B0)) ) } } rule.onNode(isDialog()) .captureToImage() .assertAgainstGolden(screenshotRule, "dialogWithNoElevation") } @Test fun dialogWithElevation() { rule.setContent { Dialog(onDismissRequest = {}) { val elevation = with(LocalDensity.current) { 8.dp.toPx() } Box( Modifier .graphicsLayer( shadowElevation = elevation, shape = RoundedCornerShape(percent = 15), clip = true ) .size(200.dp) .background(Color(0xFFA896B0)) ) } } rule.onNode(isDialog()) .captureToImage() .assertAgainstGolden( screenshotRule, "dialogWithElevation", matcher = MSSIMMatcher(threshold = 0.999) ) } }
apache-2.0
53b4eb08a2f3d67dacea4d073001c3f0
32.814433
93
0.647561
4.837758
false
true
false
false
AndroidX/androidx
privacysandbox/tools/tools-apicompiler/src/test/test-data/fullfeaturedsdk/output/com/mysdk/MySecondInterfaceStubDelegate.kt
3
6171
package com.mysdk import com.mysdk.PrivacySandboxThrowableParcelConverter import com.mysdk.PrivacySandboxThrowableParcelConverter.toThrowableParcel import com.mysdk.RequestConverter.fromParcelable import com.mysdk.ResponseConverter.toParcelable import kotlin.Array import kotlin.BooleanArray import kotlin.CharArray import kotlin.DoubleArray import kotlin.FloatArray import kotlin.IntArray import kotlin.LongArray import kotlin.String import kotlin.Unit import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch public class MySecondInterfaceStubDelegate internal constructor( public val `delegate`: MySecondInterface, ) : IMySecondInterface.Stub() { public override fun doIntStuff(x: IntArray, transactionCallback: IListIntTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doIntStuff(x.toList()) transactionCallback.onSuccess(result.toIntArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doCharStuff(x: CharArray, transactionCallback: IListCharTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doCharStuff(x.toList()) transactionCallback.onSuccess(result.toCharArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doFloatStuff(x: FloatArray, transactionCallback: IListFloatTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doFloatStuff(x.toList()) transactionCallback.onSuccess(result.toFloatArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doLongStuff(x: LongArray, transactionCallback: IListLongTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doLongStuff(x.toList()) transactionCallback.onSuccess(result.toLongArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doDoubleStuff(x: DoubleArray, transactionCallback: IListDoubleTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doDoubleStuff(x.toList()) transactionCallback.onSuccess(result.toDoubleArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doBooleanStuff(x: BooleanArray, transactionCallback: IListBooleanTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doBooleanStuff(x.toList()) transactionCallback.onSuccess(result.toBooleanArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doShortStuff(x: IntArray, transactionCallback: IListShortTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doShortStuff(x.map { it.toShort() }.toList()) transactionCallback.onSuccess(result.map { it.toInt() }.toIntArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doStringStuff(x: Array<String>, transactionCallback: IListStringTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doStringStuff(x.toList()) transactionCallback.onSuccess(result.toTypedArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } public override fun doValueStuff(x: Array<ParcelableRequest>, transactionCallback: IListResponseTransactionCallback): Unit { @OptIn(DelicateCoroutinesApi::class) val job = GlobalScope.launch(Dispatchers.Main) { try { val result = delegate.doValueStuff(x.map { fromParcelable(it) }.toList()) transactionCallback.onSuccess(result.map { toParcelable(it) }.toTypedArray()) } catch (t: Throwable) { transactionCallback.onFailure(toThrowableParcel(t)) } } val cancellationSignal = TransportCancellationCallback() { job.cancel() } transactionCallback.onCancellable(cancellationSignal) } }
apache-2.0
a030e37796f4e2fa0675e648031581c1
35.952096
100
0.724842
5.172674
false
false
false
false
AndroidX/androidx
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/MappedInteractionSource.kt
3
2445
/* * 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 * * 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.material3 import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.ui.geometry.Offset import kotlinx.coroutines.flow.map /** * Adapts an [InteractionSource] from one component to another by mapping any interactions by a * given offset. Namely used for the pill indicator in [NavigationBarItem] and [NavigationRailItem]. */ internal class MappedInteractionSource( underlyingInteractionSource: InteractionSource, private val delta: Offset ) : InteractionSource { private val mappedPresses = mutableMapOf<PressInteraction.Press, PressInteraction.Press>() override val interactions = underlyingInteractionSource.interactions.map { interaction -> when (interaction) { is PressInteraction.Press -> { val mappedPress = mapPress(interaction) mappedPresses[interaction] = mappedPress mappedPress } is PressInteraction.Cancel -> { val mappedPress = mappedPresses.remove(interaction.press) if (mappedPress == null) { interaction } else { PressInteraction.Cancel(mappedPress) } } is PressInteraction.Release -> { val mappedPress = mappedPresses.remove(interaction.press) if (mappedPress == null) { interaction } else { PressInteraction.Release(mappedPress) } } else -> interaction } } private fun mapPress(press: PressInteraction.Press): PressInteraction.Press = PressInteraction.Press(press.pressPosition - delta) }
apache-2.0
959c22e9087a2cc7b07e59b7438e2d4a
37.21875
100
0.661759
5.280778
false
false
false
false
exponent/exponent
android/expoview/src/main/java/host/exp/exponent/RNObject.kt
2
10144
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent import host.exp.exponent.analytics.EXL import host.exp.expoview.BuildConfig import java.lang.reflect.Constructor import java.lang.reflect.Field import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method // TODO: add type checking in DEBUG class RNObject { private val className: String // Unversioned private var clazz: Class<*>? = null // Versioned private var instance: Any? = null // Versioned // We ignore the version of clazz constructor(clazz: Class<*>?) { className = removeVersionFromClass(clazz) } constructor(className: String) { this.className = className } private constructor(obj: Any?) { assign(obj) className = removeVersionFromClass(clazz) } val isNull: Boolean get() = instance == null val isNotNull: Boolean get() = instance != null // required for "unversioned" flavor check fun loadVersion(version: String): RNObject { try { clazz = if (version == UNVERSIONED || BuildConfig.FLAVOR == "unversioned") { if (className.startsWith("host.exp.exponent")) { Class.forName("versioned.$className") } else { Class.forName(className) } } else { Class.forName("abi${version.replace('.', '_')}.$className") } } catch (e: ClassNotFoundException) { EXL.e(TAG, e) } return this } fun assign(obj: Any?) { if (obj != null) { clazz = obj.javaClass } instance = obj } fun get(): Any? { return instance } fun rnClass(): Class<*>? { return clazz } fun version(): String { return versionForClassname(clazz!!.name) } fun construct(vararg args: Any?): RNObject { try { instance = getConstructorWithArgumentClassTypes(clazz, *objectsToJavaClassTypes(*args)).newInstance(*args) } catch (e: NoSuchMethodException) { EXL.e(TAG, e) } catch (e: InvocationTargetException) { EXL.e(TAG, e) } catch (e: InstantiationException) { EXL.e(TAG, e) } catch (e: IllegalAccessException) { EXL.e(TAG, e) } return this } fun call(name: String, vararg args: Any?): Any? { return callWithReceiver(instance, name, *args) } fun callRecursive(name: String, vararg args: Any?): RNObject? { val result = call(name, *args) ?: return null return wrap(result) } fun callStatic(name: String, vararg args: Any?): Any? { return callWithReceiver(null, name, *args) } fun callStaticRecursive(name: String, vararg args: Any?): RNObject? { val result = callStatic(name, *args) ?: return null return wrap(result) } fun setField(name: String, value: Any) { setFieldWithReceiver(instance, name, value) } fun setStaticField(name: String, value: Any) { setFieldWithReceiver(null, name, value) } private fun callWithReceiver(receiver: Any?, name: String, vararg args: Any?): Any? { try { return getMethodWithArgumentClassTypes(clazz, name, *objectsToJavaClassTypes(*args)).invoke(receiver, *args) } catch (e: IllegalAccessException) { EXL.e(TAG, e) e.printStackTrace() } catch (e: InvocationTargetException) { EXL.e(TAG, e) e.printStackTrace() } catch (e: NoSuchMethodException) { EXL.e(TAG, e) e.printStackTrace() } catch (e: NoSuchMethodError) { EXL.e(TAG, e) e.printStackTrace() } catch (e: Throwable) { EXL.e(TAG, "Runtime exception in RNObject when calling method $name: $e") } return null } private fun setFieldWithReceiver(receiver: Any?, name: String, value: Any) { try { getFieldWithType(clazz, name, value.javaClass)[receiver] = value } catch (e: IllegalAccessException) { EXL.e(TAG, e) e.printStackTrace() } catch (e: NoSuchFieldException) { EXL.e(TAG, e) e.printStackTrace() } catch (e: NoSuchMethodError) { EXL.e(TAG, e) e.printStackTrace() } catch (e: Throwable) { EXL.e(TAG, "Runtime exception in RNObject when setting field $name: $e") } } fun onHostResume(one: Any?, two: Any?) { call("onHostResume", one, two) } fun onHostPause() { call("onHostPause") } fun onHostDestroy() { call("onHostDestroy") } companion object { private val TAG = RNObject::class.java.simpleName const val UNVERSIONED = "UNVERSIONED" @JvmStatic fun wrap(obj: Any): RNObject { return RNObject(obj) } fun versionedEnum(sdkVersion: String, className: String, value: String): Any { return try { RNObject(className).loadVersion(sdkVersion).rnClass()!!.getDeclaredField(value)[null] } catch (e: IllegalAccessException) { EXL.e(TAG, e) throw IllegalStateException("Unable to create enum: $className.value", e) } catch (e: NoSuchFieldException) { EXL.e(TAG, e) throw IllegalStateException("Unable to create enum: $className.value", e) } } fun versionForClassname(classname: String): String { return if (classname.startsWith("abi")) { val abiVersion = classname.split(".").toTypedArray()[0] abiVersion.substring(3) } else { UNVERSIONED } } private fun removeVersionFromClass(clazz: Class<*>?): String { val name = clazz!!.name return if (name.startsWith("abi")) { name.substring(name.indexOf('.') + 1) } else name } private fun objectsToJavaClassTypes(vararg objects: Any?): Array<Class<*>?> { val classes: Array<Class<*>?> = arrayOfNulls(objects.size) for (i in objects.indices) { if (objects[i] != null) { classes[i] = objects[i]!!::class.java } } return classes } // Allow types that are too specific so that we don't have to specify exact classes @Throws(NoSuchMethodException::class) private fun getMethodWithArgumentClassTypes(clazz: Class<*>?, name: String, vararg argumentClassTypes: Class<*>?): Method { val methods = clazz!!.methods for (i in methods.indices) { val method = methods[i] if (method.name != name) { continue } val currentMethodParameterTypes = method.parameterTypes if (currentMethodParameterTypes.size != argumentClassTypes.size) { continue } var isValid = true for (j in currentMethodParameterTypes.indices) { if (!isAssignableFrom(currentMethodParameterTypes[j], argumentClassTypes[j])) { isValid = false break } } if (!isValid) { continue } return method } throw NoSuchMethodException() } // Allow boxed -> unboxed assignments private fun isAssignableFrom(methodParameterClassType: Class<*>, argumentClassType: Class<*>?): Boolean { if (argumentClassType == null) { // There's not really a good way to handle this. return true } if (methodParameterClassType.isAssignableFrom(argumentClassType)) { return true } if (methodParameterClassType == Boolean::class.javaPrimitiveType && (argumentClassType == java.lang.Boolean::class.java || argumentClassType == Boolean::class.java)) { return true } else if (methodParameterClassType == Byte::class.javaPrimitiveType && (argumentClassType == java.lang.Byte::class.java || argumentClassType == Byte::class.java)) { return true } else if (methodParameterClassType == Char::class.javaPrimitiveType && (argumentClassType == java.lang.Character::class.java || argumentClassType == Char::class.java)) { return true } else if (methodParameterClassType == Float::class.javaPrimitiveType && (argumentClassType == java.lang.Float::class.java || argumentClassType == Float::class.java)) { return true } else if (methodParameterClassType == Int::class.javaPrimitiveType && (argumentClassType == java.lang.Integer::class.java || argumentClassType == Int::class.java)) { return true } else if (methodParameterClassType == Long::class.javaPrimitiveType && (argumentClassType == java.lang.Long::class.java || argumentClassType == Long::class.java)) { return true } else if (methodParameterClassType == Short::class.javaPrimitiveType && (argumentClassType == java.lang.Short::class.java || argumentClassType == Short::class.java)) { return true } else if (methodParameterClassType == Double::class.javaPrimitiveType && (argumentClassType == java.lang.Double::class.java || argumentClassType == Double::class.java)) { return true } return false } // Allow types that are too specific so that we don't have to specify exact classes @Throws(NoSuchMethodException::class) private fun getConstructorWithArgumentClassTypes(clazz: Class<*>?, vararg argumentClassTypes: Class<*>?): Constructor<*> { val constructors = clazz!!.constructors for (i in constructors.indices) { val constructor = constructors[i] val currentConstructorParameterTypes = constructor.parameterTypes if (currentConstructorParameterTypes.size != argumentClassTypes.size) { continue } var isValid = true for (j in currentConstructorParameterTypes.indices) { if (!isAssignableFrom(currentConstructorParameterTypes[j], argumentClassTypes[j])) { isValid = false break } } if (!isValid) { continue } return constructor } throw NoSuchMethodError() } @Throws(NoSuchFieldException::class) private fun getFieldWithType(clazz: Class<*>?, name: String, type: Class<*>): Field { val fields = clazz!!.fields for (i in fields.indices) { val field = fields[i] if (field.name != name) { continue } val currentFieldType = field.type if (isAssignableFrom(currentFieldType, type)) { return field } } throw NoSuchFieldException() } } }
bsd-3-clause
733dc7527717d6ed6000025c67da1ab1
31.828479
177
0.639787
4.508444
false
false
false
false
googlemaps/android-maps-compose
maps-compose-widgets/src/main/java/com/google/maps/android/compose/widgets/ScaleBar.kt
1
10348
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.maps.android.compose.widgets import android.graphics.Point import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.EnterTransition import androidx.compose.animation.ExitTransition import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment.Companion.End import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.google.android.gms.maps.model.LatLng import com.google.maps.android.compose.CameraPositionState import com.google.maps.android.ktx.utils.sphericalDistance import kotlinx.coroutines.delay public val DarkGray: Color = Color(0xFF3a3c3b) private val defaultWidth: Dp = 65.dp private val defaultHeight: Dp = 50.dp /** * A scale bar composable that shows the current scale of the map in feet and meters when zoomed in * to the map, changing to miles and kilometers, respectively, when zooming out. * * Implement your own observer on camera move events using [CameraPositionState] and pass it in * as [cameraPositionState]. */ @Composable public fun ScaleBar( modifier: Modifier = Modifier, width: Dp = defaultWidth, height: Dp = defaultHeight, cameraPositionState: CameraPositionState, textColor: Color = DarkGray, lineColor: Color = DarkGray, shadowColor: Color = Color.White, ) { Box( modifier = modifier .size(width = width, height = height) ) { var horizontalLineWidthMeters by remember { mutableStateOf(0) } Canvas( modifier = Modifier.fillMaxSize(), onDraw = { // Get width of canvas in meters val upperLeftLatLng = cameraPositionState.projection?.fromScreenLocation(Point(0, 0)) ?: LatLng(0.0, 0.0) val upperRightLatLng = cameraPositionState.projection?.fromScreenLocation(Point(0, size.width.toInt())) ?: LatLng(0.0, 0.0) val canvasWidthMeters = upperLeftLatLng.sphericalDistance(upperRightLatLng) val eightNinthsCanvasMeters = (canvasWidthMeters * 8 / 9).toInt() horizontalLineWidthMeters = eightNinthsCanvasMeters val oneNinthWidth = size.width / 9 val midHeight = size.height / 2 val oneThirdHeight = size.height / 3 val twoThirdsHeight = size.height * 2 / 3 val strokeWidth = 4f val shadowStrokeWidth = strokeWidth + 3 // Middle horizontal line shadow (drawn under main lines) drawLine( color = shadowColor, start = Offset(oneNinthWidth, midHeight), end = Offset(size.width, midHeight), strokeWidth = shadowStrokeWidth, cap = StrokeCap.Round ) // Top vertical line shadow (drawn under main lines) drawLine( color = shadowColor, start = Offset(oneNinthWidth, oneThirdHeight), end = Offset(oneNinthWidth, midHeight), strokeWidth = shadowStrokeWidth, cap = StrokeCap.Round ) // Bottom vertical line shadow (drawn under main lines) drawLine( color = shadowColor, start = Offset(oneNinthWidth, midHeight), end = Offset(oneNinthWidth, twoThirdsHeight), strokeWidth = shadowStrokeWidth, cap = StrokeCap.Round ) // Middle horizontal line drawLine( color = lineColor, start = Offset(oneNinthWidth, midHeight), end = Offset(size.width, midHeight), strokeWidth = strokeWidth, cap = StrokeCap.Round ) // Top vertical line drawLine( color = lineColor, start = Offset(oneNinthWidth, oneThirdHeight), end = Offset(oneNinthWidth, midHeight), strokeWidth = strokeWidth, cap = StrokeCap.Round ) // Bottom vertical line drawLine( color = lineColor, start = Offset(oneNinthWidth, midHeight), end = Offset(oneNinthWidth, twoThirdsHeight), strokeWidth = strokeWidth, cap = StrokeCap.Round ) } ) Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.SpaceAround ) { var metricUnits = "m" var metricDistance = horizontalLineWidthMeters if (horizontalLineWidthMeters > METERS_IN_KILOMETER) { // Switch from meters to kilometers as unit metricUnits = "km" metricDistance /= METERS_IN_KILOMETER.toInt() } var imperialUnits = "ft" var imperialDistance = horizontalLineWidthMeters.toDouble().toFeet() if (imperialDistance > FEET_IN_MILE) { // Switch from ft to miles as unit imperialUnits = "mi" imperialDistance = imperialDistance.toMiles() } ScaleText( modifier = Modifier.align(End), textColor = textColor, shadowColor = shadowColor, text = "${imperialDistance.toInt()} $imperialUnits" ) ScaleText( modifier = Modifier.align(End), textColor = textColor, shadowColor = shadowColor, text = "$metricDistance $metricUnits" ) } } } /** * An animated scale bar that appears when the zoom level of the map changes, and then disappears * after [visibilityDurationMillis]. This composable wraps [ScaleBar] with visibility animations. * * Implement your own observer on camera move events using [CameraPositionState] and pass it in * as [cameraPositionState]. */ @Composable public fun DisappearingScaleBar( modifier: Modifier = Modifier, width: Dp = defaultWidth, height: Dp = defaultHeight, cameraPositionState: CameraPositionState, textColor: Color = DarkGray, lineColor: Color = DarkGray, shadowColor: Color = Color.White, visibilityDurationMillis: Int = 3_000, enterTransition: EnterTransition = fadeIn(), exitTransition: ExitTransition = fadeOut(), ) { val visible = remember { MutableTransitionState(true) } LaunchedEffect(key1 = cameraPositionState.position.zoom) { // Show ScaleBar visible.targetState = true delay(visibilityDurationMillis.toLong()) // Hide ScaleBar after timeout period visible.targetState = false } AnimatedVisibility( visibleState = visible, modifier = modifier, enter = enterTransition, exit = exitTransition ) { ScaleBar( width = width, height = height, cameraPositionState = cameraPositionState, textColor = textColor, lineColor = lineColor, shadowColor = shadowColor ) } } @Composable private fun ScaleText( modifier: Modifier = Modifier, text: String, textColor: Color = DarkGray, shadowColor: Color = Color.White, ) { Text( text = text, fontSize = 12.sp, color = textColor, textAlign = TextAlign.End, modifier = modifier, style = MaterialTheme.typography.h4.copy( shadow = Shadow( color = shadowColor, offset = Offset(2f, 2f), blurRadius = 1f ) ) ) } /** * Converts [this] value in meters to the corresponding value in feet * @return [this] meters value converted to feet */ internal fun Double.toFeet(): Double { return this * CENTIMETERS_IN_METER / CENTIMETERS_IN_INCH / INCHES_IN_FOOT } /** * Converts [this] value in feet to the corresponding value in miles * @return [this] feet value converted to miles */ internal fun Double.toMiles(): Double { return this / FEET_IN_MILE } private const val CENTIMETERS_IN_METER: Double = 100.0 private const val METERS_IN_KILOMETER: Double = 1000.0 private const val CENTIMETERS_IN_INCH: Double = 2.54 private const val INCHES_IN_FOOT: Double = 12.0 private const val FEET_IN_MILE: Double = 5280.0
apache-2.0
ff76888933fbeda25acfb472a2e43573
35.568905
100
0.624275
5.035523
false
false
false
false
brianwernick/RecyclerExt
library/src/main/kotlin/com/devbrackets/android/recyclerext/adapter/HeaderListAdapter.kt
1
6224
/* * Copyright (C) 2016 - 2020 Brian Wernick * * 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.devbrackets.android.recyclerext.adapter import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.devbrackets.android.recyclerext.adapter.header.HeaderApi import com.devbrackets.android.recyclerext.adapter.header.HeaderCore import com.devbrackets.android.recyclerext.adapter.header.HeaderDataGenerator.HeaderData /** * A RecyclerView adapter that adds support for dynamically placing headers in the view. * * @param <H> The Header [ViewHolder] * @param <C> The Child or content [ViewHolder] */ abstract class HeaderListAdapter<T, H : ViewHolder, C : ViewHolder>( items: List<T> = emptyList() ) : ListAdapter<T, ViewHolder>(items), HeaderApi<H, C> { /** * Contains the base processing for the header adapters */ protected lateinit var core: HeaderCore /** * Initializes the non-super components for the Adapter */ protected fun init() { core = HeaderCore(this) } init { init() } /** * Called to display the header information with the `firstChildPosition` being the * position of the first child after this header. * * @param holder The ViewHolder which should be updated * @param firstChildPosition The position of the child immediately after this header */ abstract fun onBindHeaderViewHolder(holder: H, firstChildPosition: Int) /** * Called to display the child information with the `childPosition` being the * position of the child, excluding headers. * * @param holder The ViewHolder which should be updated * @param childPosition The position of the child */ abstract fun onBindChildViewHolder(holder: C, childPosition: Int) /** * This method shouldn't be used directly, instead use * [onCreateHeaderViewHolder] and * [onCreateChildViewHolder] * * @param parent The parent ViewGroup for the ViewHolder * @param viewType The type for the ViewHolder * @return The correct ViewHolder for the specified viewType */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return core.onCreateViewHolder(parent, viewType) } /** * This method shouldn't be used directly, instead use * [onBindHeaderViewHolder] and * [onBindChildViewHolder] * * @param holder The ViewHolder to update * @param position The position to update the `holder` with */ @Suppress("UNCHECKED_CAST") override fun onBindViewHolder(holder: ViewHolder, position: Int) { val viewType = getItemViewType(position) val childPosition = getChildPosition(position) if (viewType and HeaderApi.HEADER_VIEW_TYPE_MASK != 0) { onBindHeaderViewHolder(holder as H, childPosition) return } onBindChildViewHolder(holder as C, childPosition) } override var headerData: HeaderData get() = core.headerData set(headerData) { core.headerData = headerData } override var autoUpdateHeaders: Boolean get() = core.autoUpdateHeaders set(autoUpdateHeaders) { core.setAutoUpdateHeaders(this, autoUpdateHeaders) } /** * Retrieves the view type for the specified position. * * @param adapterPosition The position to determine the view type for * @return The type of ViewHolder for the `adapterPosition` */ override fun getItemViewType(adapterPosition: Int): Int { return core.getItemViewType(adapterPosition) } /** * When the RecyclerView is attached a data observer is registered * in order to determine when to re-calculate the headers * * @param recyclerView The RecyclerView that was attached */ override fun onAttachedToRecyclerView(recyclerView: RecyclerView) { super.onAttachedToRecyclerView(recyclerView) core.registerObserver(this) } /** * When the RecyclerView is detached the registered data observer * will be unregistered. See [.onAttachedToRecyclerView] * for more information * * @param recyclerView The RecyclerView that has been detached */ override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) { super.onDetachedFromRecyclerView(recyclerView) core.unregisterObserver(this) } /** * Returns the total number of items in the data set hold by the adapter, this includes * both the Headers and the Children views * * * **NOTE:** [.getChildCount] should be overridden instead of this method * * @return The total number of items in this adapter. */ override fun getItemCount(): Int { return core.itemCount } override fun getHeaderViewType(childPosition: Int): Int { return HeaderApi.HEADER_VIEW_TYPE_MASK } override fun getChildViewType(childPosition: Int): Int { return 0 } override fun getChildCount(headerId: Long): Int { return core.getChildCount(headerId) } override val childCount: Int get() = super.getItemCount() override fun getHeaderId(childPosition: Int): Long { return RecyclerView.NO_ID } override fun getChildPosition(adapterPosition: Int): Int { return core.getChildPosition(adapterPosition) } override fun getChildIndex(adapterPosition: Int): Int? { return core.getChildIndex(adapterPosition) } override fun getAdapterPositionForChild(childPosition: Int): Int { return core.getAdapterPositionForChild(childPosition) } override fun getHeaderPosition(headerId: Long): Int { return core.getHeaderPosition(headerId) } override fun showHeaderAsChild(enabled: Boolean) { core.showHeaderAsChild(enabled) } override val customStickyHeaderViewId: Int get() = 0 }
apache-2.0
c39e4ed10e7d765aad7d28facd126a58
29.970149
89
0.729756
4.637854
false
false
false
false
kiruto/debug-bottle
components/src/main/kotlin/com/exyui/android/debugbottle/components/okhttp/interceptor.kt
1
1072
package com.exyui.android.debugbottle.components.okhttp /** * Created by yuriel on 11/14/16. */ internal const val OK_HTTP_CLIENT_CLASS = "com.squareup.okhttp.OkHttpClient" internal const val OK_HTTP_CLIENT_3_CLASS = "okhttp3.OkHttpClient" internal const val F_BREAK = " %n" internal const val F_URL = " %s" internal const val F_TIME = " in %.1fms" internal const val F_HEADERS = "%s" internal const val F_RESPONSE = F_BREAK + "Response: %d" internal const val F_BODY = "body: %s" internal const val F_BREAKER = F_BREAK + "-------------------------------------------" + F_BREAK internal const val F_REQUEST_WITHOUT_BODY = F_URL + F_TIME + F_BREAK + F_HEADERS internal const val F_RESPONSE_WITHOUT_BODY = F_RESPONSE + F_BREAK + F_HEADERS + F_BREAKER internal const val F_REQUEST_WITH_BODY = F_URL + F_TIME + F_BREAK + F_HEADERS + F_BODY + F_BREAK internal const val F_RESPONSE_WITH_BODY = F_RESPONSE + F_BREAK + F_HEADERS + F_BODY + F_BREAK + F_BREAKER
apache-2.0
36d00830354184e19eb976f3371cb4a2
31.515152
96
0.607276
3.42492
false
false
false
false
androidx/androidx
camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/core/Log.kt
3
4283
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.camera2.pipe.core import android.util.Log import androidx.annotation.RequiresApi /** * This object provides a set of common log functions that are optimized for CameraPipe with * options to control which log levels are available to log at compile time via const val's. * * Log functions have been designed so that printing variables and doing string concatenation * will not occur if the log level is disabled, which leads to slightly unusual syntax: * * Log.debug { "This is a log message with a $value" } */ @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java public object Log { public const val TAG: String = "CXCP" private const val LOG_LEVEL_DEBUG = 1 private const val LOG_LEVEL_INFO = 2 private const val LOG_LEVEL_WARN = 3 private const val LOG_LEVEL_ERROR = 4 // This indicates the lowest log level that will always log. private const val LOG_LEVEL = LOG_LEVEL_DEBUG public val DEBUG_LOGGABLE: Boolean = LOG_LEVEL <= LOG_LEVEL_DEBUG || Log.isLoggable(TAG, Log.DEBUG) public val INFO_LOGGABLE: Boolean = LOG_LEVEL <= LOG_LEVEL_INFO || Log.isLoggable(TAG, Log.INFO) public val WARN_LOGGABLE: Boolean = LOG_LEVEL <= LOG_LEVEL_WARN || Log.isLoggable(TAG, Log.WARN) public val ERROR_LOGGABLE: Boolean = LOG_LEVEL <= LOG_LEVEL_ERROR || Log.isLoggable(TAG, Log.ERROR) /** * Debug functions log noisy information related to the internals of the system. */ public inline fun debug(crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && DEBUG_LOGGABLE) Log.d(TAG, msg()) } public inline fun debug(throwable: Throwable, crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && DEBUG_LOGGABLE) Log.d(TAG, msg(), throwable) } /** * Info functions log standard, useful information about the state of the system. */ public inline fun info(crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && INFO_LOGGABLE) Log.i(TAG, msg()) } public inline fun info(throwable: Throwable, crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && INFO_LOGGABLE) Log.i(TAG, msg(), throwable) } /** * Warning functions are used when something unexpected may lead to a crash or fatal exception * later on as a result if the unusual circumstances */ public inline fun warn(crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && WARN_LOGGABLE) Log.w(TAG, msg()) } public inline fun warn(throwable: Throwable, crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && WARN_LOGGABLE) Log.w(TAG, msg(), throwable) } /** * Error functions are reserved for something unexpected that will lead to a crash or data loss. */ public inline fun error(crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && ERROR_LOGGABLE) Log.e(TAG, msg()) } public inline fun error(throwable: Throwable, crossinline msg: () -> String) { if (Debug.ENABLE_LOGGING && ERROR_LOGGABLE) Log.e(TAG, msg(), throwable) } /** * Read the stack trace of a calling method and join it to a formatted string. */ public fun readStackTrace(limit: Int = 4): String { val elements = Thread.currentThread().stackTrace // Ignore the first 3 elements, which ignores: // VMStack.getThreadStackTrace // Thread.currentThread().getStackTrace() // dumpStackTrace() return elements.drop(3).joinToString( prefix = "\n\t", separator = "\t", limit = limit, ) } }
apache-2.0
866ae2c81ae7ba37009ba58c541671ec
37.936364
100
0.670325
4.178537
false
false
false
false
yschimke/okhttp
mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt
4
5941
/* * Copyright (C) 2020 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.mockwebserver import okhttp3.HttpUrl import okhttp3.Protocol import org.junit.rules.ExternalResource import java.io.Closeable import java.io.IOException import java.net.InetAddress import java.net.Proxy import java.util.concurrent.TimeUnit import java.util.logging.Level import java.util.logging.Logger import javax.net.ServerSocketFactory import javax.net.ssl.SSLSocketFactory class MockWebServer : ExternalResource(), Closeable { val delegate = mockwebserver3.MockWebServer() val requestCount: Int by delegate::requestCount var bodyLimit: Long by delegate::bodyLimit var serverSocketFactory: ServerSocketFactory? by delegate::serverSocketFactory var dispatcher: Dispatcher = QueueDispatcher() set(value) { field = value delegate.dispatcher = value.wrap() } val port: Int get() { before() // This implicitly starts the delegate. return delegate.port } val hostName: String get() { before() // This implicitly starts the delegate. return delegate.hostName } var protocolNegotiationEnabled: Boolean by delegate::protocolNegotiationEnabled @get:JvmName("protocols") var protocols: List<Protocol> get() = delegate.protocols set(value) { delegate.protocols = value } init { delegate.dispatcher = dispatcher.wrap() } private var started: Boolean = false @Synchronized override fun before() { if (started) return try { start() } catch (e: IOException) { throw RuntimeException(e) } } @JvmName("-deprecated_port") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "port"), level = DeprecationLevel.ERROR) fun getPort(): Int = port fun toProxyAddress(): Proxy { before() // This implicitly starts the delegate. return delegate.toProxyAddress() } @JvmName("-deprecated_serverSocketFactory") @Deprecated( message = "moved to var", replaceWith = ReplaceWith( expression = "run { this.serverSocketFactory = serverSocketFactory }" ), level = DeprecationLevel.ERROR) fun setServerSocketFactory(serverSocketFactory: ServerSocketFactory) { delegate.serverSocketFactory = serverSocketFactory } fun url(path: String): HttpUrl { before() // This implicitly starts the delegate. return delegate.url(path) } @JvmName("-deprecated_bodyLimit") @Deprecated( message = "moved to var", replaceWith = ReplaceWith( expression = "run { this.bodyLimit = bodyLimit }" ), level = DeprecationLevel.ERROR) fun setBodyLimit(bodyLimit: Long) { delegate.bodyLimit = bodyLimit } @JvmName("-deprecated_protocolNegotiationEnabled") @Deprecated( message = "moved to var", replaceWith = ReplaceWith( expression = "run { this.protocolNegotiationEnabled = protocolNegotiationEnabled }" ), level = DeprecationLevel.ERROR) fun setProtocolNegotiationEnabled(protocolNegotiationEnabled: Boolean) { delegate.protocolNegotiationEnabled = protocolNegotiationEnabled } @JvmName("-deprecated_protocols") @Deprecated( message = "moved to var", replaceWith = ReplaceWith(expression = "run { this.protocols = protocols }"), level = DeprecationLevel.ERROR) fun setProtocols(protocols: List<Protocol>) { delegate.protocols = protocols } @JvmName("-deprecated_protocols") @Deprecated( message = "moved to var", replaceWith = ReplaceWith(expression = "protocols"), level = DeprecationLevel.ERROR) fun protocols(): List<Protocol> = delegate.protocols fun useHttps(sslSocketFactory: SSLSocketFactory, tunnelProxy: Boolean) { delegate.useHttps(sslSocketFactory, tunnelProxy) } fun noClientAuth() { delegate.noClientAuth() } fun requestClientAuth() { delegate.requestClientAuth() } fun requireClientAuth() { delegate.requireClientAuth() } @Throws(InterruptedException::class) fun takeRequest(): RecordedRequest { return delegate.takeRequest().unwrap() } @Throws(InterruptedException::class) fun takeRequest(timeout: Long, unit: TimeUnit): RecordedRequest? { return delegate.takeRequest(timeout, unit)?.unwrap() } @JvmName("-deprecated_requestCount") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "requestCount"), level = DeprecationLevel.ERROR) fun getRequestCount(): Int = delegate.requestCount fun enqueue(response: MockResponse) { delegate.enqueue(response.wrap()) } @Throws(IOException::class) @JvmOverloads fun start(port: Int = 0) { started = true delegate.start(port) } @Throws(IOException::class) fun start(inetAddress: InetAddress, port: Int) { started = true delegate.start(inetAddress, port) } @Synchronized @Throws(IOException::class) fun shutdown() { delegate.shutdown() } @Synchronized override fun after() { try { shutdown() } catch (e: IOException) { logger.log(Level.WARNING, "MockWebServer shutdown failed", e) } } override fun toString(): String = delegate.toString() @Throws(IOException::class) override fun close() = delegate.close() companion object { private val logger = Logger.getLogger(MockWebServer::class.java.name) } }
apache-2.0
02f2367dde4560e0f6410462c5147787
26.252294
93
0.700555
4.619751
false
false
false
false
SevenLines/Celebs-Image-Viewer
src/main/kotlin/theplace/parsers/SuperiorPicsParser.kt
1
3024
package theplace.parsers import com.mashape.unirest.http.Unirest import org.jsoup.Jsoup import theplace.parsers.elements.* import java.io.InputStream /** * Created by mk on 07.04.16. */ class SuperiorPicsParser : BaseParser(url = "http://forums.superiorpics.com/", title = "superiorpics") { override var isAlwaysOnePage = true override fun getAlbumPages(album: GalleryAlbum): List<GalleryAlbumPage> { return listOf(GalleryAlbumPage(url = album.url, album = album)) } override fun getAlbums(subGallery: SubGallery): List<GalleryAlbum> { var r = Unirest.get(subGallery.url).asString() var doc = Jsoup.parse(r.body) var boxes = doc.select(".content-left .box135.box-shadow-full") return boxes.map { var href = it.select("a").map { it.attr("href") }.filter { it.startsWith("http://forums.superiorpics.com") }.distinct().first() var title = it.select(".forum-box-news-title-small a").first().text() var thumb_url = it.select(".box135-thumb-wrapper img").first().attr("src") var album = GalleryAlbum( url = href, title = title, subgallery = subGallery ) album.thumb = GalleryImage( url = thumb_url, url_thumb = thumb_url, album = album ) return@map album } } override fun getGalleries_internal(): List<Gallery> { throw UnsupportedOperationException() } override fun getImages(albumPage: GalleryAlbumPage): List<GalleryImage> { var r = Unirest.get(albumPage.url).asString() var doc = Jsoup.parse(r.body) var links = doc.select(".post-content .post_inner a") return links.filter { !(it.parent().hasClass("fr-item-thumb-box") or it.parents().hasClass("signature")) }.map { var url = it.attr("href") var url_thumb = it.select("img").first()?.attr("src") if (url_thumb != null) { GalleryImage(page = albumPage, album = albumPage.album, url = url, url_thumb = url_thumb) } else { return@map null } }.filterNotNull() } override fun downloadImage(image_url: String): InputStream? { return Unirest.get("$image_url").header("referer", "$url").asBinary().body } override fun getSubGalleries(gallery: Gallery): List<SubGallery> { var r = Unirest.get(gallery.url).asString() var doc = Jsoup.parse(r.body) var links = doc.select(".alphaGender-font-paging-box-center a") var max = links.map { it.text() }.filter { "\\d+".toRegex().matches(it) }.map { it.toInt() }.max() return IntRange(1, max ?: 1).map { var newUrl = if (it != 1) "${gallery.url}/index$it.html" else gallery.url SubGallery(url = newUrl, gallery = gallery) } } }
mit
e1da4f1263d54f3cab1046ce90a5312b
36.345679
106
0.574074
4.131148
false
false
false
false
moove-it/android-kotlin-architecture
app/src/test/java/com/mooveit/kotlin/kotlintemplateproject/data/entity/EntityMocker.kt
1
378
package com.mooveit.kotlin.kotlintemplateproject.data.entity class EntityMocker { companion object Factory { fun getExternalId(): Long = 123456789 fun getMockerPet(): Pet { val pet = Pet() pet.externalId = getExternalId() pet.name = "Spike" pet.status = "available" return pet } } }
mit
eb245941eaef745ce59f6fa29c86c027
21.294118
60
0.566138
4.909091
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/sponge/inspection/SpongeWrongGetterTypeInspection.kt
1
8036
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.sponge.inspection import com.demonwav.mcdev.platform.sponge.util.SpongeConstants import com.demonwav.mcdev.platform.sponge.util.isValidSpongeListener import com.demonwav.mcdev.platform.sponge.util.resolveSpongeGetterTarget import com.demonwav.mcdev.util.isJavaOptional import com.intellij.codeInspection.AbstractBaseUastLocalInspectionTool import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.IntentionAndQuickFixAction import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.lang.jvm.JvmMethod import com.intellij.lang.jvm.actions.createChangeParametersActions import com.intellij.lang.jvm.actions.expectedParameter import com.intellij.lang.jvm.actions.updateMethodParametersRequest import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClassType import com.intellij.psi.PsiFile import com.intellij.psi.PsiPrimitiveType import com.intellij.psi.PsiSubstitutor import com.intellij.psi.PsiType import com.intellij.psi.util.TypeConversionUtil import com.siyeh.ig.InspectionGadgetsFix import java.util.function.Supplier import org.jetbrains.uast.UMethod import org.jetbrains.uast.getContainingUClass class SpongeWrongGetterTypeInspection : AbstractBaseUastLocalInspectionTool() { override fun getDisplayName() = "Parameter's type is not assignable to its @Getter method return type" override fun getStaticDescription() = "@Getter requires the parameter's type to be assignable from the annotation's target method return type" override fun checkMethod( method: UMethod, manager: InspectionManager, isOnTheFly: Boolean ): Array<ProblemDescriptor>? { val parameters = method.uastParameters if (parameters.size < 2 || !method.isValidSpongeListener()) { return null } val eventClassType = parameters.first().type as? PsiClassType val resolveEventClassTypeGenerics = eventClassType?.resolveGenerics() val eventTypeSubstitutor = resolveEventClassTypeGenerics?.substitutor ?: PsiSubstitutor.EMPTY resolveEventClassTypeGenerics?.element?.let { eventTypeSubstitutor.putAll(it, eventClassType.parameters) } val problems = mutableListOf<ProblemDescriptor>() // We start at 1 because the first parameter is the event for (i in 1 until parameters.size) { val parameter = parameters[i] val getterAnnotation = parameter.findAnnotation(SpongeConstants.GETTER_ANNOTATION) ?: continue val getterMethod = getterAnnotation.resolveSpongeGetterTarget() ?: continue val getterClass = getterMethod.getContainingUClass() ?: continue val eventClass = eventClassType?.resolve() ?: continue val getterSubst = TypeConversionUtil.getSuperClassSubstitutor( getterClass.javaPsi, eventClass, eventTypeSubstitutor ) val getterReturnType = getterMethod.returnType?.let(getterSubst::substitute) ?: continue val parameterType = parameter.type if (getterReturnType.isAssignableFrom(parameterType)) { continue } if (isOptional(getterReturnType)) { val getterOptionalType = getFirstGenericType(getterReturnType) if (getterOptionalType != null && areInSameHierarchy(getterOptionalType, parameterType)) { continue } if (getterOptionalType != null && isOptional(parameterType)) { val paramOptionalType = getFirstGenericType(parameterType) if (paramOptionalType != null && areInSameHierarchy(getterOptionalType, paramOptionalType)) { continue } } } // Prefer highlighting the type, but if type is absent use the whole parameter instead val typeReference = parameter.typeReference ?: continue val location = typeReference.sourcePsi?.takeUnless { it.textRange.isEmpty } ?: continue val methodJava = method.javaPsi as JvmMethod val fixes = this.createFixes(methodJava, getterReturnType, i, manager.project) problems += manager.createProblemDescriptor( location, this.staticDescription, isOnTheFly, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING ) } return problems.toTypedArray() } private fun areInSameHierarchy(aType: PsiType, otherType: PsiType): Boolean = aType.isAssignableFrom(otherType) || otherType.isAssignableFrom(aType) private fun isOptional(type: PsiType): Boolean { val typeClass = type as? PsiClassType ?: return false return typeClass.isJavaOptional() && typeClass.hasParameters() } private fun getFirstGenericType(typeElement: PsiType): PsiType? = (typeElement as? PsiClassType)?.parameters?.firstOrNull() private fun createFixes( method: JvmMethod, expectedType: PsiType, paramIndex: Int, project: Project ): Array<out LocalQuickFix> { if (expectedType is PsiPrimitiveType || expectedType is PsiClassType && !isOptional(expectedType) ) { // The getter does not return an Optional, simply suggest the return type return arrayOf(Fix(method, paramIndex, expectedType)) } val elementFactory = JavaPsiFacade.getElementFactory(project) val expectedClassType = expectedType as? PsiClassType ?: return InspectionGadgetsFix.EMPTY_ARRAY val fixedClassType = if (isOptional(expectedClassType)) { val wrappedType = expectedClassType.parameters.first() val resolveResult = (wrappedType as? PsiClassType)?.resolveGenerics() ?: return InspectionGadgetsFix.EMPTY_ARRAY val element = resolveResult.element ?: return InspectionGadgetsFix.EMPTY_ARRAY elementFactory.createType(element, resolveResult.substitutor) } else { val resolvedClass = expectedClassType.resolve() ?: return InspectionGadgetsFix.EMPTY_ARRAY elementFactory.createType(resolvedClass) } // Suggest a non-Optional version too return arrayOf( Fix(method, paramIndex, expectedType), Fix(method, paramIndex, fixedClassType) ) } private class Fix( method: JvmMethod, val paramIndex: Int, val expectedType: PsiType, ) : IntentionAndQuickFixAction() { private val myText: String = "Set parameter type to ${expectedType.presentableText}" private val methodPointer = Supplier<JvmMethod?> { method } override fun applyFix(project: Project, file: PsiFile, editor: Editor?) { val changeParamsRequest = updateMethodParametersRequest(methodPointer) { actualParams -> val existingParam = actualParams[paramIndex] val newParam = expectedParameter( expectedType, existingParam.semanticNames.first(), existingParam.expectedAnnotations ) actualParams.toMutableList().also { it[paramIndex] = newParam } } val waw = createChangeParametersActions(methodPointer.get()!!, changeParamsRequest).firstOrNull() ?: return waw.invoke(project, editor, file) } override fun getName(): String = myText override fun getFamilyName(): String = myText } }
mit
cc9c43d7c1678a90c695fa0dfe53844d
41.744681
119
0.680314
5.580556
false
false
false
false
handstandsam/ShoppingApp
shopping-cart-sqldelight/src/main/java/com/handstandsam/shoppingapp/cart/SqlDelightShoppingCartDao.kt
1
2466
package com.handstandsam.shoppingapp.cart import com.handstandsam.shoppingapp.cart.sqldelight.Database import com.handstandsam.shoppingapp.models.Item import com.handstandsam.shoppingapp.models.ItemWithQuantity import com.squareup.sqldelight.db.SqlDriver import com.squareup.sqldelight.runtime.coroutines.asFlow import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map /** * A SqlDelight Implementation of our [ShoppingCartDao] to read and write to the Database */ class SqlDelightShoppingCartDao(sqlDriver: SqlDriver) : CoroutineScope by CoroutineScope(Dispatchers.IO), ShoppingCartDao { /** * The SqlDelight queries that were created during code generation from our .sq file */ private val itemInCartEntityQueries = Database(sqlDriver).itemInCartEntityQueries override val allItems: Flow<List<ItemWithQuantity>> get() = itemInCartEntityQueries.selectAll() .asFlow() .map { query -> query.executeAsList() .toItemWithQuantityList() } override suspend fun findByLabel(label: String): ItemWithQuantity? { return itemInCartEntityQueries.selectByLabel(label) .executeAsOneOrNull() ?.toItemWithQuantity() } override suspend fun upsert(itemWithQuantity: ItemWithQuantity) { itemInCartEntityQueries.insertOrReplace( label = itemWithQuantity.item.label, image = itemWithQuantity.item.image, link = itemWithQuantity.item.link, quantity = itemWithQuantity.quantity ) } override suspend fun remove(itemWithQuantity: ItemWithQuantity) { itemInCartEntityQueries.deleteByLabel(itemWithQuantity.item.label) } override suspend fun empty() { itemInCartEntityQueries.empty() } } /** * Extension Function converting the SqlDelight Model into our App's Model */ private fun ItemInCart.toItemWithQuantity(): ItemWithQuantity { return ItemWithQuantity( item = Item( label = label, image = image, link = link ), quantity = quantity ) } /** * Extension Function mapping the SqlDelight Model into our App's Model */ private fun List<ItemInCart>.toItemWithQuantityList(): List<ItemWithQuantity> { return this.map { it.toItemWithQuantity() } }
apache-2.0
63c9dc3319a3f65618f8dd84d0d5ab17
29.825
89
0.699513
5.36087
false
false
false
false
jankotek/MapDB
src/test/java/org/mapdb/DBCollectionTest.kt
2
5841
package org.mapdb import io.kotlintest.should import io.kotlintest.shouldBe import org.junit.Assert.assertTrue import org.mapdb.cli.Export import org.mapdb.cli.Import import org.mapdb.db.DB import org.mapdb.io.DataInput2 import org.mapdb.io.DataInput2ByteArray import org.mapdb.io.DataOutput2ByteArray import org.mapdb.ser.Serializer import org.mapdb.ser.Serializers import org.mapdb.util.Exporter class DBCollectionTest: DBWordSpec({ for(a in adapters()){ a.name should { "wrong serializer fail on reopen"{ TT.withTempFile { f-> var db = DB.Maker.appendFile(f).make() a.open(db, "name", Serializers.INTEGER) db.close() db = DB.Maker.appendFile(f).make() TT.assertFailsWith(DBException.WrongSerializer::class) { a.open(db, "name", Serializers.LONG) } } } "use the same instance"{ val db = DB.Maker.heapSer().make() val c1 = a.open(db, "name", Serializers.INTEGER) val c2 = a.open(db, "name", Serializers.INTEGER) val c3 = a.open(db, "name", Serializers.INTEGER) assertTrue(c1===c2 && c2===c3) } "import fails on existing"{ TT.withTempFile { f -> var db = DB.Maker.appendFile(f).make() a.open(db, "name", Serializers.INTEGER) db.close() db = DB.Maker.appendFile(f).make() val input = DataInput2ByteArray(ByteArray(0)) TT.assertFailsWith(DBException.WrongConfig::class){ a.import(db, "name", Serializers.INTEGER, input ) } } } "export"{ val db1 = DB.Maker.heapSer().make() val c1 = a.open(db1, "aa", Serializers.INTEGER) for(i in 1..100) a.add(c1, i) val output = DataOutput2ByteArray() (c1 as Exporter).exportToDataOutput2(output) val input = DataInput2ByteArray(output.copyBytes()) val db2 = DB.Maker.heapSer().make() val c2 = a.import(db2, "aa", Serializers.INTEGER, input) val all = a.getAll(c2).toList() for(i in 1..100){ all[i-1] shouldBe i } } "cli export"{ TT.withTempFile { dbf -> var db = DB.Maker.appendFile(dbf).make() var c = a.open(db, "name", Serializers.INTEGER) for(i in 1..100) a.add(c, i) db.close() val outf = TT.tempNotExistFile() //export from cli Export.main(arrayOf("-d",dbf.path, "-o", outf.path, "-n","name")) outf.length() should {it>0L} db = DB.Maker.heapSer().make() val input = DataInput2ByteArray(outf.readBytes()) c = a.import(db, "name2", Serializers.INTEGER, input ) val all = a.getAll(c).toList() for(i in 1..100){ all[i-1] shouldBe i } } } "cli import"{ TT.withTempFile { dbf -> var db = DB.Maker.heapSer().make() var c = a.open(db, "name", Serializers.INTEGER) for(i in 1..100) a.add(c, i) val output = DataOutput2ByteArray() (c as Exporter).exportToDataOutput2(output) val outf = TT.tempFile() outf.writeBytes(output.copyBytes()) //import from cli Import.main(arrayOf("-d",dbf.path, "-i", outf.path, "-n","name")) dbf.length() should {it>0L} db = DB.Maker.appendFile(dbf).make() c = a.open(db, "name", Serializers.INTEGER) val all = a.getAll(c).toList() for(i in 1..100){ all[i-1] shouldBe i } } } } } }){ companion object { abstract class Adapter<C>{ abstract fun open(db: DB, name:String, serializer: Serializer<*>):C abstract fun import(db: DB, name:String, serializer: Serializer<*>, input: DataInput2):C abstract fun add(c:C, e:Any?) abstract fun getAll(c:C):Iterable<Any?> abstract val name:String } fun adapters():List<Adapter<Any>>{ /* val qAdapter = object: Adapter<LinkedFIFOQueue<Any>>() { override fun import(db: DB, name: String, serializer: Serializer<*>, input: DataInput2): LinkedFIFOQueue<Any> { return db.queue(name, serializer) .importFromDataInput2(input) .make() as LinkedFIFOQueue<Any> } override fun open(db: DB, name: String, serializer: Serializer<*>): LinkedFIFOQueue<Any> { return db.queue(name, serializer).make() as LinkedFIFOQueue<Any> } override fun add(c: LinkedFIFOQueue<Any>, e: Any?) { c.add(e) } override fun getAll(c: LinkedFIFOQueue<Any>): Iterable<Any?> { return c } override val name = "queue" } */ return emptyList() } } }
apache-2.0
d3965ff3017beb0a352cd082b7cec4a3
30.572973
127
0.466359
4.559719
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/other/settings/SettingsFragment.kt
1
12936
package de.tum.`in`.tumcampusapp.component.other.settings import android.Manifest.permission.READ_CALENDAR import android.Manifest.permission.WRITE_CALENDAR import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager.PERMISSION_GRANTED import android.graphics.drawable.BitmapDrawable import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat.checkSelfPermission import androidx.core.content.edit import androidx.core.os.bundleOf import androidx.preference.CheckBoxPreference import androidx.preference.ListPreference import androidx.preference.MultiSelectListPreference import androidx.preference.Preference import androidx.preference.PreferenceCategory import androidx.preference.PreferenceFragmentCompat import androidx.preference.SwitchPreferenceCompat import com.squareup.picasso.Picasso import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.api.tumonline.AccessTokenManager import de.tum.`in`.tumcampusapp.component.tumui.calendar.CalendarController import de.tum.`in`.tumcampusapp.component.ui.cafeteria.repository.CafeteriaLocalRepository import de.tum.`in`.tumcampusapp.component.ui.eduroam.SetupEduroamActivity import de.tum.`in`.tumcampusapp.component.ui.news.NewsController import de.tum.`in`.tumcampusapp.component.ui.onboarding.StartupActivity import de.tum.`in`.tumcampusapp.database.TcaDb import de.tum.`in`.tumcampusapp.di.injector import de.tum.`in`.tumcampusapp.service.SilenceService import de.tum.`in`.tumcampusapp.service.StartSyncReceiver import de.tum.`in`.tumcampusapp.utils.Const import de.tum.`in`.tumcampusapp.utils.Utils import de.tum.`in`.tumcampusapp.utils.plusAssign import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_setup_eduroam.* import org.jetbrains.anko.defaultSharedPreferences import org.jetbrains.anko.notificationManager import java.util.concurrent.ExecutionException import javax.inject.Inject class SettingsFragment : PreferenceFragmentCompat(), Preference.OnPreferenceClickListener, SharedPreferences.OnSharedPreferenceChangeListener { private val compositeDisposable = CompositeDisposable() @Inject lateinit var cafeteriaLocalRepository: CafeteriaLocalRepository @Inject lateinit var newsController: NewsController override fun onAttach(context: Context) { super.onAttach(context) injector.inject(this) } override fun onCreatePreferences( savedInstanceState: Bundle?, rootKey: String? ) { setPreferencesFromResource(R.xml.settings, rootKey) populateNewsSources() setUpEmployeeSettings() // Disables silence service and logout if the app is used without TUMOnline access val silentSwitch = findPreference(Const.SILENCE_SERVICE) as? SwitchPreferenceCompat val logoutButton = findPreference(BUTTON_LOGOUT) if (!AccessTokenManager.hasValidAccessToken(context)) { if (silentSwitch != null) { silentSwitch.isEnabled = false } logoutButton.isVisible = false } // Only do these things if we are in the root of the preferences if (rootKey == null) { // Click listener for preference list entries. Used to simulate a button // (since it is not possible to add a button to the preferences screen) findPreference(BUTTON_LOGOUT).onPreferenceClickListener = this setSummary("language_preference") setSummary("card_default_campus") setSummary("silent_mode_set_to") setSummary("background_mode_set_to") } else if (rootKey == "card_cafeteria") { setSummary("card_cafeteria_default_G") setSummary("card_cafeteria_default_K") setSummary("card_cafeteria_default_W") setSummary("card_role") initCafeteriaCardSelections() } else if (rootKey == "card_mvv") { setSummary("card_stations_default_G") setSummary("card_stations_default_C") setSummary("card_stations_default_K") } else if (rootKey == "card_eduroam") { findPreference(SETUP_EDUROAM).onPreferenceClickListener = this } requireContext().defaultSharedPreferences.registerOnSharedPreferenceChangeListener(this) } private fun populateNewsSources() { val newsSourcesPreference = findPreference("card_news_sources") as? PreferenceCategory ?: return val newsSources = newsController.newsSources for (newsSource in newsSources) { val pref = CheckBoxPreference(requireContext()) pref.key = "card_news_source_" + newsSource.id pref.setDefaultValue(true) // Reserve space so that when the icon is loaded the text is not moved again pref.isIconSpaceReserved = true // Load news source icon in background and set it val url = newsSource.icon if (url.isNotBlank()) { loadNewsSourceIcon(pref, url) } pref.title = newsSource.title newsSourcesPreference.addPreference(pref) } } private fun loadNewsSourceIcon( preference: Preference, url: String ) { compositeDisposable += Single .fromCallable { Picasso.get().load(url).get() } .subscribeOn(Schedulers.io()) .map { BitmapDrawable(resources, it) } .observeOn(AndroidSchedulers.mainThread()) .subscribe(preference::setIcon, Utils::log) } /** * Disable setting for non-employees. */ private fun setUpEmployeeSettings() { val isEmployee = Utils.getSetting(requireContext(), Const.TUMO_EMPLOYEE_ID, "").isNotEmpty() val checkbox = findPreference(Const.EMPLOYEE_MODE) ?: return if (!isEmployee) { checkbox.isEnabled = false } } override fun onSharedPreferenceChanged( sharedPrefs: SharedPreferences, key: String? ) { if (key == null) { return } setSummary(key) // When newspread selection changes // deselect all newspread sources and select only the // selected source if one of all was selected before if (key == "news_newspread") { val newspreadIds = 7..13 val value = newspreadIds.any { sharedPrefs.getBoolean("card_news_source_$it", false) } val newSource = sharedPrefs.getString(key, "7") sharedPrefs.edit { newspreadIds.forEach { putBoolean("card_news_source_$it", false) } putBoolean("card_news_source_$newSource", value) } } // If the silent mode was activated, start the service. This will invoke // the service to call onHandleIntent which checks available lectures if (key == Const.SILENCE_SERVICE) { val service = Intent(requireContext(), SilenceService::class.java) if (sharedPrefs.getBoolean(key, false)) { if (!SilenceService.hasPermissions(requireContext())) { // disable until silence service permission is resolved val silenceSwitch = findPreference(Const.SILENCE_SERVICE) as SwitchPreferenceCompat silenceSwitch.isChecked = false Utils.setSetting(requireContext(), Const.SILENCE_SERVICE, false) SilenceService.requestPermissions(requireContext()) } else { requireContext().startService(service) } } else { requireContext().stopService(service) } } // If the background mode was activated, start the service. This will invoke // the service to call onHandleIntent which updates all background data if (key == Const.BACKGROUND_MODE) { if (sharedPrefs.getBoolean(key, false)) { StartSyncReceiver.startBackground(requireContext()) } else { StartSyncReceiver.cancelBackground() } } // restart app after language change if (key == "language_preference" && activity != null) { (activity as SettingsActivity).restartApp() } } private fun initCafeteriaCardSelections() { val cafeterias = cafeteriaLocalRepository .getAllCafeterias() .blockingFirst() .sortedBy { it.name } val cafeteriaByLocationName = getString(R.string.settings_cafeteria_depending_on_location) val cafeteriaNames = listOf(cafeteriaByLocationName) + cafeterias.map { it.name } val cafeteriaByLocationId = Const.CAFETERIA_BY_LOCATION_SETTINGS_ID val cafeteriaIds = listOf(cafeteriaByLocationId) + cafeterias.map { it.id.toString() } val preference = findPreference(Const.CAFETERIA_CARDS_SETTING) as MultiSelectListPreference preference.entries = cafeteriaNames.toTypedArray() preference.entryValues = cafeteriaIds.toTypedArray() preference.setOnPreferenceChangeListener { pref, newValue -> (pref as MultiSelectListPreference).values = newValue as Set<String> setCafeteriaCardsSummary(preference) false } setCafeteriaCardsSummary(preference) } private fun setSummary(key: CharSequence) { val pref = findPreference(key) if (pref is ListPreference) { val entry = pref.entry.toString() pref.summary = entry } } private fun setCafeteriaCardsSummary(preference: MultiSelectListPreference) { val values = preference.values if (values.isEmpty()) { preference.setSummary(R.string.settings_no_location_selected) } else { preference.summary = values .map { preference.findIndexOfValue(it) } .map { preference.entries[it] } .map { it.toString() } .sorted() .joinToString(", ") } } override fun onPreferenceClick( preference: Preference? ): Boolean { when (preference?.key) { SETUP_EDUROAM -> startActivity(Intent(context, SetupEduroamActivity::class.java)) BUTTON_LOGOUT -> showLogoutDialog(R.string.logout_title, R.string.logout_message) else -> return false } return true } private fun showLogoutDialog(title: Int, message: Int) { AlertDialog.Builder(requireContext()) .setTitle(title) .setMessage(message) .setPositiveButton(R.string.logout) { _, _ -> logout() } .setNegativeButton(R.string.cancel, null) .create() .apply { window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background) } .show() } private fun logout() { try { clearData() } catch (e: Exception) { Utils.log(e) showLogoutDialog(R.string.logout_error_title, R.string.logout_try_again) return } startActivity(Intent(requireContext(), StartupActivity::class.java)) requireActivity().finish() } @SuppressLint("ApplySharedPref") @Throws(ExecutionException::class, InterruptedException::class) private fun clearData() { TcaDb.resetDb(requireContext()) requireContext().defaultSharedPreferences.edit().clear().commit() // Remove all notifications that are currently shown requireContext().notificationManager.cancelAll() val readCalendar = checkSelfPermission(requireActivity(), READ_CALENDAR) val writeCalendar = checkSelfPermission(requireActivity(), WRITE_CALENDAR) // Delete local calendar Utils.setSetting(requireContext(), Const.SYNC_CALENDAR, false) if (readCalendar == PERMISSION_GRANTED && writeCalendar == PERMISSION_GRANTED) { CalendarController.deleteLocalCalendar(requireContext()) } } override fun onDestroy() { compositeDisposable.dispose() super.onDestroy() } companion object { private const val BUTTON_LOGOUT = "button_logout" private const val SETUP_EDUROAM = "card_eduroam_setup" fun newInstance( key: String? ) = SettingsFragment().apply { arguments = bundleOf(ARG_PREFERENCE_ROOT to key) } } }
gpl-3.0
7b7ae1427333d41191a3491539cf07f9
38.319149
104
0.654066
5.166134
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/subject/nine/module/options/OptionsModelImpl.kt
1
1891
package com.intfocus.template.subject.nine.module.options import com.alibaba.fastjson.JSONObject import com.intfocus.template.model.DaoUtil import com.intfocus.template.model.callback.LoadDataCallback import com.intfocus.template.model.gen.SourceDao import com.intfocus.template.subject.nine.CollectionModelImpl import com.intfocus.template.subject.nine.module.ModuleModel /** * @author liuruilin * @data 2017/11/3 * @describe */ class OptionsModelImpl : ModuleModel<OptionsEntity> { companion object { private var INSTANCE: OptionsModelImpl? = null /** * Returns the single instance of this class, creating it if necessary. */ @JvmStatic fun getInstance(): OptionsModelImpl { return INSTANCE ?: OptionsModelImpl() .apply { INSTANCE = this } } /** * Used to force [getInstance] to create a new instance * next time it's called. */ @JvmStatic fun destroyInstance() { INSTANCE = null } } override fun analyseData(params: String, callback: LoadDataCallback<OptionsEntity>) { val data = JSONObject.parseObject(params, OptionsEntity::class.java) callback.onSuccess(data) } override fun insertDb(value: String, key: String, listItemType: Int) { val sourceDao = DaoUtil.getDaoSession()!!.sourceDao val collectionQb = sourceDao.queryBuilder() val collection = collectionQb.where(collectionQb.and(SourceDao.Properties.Key.eq(key), SourceDao.Properties.Uuid.eq(CollectionModelImpl.uuid))).unique() if (null != collection) { collection.value = value sourceDao.update(collection) if (listItemType != 0) { CollectionModelImpl.getInstance().updateCollectionData(listItemType, value) } } } }
gpl-3.0
abd15bc550bcc511be8fefb7eb161be8
34.018519
160
0.658382
4.657635
false
false
false
false
HabitRPG/habitica-android
wearos/src/main/java/com/habitrpg/wearos/habitica/ui/activities/TaskFormActivity.kt
1
5233
package com.habitrpg.wearos.habitica.ui.activities import android.app.Activity import android.content.Intent import android.content.res.ColorStateList import android.os.Bundle import android.widget.TextView import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.ActivityTaskFormBinding import com.habitrpg.shared.habitica.models.tasks.TaskType import com.habitrpg.wearos.habitica.ui.viewmodels.TaskFormViewModel import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.launch @AndroidEntryPoint class TaskFormActivity : BaseActivity<ActivityTaskFormBinding, TaskFormViewModel>() { var taskType: TaskType? = null set(value) { field = value updateTaskTypeButton(binding.todoButton, TaskType.TODO) updateTaskTypeButton(binding.dailyButton, TaskType.DAILY) updateTaskTypeButton(binding.habitButton, TaskType.HABIT) val typeName = getString(when(value) { TaskType.HABIT -> R.string.habit TaskType.DAILY -> R.string.daily TaskType.TODO -> R.string.todo TaskType.REWARD -> R.string.reward else -> R.string.task }) binding.confirmationTitle.text = getString(R.string.new_task_x, typeName) binding.saveButton.setChipText(getString(R.string.save_task_x, typeName)) } override val viewModel: TaskFormViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { binding = ActivityTaskFormBinding.inflate(layoutInflater) super.onCreate(savedInstanceState) binding.editText.setOnClickListener { it.clearFocus() requestInput() } binding.editButton.setOnClickListener { binding.editTaskWrapper.isVisible = true binding.taskConfirmationWrapper.isVisible = false if (intent.extras?.containsKey("task_type") == true) { requestInput() } } binding.todoButton.setOnClickListener { taskType = TaskType.TODO } binding.dailyButton.setOnClickListener { taskType = TaskType.DAILY } binding.habitButton.setOnClickListener { taskType = TaskType.HABIT } binding.saveButton.setOnClickListener { binding.saveButton.isEnabled = false lifecycleScope.launch(CoroutineExceptionHandler { _, _ -> binding.saveButton.isEnabled = true binding.editTaskWrapper.isVisible = true binding.taskConfirmationWrapper.isVisible = false }) { viewModel.saveTask(binding.editText.text, taskType) val data = Intent() data.putExtra("task_type", taskType?.value) setResult(Activity.RESULT_OK, data) finish() parent.startActivity(Intent(parent, TaskListActivity::class.java).apply { putExtra("task_type", taskType?.value) }) } } if (intent.extras?.containsKey("task_type") == true) { taskType = TaskType.from(intent.getStringExtra("task_type")) binding.taskTypeHeader.isVisible = false binding.taskTypeWrapper.isVisible = false binding.header.textView.text = getString(R.string.create_task, taskType?.value) requestInput() } else { taskType = TaskType.TODO binding.header.textView.text = getString(R.string.new_task) } } private val inputResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { val input = it.data?.getStringExtra("input") if (input?.isNotBlank() == true) { binding.editTaskWrapper.isVisible = false binding.taskConfirmationWrapper.isVisible = true binding.confirmationText.text = input binding.editText.setText(input) } } private fun requestInput() { val intent = Intent(this, InputActivity::class.java).apply { putExtra("title", getString(R.string.task_title_hint)) putExtra("input", binding.editText.text.toString()) } inputResult.launch(intent) } private fun updateTaskTypeButton(button: TextView, thisType: TaskType) { if (taskType == thisType) { button.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(this, R.color.watch_purple_10)) button.background.alpha = 100 button.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.radio_checked, 0) } else { button.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(this, R.color.watch_purple_5)) button.background.alpha = 255 button.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.radio_unchecked, 0) } } }
gpl-3.0
99091b6cb6f5bc80c82629ba75979e38
41.901639
107
0.660042
5.036574
false
false
false
false
wix/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/options/StackAnimationOptions.kt
1
2648
package com.reactnativenavigation.options import com.reactnativenavigation.options.animations.ViewAnimationOptions import com.reactnativenavigation.options.params.Bool import com.reactnativenavigation.options.params.NullBool import com.reactnativenavigation.options.parsers.BoolParser import org.json.JSONObject open class StackAnimationOptions(json: JSONObject? = null) : LayoutAnimation { @JvmField var enabled: Bool = NullBool() @JvmField var waitForRender: Bool = NullBool() @JvmField var content = ViewAnimationOptions() @JvmField var bottomTabs = ViewAnimationOptions() @JvmField var topBar = ViewAnimationOptions() override var sharedElements = SharedElements() override var elementTransitions = ElementTransitions() init { parse(json) } fun mergeWith(other: StackAnimationOptions) { topBar.mergeWith(other.topBar) content.mergeWith(other.content) bottomTabs.mergeWith(other.bottomTabs) sharedElements.mergeWith(other.sharedElements) elementTransitions.mergeWith(other.elementTransitions) if (other.enabled.hasValue()) enabled = other.enabled if (other.waitForRender.hasValue()) waitForRender = other.waitForRender } fun mergeWithDefault(defaultOptions: StackAnimationOptions) { content.mergeWithDefault(defaultOptions.content) bottomTabs.mergeWithDefault(defaultOptions.bottomTabs) topBar.mergeWithDefault(defaultOptions.topBar) sharedElements.mergeWithDefault(defaultOptions.sharedElements) elementTransitions.mergeWithDefault(defaultOptions.elementTransitions) if (!enabled.hasValue()) enabled = defaultOptions.enabled if (!waitForRender.hasValue()) waitForRender = defaultOptions.waitForRender } fun hasEnterValue(): Boolean { return topBar.enter.hasValue() || content.enter.hasValue() || bottomTabs.enter.hasValue() || waitForRender.hasValue() } fun hasExitValue(): Boolean { return topBar.exit.hasValue() || content.exit.hasValue() || bottomTabs.exit.hasValue() || waitForRender.hasValue() } private fun parse(json: JSONObject?) { json ?: return content = ViewAnimationOptions(json.optJSONObject("content")) bottomTabs = ViewAnimationOptions(json.optJSONObject("bottomTabs")) topBar = ViewAnimationOptions(json.optJSONObject("topBar")) enabled = BoolParser.parseFirst(json, "enabled", "enable") waitForRender = BoolParser.parse(json, "waitForRender") sharedElements = SharedElements.parse(json) elementTransitions = ElementTransitions.parse(json) } }
mit
23cc334d526e06ca2d1f4c781714d358
42.42623
125
0.736782
5.471074
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/debug/frame/QueryExecutionStack.kt
1
1406
/* * 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.processor.debug.frame import com.intellij.xdebugger.frame.XExecutionStack import com.intellij.xdebugger.frame.XStackFrame import uk.co.reecedunn.intellij.plugin.processor.debug.DebugSession class QueryExecutionStack(displayName: String, private val session: DebugSession) : XExecutionStack(displayName) { private var frames: List<XStackFrame>? = null override fun computeStackFrames(firstFrameIndex: Int, container: XStackFrameContainer?) { if (firstFrameIndex == 0) { frames = session.stackFrames container?.addStackFrames(frames!!, true) } else { container?.addStackFrames(frames!!.drop(firstFrameIndex), true) } } override fun getTopFrame(): XStackFrame? = frames?.firstOrNull() }
apache-2.0
35bef09a64f53f41bdb4c4a4a705c52c
37
93
0.731152
4.477707
false
false
false
false
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/common/basic/GeoActivity.kt
1
5274
package wangdaye.com.geometricweather.common.basic import android.content.Intent import android.graphics.Rect import android.os.Bundle import android.view.ViewGroup import androidx.annotation.CallSuper import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Lifecycle import wangdaye.com.geometricweather.GeometricWeather import wangdaye.com.geometricweather.common.basic.insets.FitHorizontalSystemBarRootLayout import wangdaye.com.geometricweather.common.snackbar.SnackbarContainer import wangdaye.com.geometricweather.common.utils.DisplayUtils import wangdaye.com.geometricweather.common.utils.LanguageUtils import wangdaye.com.geometricweather.settings.SettingsManager abstract class GeoActivity : AppCompatActivity() { lateinit var fitHorizontalSystemBarRootLayout: FitHorizontalSystemBarRootLayout private class KeyboardResizeBugWorkaround private constructor( activity: GeoActivity ) { private val root = activity.fitHorizontalSystemBarRootLayout private val rootParams: ViewGroup.LayoutParams private var usableHeightPrevious = 0 private fun possiblyResizeChildOfContent() { val usableHeightNow = computeUsableHeight() if (usableHeightNow != usableHeightPrevious) { val screenHeight = root.rootView.height val keyboardExpanded: Boolean if (screenHeight - usableHeightNow > screenHeight / 5) { // keyboard probably just became visible. keyboardExpanded = true rootParams.height = usableHeightNow } else { // keyboard probably just became hidden. keyboardExpanded = false rootParams.height = screenHeight } usableHeightPrevious = usableHeightNow root.setFitKeyboardExpanded(keyboardExpanded) } } private fun computeUsableHeight(): Int { val r = Rect() DisplayUtils.getVisibleDisplayFrame(root, r) return r.bottom // - r.top; --> Do not reduce the height of status bar. } companion object { // For more information, see https://issuetracker.google.com/issues/36911528 // To use this class, simply invoke assistActivity() on an Activity that already has its content view set. fun assistActivity(activity: GeoActivity) { KeyboardResizeBugWorkaround(activity) } } init { root.viewTreeObserver.addOnGlobalLayoutListener { possiblyResizeChildOfContent() } rootParams = root.layoutParams } } @CallSuper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) fitHorizontalSystemBarRootLayout = FitHorizontalSystemBarRootLayout(this) GeometricWeather.instance.addActivity(this) LanguageUtils.setLanguage( this, SettingsManager.getInstance(this).language.locale ) DisplayUtils.setSystemBarStyle( this, window, false, !DisplayUtils.isDarkMode(this), true, !DisplayUtils.isDarkMode(this) ) } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) // decor -> fit horizontal system bar -> decor child. val decorView = window.decorView as ViewGroup val decorChild = decorView.getChildAt(0) as ViewGroup decorView.removeView(decorChild) decorView.addView(fitHorizontalSystemBarRootLayout) fitHorizontalSystemBarRootLayout.removeAllViews() fitHorizontalSystemBarRootLayout.addView(decorChild) KeyboardResizeBugWorkaround.assistActivity(this) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) GeometricWeather.instance.setTopActivity(this) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) GeometricWeather.instance.setTopActivity(this) } @CallSuper override fun onResume() { super.onResume() GeometricWeather.instance.setTopActivity(this) } @CallSuper override fun onPause() { super.onPause() GeometricWeather.instance.checkToCleanTopActivity(this) } @CallSuper override fun onDestroy() { super.onDestroy() GeometricWeather.instance.removeActivity(this) } open val snackbarContainer: SnackbarContainer? get() = SnackbarContainer( this, findViewById<ViewGroup>(android.R.id.content).getChildAt(0) as ViewGroup, true ) fun provideSnackbarContainer(): SnackbarContainer? = snackbarContainer val isActivityCreated: Boolean get() = lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED) val isActivityStarted: Boolean get() = lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) val isActivityResumed: Boolean get() = lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED) }
lgpl-3.0
ddc9daa9af948685f5970ced80f37120
33.933775
118
0.677474
5.640642
false
false
false
false
ShadwLink/Shadow-Mapper
src/main/java/nl/shadowlink/tools/io/ByteReader.kt
1
5777
package nl.shadowlink.tools.io import java.io.ByteArrayInputStream import java.nio.ByteBuffer /** * @author Shadow-Link */ class ByteReader( private val stream: ByteArray, private var currentOffset: Int ) { private var system = true private var sysSize = 0 fun readUInt32(): Int { var i = 0 val len = 4 var cnt = 0 val tmp = ByteArray(len) i = currentOffset while (i < currentOffset + len) { tmp[cnt] = stream[i] cnt++ i++ } var accum: Long = 0 i = 0 var shiftBy = 0 while (shiftBy < 32) { accum = accum or ((tmp[i].toInt() and 0xff).toLong() shl shiftBy) i++ shiftBy += 8 } currentOffset += 4 return accum.toInt() } fun readOffset(): Int { val value: Int val offset = readUInt32() value = if (offset == 0) { 0 } else { if (offset shr 28 != 5) { throw IllegalStateException("Expected an offset") } else { offset and 0x0fffffff } } return value } fun readVector4D(): Vector4D { val x = readFloat() val y = readFloat() val z = readFloat() val w = readFloat() return Vector4D(x, y, z, w) } fun readFloat(): Float { var accum = 0 var i = 0 var shiftBy = 0 while (shiftBy < 32) { accum = (accum.toLong() or ((stream[currentOffset + i].toInt() and 0xff).toLong() shl shiftBy)).toInt() i++ shiftBy += 8 } currentOffset += 4 return java.lang.Float.intBitsToFloat(accum) } fun readUInt16(): Int { val low = stream[currentOffset].toInt() and 0xff val high = stream[currentOffset + 1].toInt() and 0xff currentOffset += 2 return (high shl 8 or low) } fun readInt16(): Short { val ret = (stream[currentOffset + 1].toShort().toInt() shl 8 or (stream[currentOffset].toShort() .toInt() and 0xff)).toShort() currentOffset += 2 return ret } fun readDataOffset(): Int { val value: Int val offset = readUInt32() value = if (offset == 0) { 0 } else { if (offset shr 28 != 6) { } offset and 0x0fffffff } return value } /** * Returns a String from the DataInputStream with the given size till 0 * * @param data_in * @param size * @return a String of the size size */ fun readNullTerminatedString(size: Int): String { var woord = "" var gotNull = false for (i in 0 until size) { val b = readByte() if (!gotNull) { if (b.toInt() != 0) woord += Char(b.toUShort()) else gotNull = true } } return woord } fun readNullTerminatedString(): String { var sb = "" var c = Char(stream[currentOffset].toUShort()) while (c.code != 0) { // nl.shadowlink.tools.io.Message.displayMsgHigh("String: " + sb + " c: " + c); sb = sb + c currentOffset++ c = Char(stream[currentOffset].toUShort()) } return sb } fun readString(length: Int): String { var sb = "" for (i in 0 until length) { val c = Char(stream[currentOffset].toUShort()) sb += c currentOffset++ } return sb } fun toArray(bytes: Int): ByteArray { val arr = ByteArray(bytes) for (i in 0 until bytes) { arr[i] = stream[currentOffset] currentOffset++ } return arr } fun toArray(): ByteArray { return stream } fun toArray(start: Int, end: Int): ByteArray { val retSize = end - start val retStream = ByteArray(retSize) setCurrentOffset(start) for (i in 0 until retSize) { retStream[i] = stream[currentOffset] currentOffset++ } return retStream } fun readByte(): Byte { currentOffset++ return stream[currentOffset - 1] } fun getCurrentOffset(): Int { return currentOffset } fun setCurrentOffset(offset: Int) { currentOffset = offset if (!system) { currentOffset += sysSize } } fun setSysSize(size: Int) { sysSize = size } fun setSystemMemory(system: Boolean) { this.system = system } fun getByteBuffer(size: Int): ByteBuffer { val buffer = ByteArray(size) val bbuf = ByteBuffer.allocate(size) for (i in 0 until size) { buffer[i] = readByte() } bbuf.put(buffer) bbuf.rewind() return bbuf } fun readBytes(pCount: Int): ByteArray { val buffer = ByteArray(pCount) for (i in 0 until pCount) { buffer[i] = readByte() } return buffer } val inputStream: ByteArrayInputStream get() = ByteArrayInputStream(stream, currentOffset, stream.size - currentOffset) fun skipBytes(bytes: Int) { currentOffset += bytes } /** * returns if a certain flag is on * * @param flags * @param flag * @return if a flag has been set */ fun hasFlag(flags: Int, flag: Int): Boolean { return flags and flag == flag } fun moreToRead(): Int { return stream.size - currentOffset } fun unsignedInt(): Long { val i = readUInt32() return i.toLong() and 0xffffffffL } }
gpl-2.0
9bda15a980b34fee2e8907d0aea4a76a
23.483051
115
0.513069
4.389818
false
false
false
false
Heiner1/AndroidAPS
medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt
1
57733
package info.nightscout.androidaps.plugins.pump.medtronic import android.content.ComponentName import android.content.Context import android.content.ServiceConnection import android.os.IBinder import android.os.SystemClock import androidx.preference.Preference import dagger.android.HasAndroidInjector import info.nightscout.androidaps.activities.ErrorHelperActivity.Companion.runAlarm import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.interfaces.PumpSync.TemporaryBasalType import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.common.events.EventRefreshButtonState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpDevice import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpInfo import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ResetRileyLinkConfigurationTask import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.WakeAndTuneTask import info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntryTBR import info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncEntriesCreator import info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncStorage import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil import info.nightscout.androidaps.plugins.pump.common.utils.ProfileUtil import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryResult import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile.Companion.getProfilesByHourToString import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfileEntry import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.TempBasalPair import info.nightscout.androidaps.plugins.pump.medtronic.defs.* import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType.Companion.getSettings import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpConfigurationChanged import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpValuesChanged import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil.Companion.isSame import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.TimeChangeType import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import org.joda.time.LocalDateTime import java.util.* import javax.inject.Inject import javax.inject.Singleton import kotlin.math.abs import kotlin.math.floor /** * Created by andy on 23.04.18. * * @author Andy Rozman ([email protected]) */ @Singleton class MedtronicPumpPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, rxBus: RxBus, context: Context, rh: ResourceHelper, activePlugin: ActivePlugin, sp: SP, commandQueue: CommandQueue, fabricPrivacy: FabricPrivacy, private val medtronicUtil: MedtronicUtil, private val medtronicPumpStatus: MedtronicPumpStatus, private val medtronicHistoryData: MedtronicHistoryData, private val rileyLinkServiceData: RileyLinkServiceData, private val serviceTaskExecutor: ServiceTaskExecutor, dateUtil: DateUtil, aapsSchedulers: AapsSchedulers, pumpSync: PumpSync, pumpSyncStorage: PumpSyncStorage ) : PumpPluginAbstract( PluginDescription() // .mainType(PluginType.PUMP) // .fragmentClass(MedtronicFragment::class.java.name) // .pluginIcon(R.drawable.ic_veo_128) .pluginName(R.string.medtronic_name) // .shortName(R.string.medtronic_name_short) // .preferencesId(R.xml.pref_medtronic) .description(R.string.description_pump_medtronic), // PumpType.MEDTRONIC_522_722, // we default to most basic model, correct model from config is loaded later injector, rh, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil, aapsSchedulers, pumpSync, pumpSyncStorage ), Pump, RileyLinkPumpDevice, PumpSyncEntriesCreator { private var rileyLinkMedtronicService: RileyLinkMedtronicService? = null // variables for handling statuses and history private var firstRun = true private var isRefresh = false private val statusRefreshMap: MutableMap<MedtronicStatusRefreshType, Long> = mutableMapOf() private var isInitialized = false private var lastPumpHistoryEntry: PumpHistoryEntry? = null private val busyTimestamps: MutableList<Long> = ArrayList() private var hasTimeDateOrTimeZoneChanged = false private var isBusy = false override fun onStart() { aapsLogger.debug(LTag.PUMP, deviceID() + " started. (V2.0006)") serviceConnection = object : ServiceConnection { override fun onServiceDisconnected(name: ComponentName) { aapsLogger.debug(LTag.PUMP, "RileyLinkMedtronicService is disconnected") //rileyLinkMedtronicService = null } override fun onServiceConnected(name: ComponentName, service: IBinder) { aapsLogger.debug(LTag.PUMP, "RileyLinkMedtronicService is connected") val mLocalBinder = service as RileyLinkMedtronicService.LocalBinder rileyLinkMedtronicService = mLocalBinder.serviceInstance isServiceSet = true rileyLinkMedtronicService?.verifyConfiguration() Thread { for (i in 0..19) { SystemClock.sleep(5000) aapsLogger.debug(LTag.PUMP, "Starting Medtronic-RileyLink service") if (rileyLinkMedtronicService?.setNotInPreInit() == true) { break } } }.start() } } super.onStart() } override fun updatePreferenceSummary(pref: Preference) { super.updatePreferenceSummary(pref) if (pref.key == rh.gs(R.string.key_rileylink_mac_address)) { val value = sp.getStringOrNull(R.string.key_rileylink_mac_address, null) pref.summary = value ?: rh.gs(R.string.not_set_short) } } private val logPrefix: String get() = "MedtronicPumpPlugin::" override fun initPumpStatusData() { medtronicPumpStatus.lastConnection = sp.getLong(RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L) medtronicPumpStatus.lastDataTime = medtronicPumpStatus.lastConnection medtronicPumpStatus.previousConnection = medtronicPumpStatus.lastConnection //if (rileyLinkMedtronicService != null) rileyLinkMedtronicService.verifyConfiguration(); aapsLogger.debug(LTag.PUMP, "initPumpStatusData: $medtronicPumpStatus") // this is only thing that can change, by being configured pumpDescription.maxTempAbsolute = if (medtronicPumpStatus.maxBasal != null) medtronicPumpStatus.maxBasal!! else 35.0 // set first Medtronic Pump Start if (!sp.contains(MedtronicConst.Statistics.FirstPumpStart)) { sp.putLong(MedtronicConst.Statistics.FirstPumpStart, System.currentTimeMillis()) } migrateSettings() pumpSyncStorage.initStorage() this.displayConnectionMessages = false } override fun triggerPumpConfigurationChangedEvent() { rxBus.send(EventMedtronicPumpConfigurationChanged()) } private fun migrateSettings() { if ("US (916 MHz)" == sp.getString(MedtronicConst.Prefs.PumpFrequency, "US (916 MHz)")) { sp.putString(MedtronicConst.Prefs.PumpFrequency, rh.gs(R.string.key_medtronic_pump_frequency_us_ca)) } val encoding = sp.getString(MedtronicConst.Prefs.Encoding, "RileyLink 4b6b Encoding") if ("RileyLink 4b6b Encoding" == encoding) { sp.putString(MedtronicConst.Prefs.Encoding, rh.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink)) } if ("Local 4b6b Encoding" == encoding) { sp.putString(MedtronicConst.Prefs.Encoding, rh.gs(R.string.key_medtronic_pump_encoding_4b6b_local)) } } override fun hasService(): Boolean { return true } override fun onStartScheduledPumpActions() { // check status every minute (if any status needs refresh we send readStatus command) Thread { do { SystemClock.sleep(60000) if (this.isInitialized) { val statusRefresh = synchronized(statusRefreshMap) { HashMap(statusRefreshMap) } if (doWeHaveAnyStatusNeededRefreshing(statusRefresh)) { if (!commandQueue.statusInQueue()) { commandQueue.readStatus(rh.gs(R.string.scheduled_status_refresh), null) } } clearBusyQueue() } } while (serviceRunning) }.start() } override val serviceClass: Class<*> = RileyLinkMedtronicService::class.java override val pumpStatusData: PumpStatus get() = medtronicPumpStatus override fun deviceID(): String = "Medtronic" override val isFakingTempsByExtendedBoluses: Boolean = false override fun canHandleDST(): Boolean = false private var isServiceSet: Boolean = false override val rileyLinkService: RileyLinkMedtronicService? get() = rileyLinkMedtronicService override val pumpInfo: RileyLinkPumpInfo get() = RileyLinkPumpInfo( rh.gs(if (medtronicPumpStatus.pumpFrequency == "medtronic_pump_frequency_us_ca") R.string.medtronic_pump_frequency_us_ca else R.string.medtronic_pump_frequency_worldwide), if (!medtronicUtil.isModelSet) "???" else "Medtronic " + medtronicPumpStatus.medtronicDeviceType.pumpModel, medtronicPumpStatus.serialNumber ) override val lastConnectionTimeMillis: Long get() = medtronicPumpStatus.lastConnection override fun setLastCommunicationToNow() { medtronicPumpStatus.setLastCommunicationToNow() } override fun isInitialized(): Boolean { if (displayConnectionMessages) aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::isInitialized") return isServiceSet && isInitialized } override fun setBusy(busy: Boolean) { isBusy = busy } override fun isBusy(): Boolean { if (displayConnectionMessages) aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::isBusy") if (isServiceSet) { if (isBusy) return true if (busyTimestamps.size > 0) { clearBusyQueue() return busyTimestamps.size > 0 } } return false } @Synchronized private fun clearBusyQueue() { if (busyTimestamps.size == 0) { return } val deleteFromQueue: MutableSet<Long> = HashSet() for (busyTimestamp in busyTimestamps) { if (System.currentTimeMillis() > busyTimestamp) { deleteFromQueue.add(busyTimestamp) } } if (deleteFromQueue.size == busyTimestamps.size) { busyTimestamps.clear() setEnableCustomAction(MedtronicCustomActionType.ClearBolusBlock, false) } if (deleteFromQueue.size > 0) { busyTimestamps.removeAll(deleteFromQueue) } } override fun isConnected(): Boolean { if (displayConnectionMessages) aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::isConnected") return isServiceSet && rileyLinkMedtronicService?.isInitialized == true } override fun isConnecting(): Boolean { if (displayConnectionMessages) aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::isConnecting") return !isServiceSet || rileyLinkMedtronicService?.isInitialized != true } override fun getPumpStatus(reason: String) { var needRefresh = true if (firstRun) { needRefresh = initializePump() /*!isRefresh*/ } else { refreshAnyStatusThatNeedsToBeRefreshed() } if (needRefresh) rxBus.send(EventMedtronicPumpValuesChanged()) } fun resetStatusState() { firstRun = true isRefresh = true }// private val isPumpNotReachable: Boolean get() { val rileyLinkServiceState = rileyLinkServiceData.rileyLinkServiceState if (rileyLinkServiceState != RileyLinkServiceState.PumpConnectorReady && rileyLinkServiceState != RileyLinkServiceState.RileyLinkReady && rileyLinkServiceState != RileyLinkServiceState.TuneUpDevice ) { aapsLogger.debug(LTag.PUMP, "RileyLink unreachable.") return false } return rileyLinkMedtronicService?.deviceCommunicationManager?.isDeviceReachable != true } private fun refreshAnyStatusThatNeedsToBeRefreshed() { val statusRefresh = synchronized(statusRefreshMap) { HashMap(statusRefreshMap) } if (!doWeHaveAnyStatusNeededRefreshing(statusRefresh)) { return } var resetTime = false if (isPumpNotReachable) { aapsLogger.error("Pump unreachable.") medtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable, rh, rxBus) return } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) if (hasTimeDateOrTimeZoneChanged) { checkTimeAndOptionallySetTime() // read time if changed, set new time hasTimeDateOrTimeZoneChanged = false } // execute val refreshTypesNeededToReschedule: MutableSet<MedtronicStatusRefreshType> = mutableSetOf() for ((key, value) in statusRefresh) { if (value > 0 && System.currentTimeMillis() > value) { @Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") when (key) { MedtronicStatusRefreshType.PumpHistory -> { readPumpHistory() } MedtronicStatusRefreshType.PumpTime -> { checkTimeAndOptionallySetTime() refreshTypesNeededToReschedule.add(key) resetTime = true } MedtronicStatusRefreshType.BatteryStatus, MedtronicStatusRefreshType.RemainingInsulin -> { rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(key.getCommandType(medtronicUtil.medtronicPumpModel)!!) refreshTypesNeededToReschedule.add(key) resetTime = true } MedtronicStatusRefreshType.Configuration -> { rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(key.getCommandType(medtronicUtil.medtronicPumpModel)!!) resetTime = true } } } // reschedule for (refreshType2 in refreshTypesNeededToReschedule) { scheduleNextRefresh(refreshType2) } } if (resetTime) medtronicPumpStatus.setLastCommunicationToNow() } private fun doWeHaveAnyStatusNeededRefreshing(statusRefresh: Map<MedtronicStatusRefreshType, Long>): Boolean { for ((_, value) in statusRefresh) { if (value > 0 && System.currentTimeMillis() > value) { return true } } return hasTimeDateOrTimeZoneChanged } private fun setRefreshButtonEnabled(enabled: Boolean) { rxBus.send(EventRefreshButtonState(enabled)) } private fun initializePump(): Boolean { if (!isServiceSet) return false aapsLogger.info(LTag.PUMP, logPrefix + "initializePump - start") rileyLinkMedtronicService?.deviceCommunicationManager?.setDoWakeUpBeforeCommand(false) setRefreshButtonEnabled(false) if (isRefresh) { if (isPumpNotReachable) { aapsLogger.error(logPrefix + "initializePump::Pump unreachable.") medtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable, rh, rxBus) setRefreshButtonEnabled(true) return true } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) } // model (once) if (!medtronicUtil.isModelSet) { rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.PumpModel) } else { if (medtronicPumpStatus.medtronicDeviceType !== medtronicUtil.medtronicPumpModel) { aapsLogger.warn(LTag.PUMP, logPrefix + "Configured pump is not the same as one detected.") medtronicUtil.sendNotification(MedtronicNotificationType.PumpTypeNotSame, rh, rxBus) } } pumpState = PumpDriverState.Connected // time (1h) checkTimeAndOptionallySetTime() readPumpHistory() // remaining insulin (>50 = 4h; 50-20 = 1h; 15m) rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.GetRemainingInsulin) scheduleNextRefresh(MedtronicStatusRefreshType.RemainingInsulin, 10) // remaining power (1h) rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.GetBatteryStatus) scheduleNextRefresh(MedtronicStatusRefreshType.BatteryStatus, 20) // configuration (once and then if history shows config changes) rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(getSettings(medtronicUtil.medtronicPumpModel)) // read profile (once, later its controlled by isThisProfileSet method) basalProfiles val errorCount = rileyLinkMedtronicService?.medtronicUIComm?.invalidResponsesCount ?: 0 if (errorCount >= 5) { aapsLogger.error("Number of error counts was 5 or more. Starting tuning.") setRefreshButtonEnabled(true) serviceTaskExecutor.startTask(WakeAndTuneTask(injector)) return true } medtronicPumpStatus.setLastCommunicationToNow() setRefreshButtonEnabled(true) if (!isRefresh) { pumpState = PumpDriverState.Initialized } isInitialized = true // this.pumpState = PumpDriverState.Initialized; firstRun = false return true } private val basalProfiles: Unit get() { val medtronicUITask = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.GetBasalProfileSTD) if (medtronicUITask?.responseType === MedtronicUIResponseType.Error) { rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.GetBasalProfileSTD) } } @Synchronized override fun isThisProfileSet(profile: Profile): Boolean { aapsLogger.debug(LTag.PUMP, "isThisProfileSet: basalInitialized=" + medtronicPumpStatus.basalProfileStatus) if (!isInitialized) return true if (medtronicPumpStatus.basalProfileStatus === BasalProfileStatus.NotInitialized) { // this shouldn't happen, but if there was problem we try again basalProfiles return isProfileSame(profile) } else if (medtronicPumpStatus.basalProfileStatus === BasalProfileStatus.ProfileChanged) { return false } return medtronicPumpStatus.basalProfileStatus !== BasalProfileStatus.ProfileOK || isProfileSame(profile) } private fun isProfileSame(profile: Profile): Boolean { var invalid = false val basalsByHour: DoubleArray? = medtronicPumpStatus.basalsByHour aapsLogger.debug( LTag.PUMP, "Current Basals (h): " + (basalsByHour?.let { getProfilesByHourToString(it) } ?: "null")) // int index = 0; if (basalsByHour == null) return true // we don't want to set profile again, unless we are sure val stringBuilder = StringBuilder("Requested Basals (h): ") stringBuilder.append(ProfileUtil.getBasalProfilesDisplayableAsStringOfArray(profile, this.pumpType)) for (basalValue in profile.getBasalValues()) { val basalValueValue = pumpDescription.pumpType.determineCorrectBasalSize(basalValue.value) val hour = basalValue.timeAsSeconds / (60 * 60) if (!isSame(basalsByHour[hour], basalValueValue)) { invalid = true } // stringBuilder.append(String.format(Locale.ENGLISH, "%.3f", basalValueValue)) // stringBuilder.append(" ") } aapsLogger.debug(LTag.PUMP, stringBuilder.toString()) if (!invalid) { aapsLogger.debug(LTag.PUMP, "Basal profile is same as AAPS one.") } else { aapsLogger.debug(LTag.PUMP, "Basal profile on Pump is different than the AAPS one.") } return !invalid } override fun lastDataTime(): Long { return if (medtronicPumpStatus.lastConnection > 0) { medtronicPumpStatus.lastConnection } else System.currentTimeMillis() } override val baseBasalRate: Double get() = medtronicPumpStatus.basalProfileForHour override val reservoirLevel: Double get() = medtronicPumpStatus.reservoirRemainingUnits override val batteryLevel: Int get() = medtronicPumpStatus.batteryRemaining override fun triggerUIChange() { rxBus.send(EventMedtronicPumpValuesChanged()) } override fun generateTempId(objectA: Any): Long { val timestamp: Long = objectA as Long return DateTimeUtil.toATechDate(timestamp) } private var bolusDeliveryType = BolusDeliveryType.Idle private enum class BolusDeliveryType { Idle, // DeliveryPrepared, // Delivering, // CancelDelivery } private fun checkTimeAndOptionallySetTime() { aapsLogger.info(LTag.PUMP, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Start") setRefreshButtonEnabled(false) if (isPumpNotReachable) { aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Pump Unreachable.") setRefreshButtonEnabled(true) return } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.GetRealTimeClock) var clock = medtronicUtil.pumpTime if (clock == null) { // retry rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.GetRealTimeClock) clock = medtronicUtil.pumpTime } if (clock == null) return val timeDiff = abs(clock.timeDifference) if (timeDiff > 20) { if (clock.localDeviceTime.year <= 2015 || timeDiff <= 24 * 60 * 60) { aapsLogger.info(LTag.PUMP, String.format(Locale.ENGLISH, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference is %d s. Set time on pump.", timeDiff)) rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.SetRealTimeClock) if (clock.timeDifference == 0) { val notification = Notification(Notification.INSIGHT_DATE_TIME_UPDATED, rh.gs(R.string.pump_time_updated), Notification.INFO, 60) rxBus.send(EventNewNotification(notification)) } } else { if (clock.localDeviceTime.year > 2015) { aapsLogger.error(String.format(Locale.ENGLISH, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference over 24h requested [diff=%d s]. Doing nothing.", timeDiff)) medtronicUtil.sendNotification(MedtronicNotificationType.TimeChangeOver24h, rh, rxBus) } } } else { aapsLogger.info(LTag.PUMP, String.format(Locale.ENGLISH, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference is %d s. Do nothing.", timeDiff)) } scheduleNextRefresh(MedtronicStatusRefreshType.PumpTime, 0) } @Synchronized override fun deliverBolus(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult { aapsLogger.info(LTag.PUMP, "MedtronicPumpPlugin::deliverBolus - " + BolusDeliveryType.DeliveryPrepared) setRefreshButtonEnabled(false) if (detailedBolusInfo.insulin > medtronicPumpStatus.reservoirRemainingUnits) { return PumpEnactResult(injector) // .success(false) // .enacted(false) // .comment( rh.gs( R.string.medtronic_cmd_bolus_could_not_be_delivered_no_insulin, medtronicPumpStatus.reservoirRemainingUnits, detailedBolusInfo.insulin ) ) } bolusDeliveryType = BolusDeliveryType.DeliveryPrepared if (isPumpNotReachable) { aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::deliverBolus - Pump Unreachable.") return setNotReachable(isBolus = true, success = false) } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) if (bolusDeliveryType == BolusDeliveryType.CancelDelivery) { // LOG.debug("MedtronicPumpPlugin::deliverBolus - Delivery Canceled."); return setNotReachable(isBolus = true, success = true) } // LOG.debug("MedtronicPumpPlugin::deliverBolus - Starting wait period."); val sleepTime = sp.getInt(MedtronicConst.Prefs.BolusDelay, 10) * 1000 SystemClock.sleep(sleepTime.toLong()) return if (bolusDeliveryType == BolusDeliveryType.CancelDelivery) { // LOG.debug("MedtronicPumpPlugin::deliverBolus - Delivery Canceled, before wait period."); setNotReachable(isBolus = true, success = true) } else try { bolusDeliveryType = BolusDeliveryType.Delivering // LOG.debug("MedtronicPumpPlugin::deliverBolus - Start delivery"); val responseTask = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand( MedtronicCommandType.SetBolus, arrayListOf(detailedBolusInfo.insulin) ) val response = responseTask?.result as Boolean? setRefreshButtonEnabled(true) // LOG.debug("MedtronicPumpPlugin::deliverBolus - Response: {}", response); return if (response == null || !response) { PumpEnactResult(injector) // .success(bolusDeliveryType == BolusDeliveryType.CancelDelivery) // .enacted(false) // .comment(R.string.medtronic_cmd_bolus_could_not_be_delivered) } else { if (bolusDeliveryType == BolusDeliveryType.CancelDelivery) { // LOG.debug("MedtronicPumpPlugin::deliverBolus - Delivery Canceled after Bolus started."); Thread { SystemClock.sleep(2000) runAlarm(context, rh.gs(R.string.medtronic_cmd_cancel_bolus_not_supported), rh.gs(R.string.medtronic_warning), R.raw.boluserror) }.start() } val now = System.currentTimeMillis() detailedBolusInfo.timestamp = now pumpSyncStorage.addBolusWithTempId(detailedBolusInfo, true, this) // we subtract insulin, exact amount will be visible with next remainingInsulin update. medtronicPumpStatus.reservoirRemainingUnits = medtronicPumpStatus.reservoirRemainingUnits - detailedBolusInfo.insulin incrementStatistics(if (detailedBolusInfo.bolusType === DetailedBolusInfo.BolusType.SMB) MedtronicConst.Statistics.SMBBoluses else MedtronicConst.Statistics.StandardBoluses) // calculate time for bolus and set driver to busy for that time val bolusTime = (detailedBolusInfo.insulin * 42.0).toInt() val time = now + bolusTime * 1000 busyTimestamps.add(time) setEnableCustomAction(MedtronicCustomActionType.ClearBolusBlock, true) PumpEnactResult(injector).success(true) // .enacted(true) // .bolusDelivered(detailedBolusInfo.insulin) // .carbsDelivered(detailedBolusInfo.carbs) } } finally { finishAction("Bolus") bolusDeliveryType = BolusDeliveryType.Idle } // LOG.debug("MedtronicPumpPlugin::deliverBolus - End wait period. Start delivery"); } @Suppress("SameParameterValue") private fun setNotReachable(isBolus: Boolean, success: Boolean): PumpEnactResult { setRefreshButtonEnabled(true) if (isBolus) bolusDeliveryType = BolusDeliveryType.Idle return if (success) PumpEnactResult(injector).success(true).enacted(false) else PumpEnactResult(injector).success(false).enacted(false).comment(R.string.medtronic_pump_status_pump_unreachable) } override fun stopBolusDelivering() { bolusDeliveryType = BolusDeliveryType.CancelDelivery // if (isLoggingEnabled()) // LOG.warn("MedtronicPumpPlugin::deliverBolus - Stop Bolus Delivery."); } private fun incrementStatistics(statsKey: String) { var currentCount = sp.getLong(statsKey, 0L) currentCount++ sp.putLong(statsKey, currentCount) } // if enforceNew===true current temp basal is canceled and new TBR set (duration is prolonged), // if false and the same rate is requested enacted=false and success=true is returned and TBR is not changed @Synchronized override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: TemporaryBasalType): PumpEnactResult { setRefreshButtonEnabled(false) if (isPumpNotReachable) { setRefreshButtonEnabled(true) return PumpEnactResult(injector) // .success(false) // .enacted(false) // .comment(R.string.medtronic_pump_status_pump_unreachable) } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute: rate: " + absoluteRate + ", duration=" + durationInMinutes) // read current TBR val tbrCurrent = readTBR() if (tbrCurrent == null) { aapsLogger.warn(LTag.PUMP, logPrefix + "setTempBasalAbsolute - Could not read current TBR, canceling operation.") finishAction("TBR") return PumpEnactResult(injector).success(false).enacted(false) .comment(R.string.medtronic_cmd_cant_read_tbr) } else { aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute: Current Basal: duration: " + tbrCurrent.durationMinutes + " min, rate=" + tbrCurrent.insulinRate) } if (!enforceNew) { if (isSame(tbrCurrent.insulinRate, absoluteRate)) { var sameRate = true if (isSame(0.0, absoluteRate) && durationInMinutes > 0) { // if rate is 0.0 and duration>0 then the rate is not the same sameRate = false } if (sameRate) { aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute - No enforceNew and same rate. Exiting.") finishAction("TBR") return PumpEnactResult(injector).success(true).enacted(false) } } // if not the same rate, we cancel and start new } // if TBR is running we will cancel it. if (tbrCurrent.insulinRate > 0.0 && tbrCurrent.durationMinutes > 0) { aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute - TBR running - so canceling it.") // CANCEL val responseTask2 = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.CancelTBR) val response = responseTask2?.result as Boolean? if (response == null || !response) { aapsLogger.error(logPrefix + "setTempBasalAbsolute - Cancel TBR failed.") finishAction("TBR") return PumpEnactResult(injector).success(false).enacted(false) .comment(R.string.medtronic_cmd_cant_cancel_tbr_stop_op) } else { //cancelTBRWithTemporaryId() aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute - Current TBR cancelled.") } } // now start new TBR val responseTask = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand( MedtronicCommandType.SetTemporaryBasal, arrayListOf(absoluteRate, durationInMinutes) ) val response = responseTask?.result as Boolean? aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute - setTBR. Response: " + response) return if (response == null || !response) { finishAction("TBR") PumpEnactResult(injector).success(false).enacted(false) // .comment(R.string.medtronic_cmd_tbr_could_not_be_delivered) } else { medtronicPumpStatus.tempBasalStart = System.currentTimeMillis() medtronicPumpStatus.tempBasalAmount = absoluteRate medtronicPumpStatus.tempBasalLength = durationInMinutes val tempData = PumpDbEntryTBR(absoluteRate, true, durationInMinutes * 60, tbrType) medtronicPumpStatus.runningTBRWithTemp = tempData pumpSyncStorage.addTemporaryBasalRateWithTempId(tempData, true, this) incrementStatistics(MedtronicConst.Statistics.TBRsSet) finishAction("TBR") PumpEnactResult(injector).success(true).enacted(true) // .absolute(absoluteRate).duration(durationInMinutes) } } @Deprecated("Not used, TBRs fixed in history, should be removed.") private fun cancelTBRWithTemporaryId() { val tbrs: MutableList<PumpDbEntryTBR> = pumpSyncStorage.getTBRs() if (tbrs.size > 0 && medtronicPumpStatus.runningTBRWithTemp != null) { aapsLogger.info(LTag.PUMP, logPrefix + "cancelTBRWithTemporaryId - TBR items: ${tbrs.size}") var item: PumpDbEntryTBR? = null if (tbrs.size == 1) { item = tbrs[0] } else { for (tbr in tbrs) { if (tbr.date == medtronicPumpStatus.runningTBRWithTemp!!.date) { item = tbr break } } } if (item != null) { aapsLogger.debug(LTag.PUMP, "DD: cancelTBRWithTemporaryId: tempIdEntry=${item}") val differenceS = (System.currentTimeMillis() - item.date) / 1000 aapsLogger.debug( LTag.PUMP, "syncTemporaryBasalWithTempId " + "[date=${item.date}, " + "rate=${item.rate}, " + "duration=${differenceS} s, " + "isAbsolute=${!item.isAbsolute}, temporaryId=${item.temporaryId}, " + "pumpId=NO, pumpType=${medtronicPumpStatus.pumpType}, " + "pumpSerial=${medtronicPumpStatus.serialNumber}]" ) val result = pumpSync.syncTemporaryBasalWithTempId( timestamp = item.date, rate = item.rate, duration = differenceS * 1000L, isAbsolute = item.isAbsolute, temporaryId = item.temporaryId, type = item.tbrType, pumpId = null, pumpType = medtronicPumpStatus.pumpType, pumpSerial = medtronicPumpStatus.serialNumber ) aapsLogger.debug(LTag.PUMP, "syncTemporaryBasalWithTempId - Result: $result") } } else { aapsLogger.info(LTag.PUMP, logPrefix + "cancelTBRWithTemporaryId - TBR items: ${tbrs.size}, runningTBRWithTemp=${medtronicPumpStatus.runningTBRWithTemp}") } if (medtronicPumpStatus.runningTBRWithTemp != null) { medtronicPumpStatus.runningTBRWithTemp = null } } @Synchronized override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: TemporaryBasalType): PumpEnactResult { return if (percent == 0) { setTempBasalAbsolute(0.0, durationInMinutes, profile, enforceNew, tbrType) } else { var absoluteValue = profile.getBasal() * (percent / 100.0) absoluteValue = pumpDescription.pumpType.determineCorrectBasalSize(absoluteValue) aapsLogger.warn( LTag.PUMP, "setTempBasalPercent [MedtronicPumpPlugin] - You are trying to use setTempBasalPercent with percent other then 0% ($percent). This will start setTempBasalAbsolute, with calculated value ($absoluteValue). Result might not be 100% correct." ) setTempBasalAbsolute(absoluteValue, durationInMinutes, profile, enforceNew, tbrType) } } private fun finishAction(overviewKey: String?) { if (overviewKey != null) rxBus.send(EventRefreshOverview(overviewKey, false)) triggerUIChange() setRefreshButtonEnabled(true) } private fun readPumpHistory() { // if (isLoggingEnabled()) // LOG.error(getLogPrefix() + "readPumpHistory WIP."); readPumpHistoryLogic() scheduleNextRefresh(MedtronicStatusRefreshType.PumpHistory) if (medtronicHistoryData.hasRelevantConfigurationChanged()) { scheduleNextRefresh(MedtronicStatusRefreshType.Configuration, -1) } if (medtronicHistoryData.hasPumpTimeChanged()) { scheduleNextRefresh(MedtronicStatusRefreshType.PumpTime, -1) } if (medtronicPumpStatus.basalProfileStatus !== BasalProfileStatus.NotInitialized && medtronicHistoryData.hasBasalProfileChanged() ) { medtronicHistoryData.processLastBasalProfileChange(pumpDescription.pumpType, medtronicPumpStatus) } val previousState = pumpState if (medtronicHistoryData.isPumpSuspended()) { pumpState = PumpDriverState.Suspended aapsLogger.debug(LTag.PUMP, logPrefix + "isPumpSuspended: true") } else { if (previousState === PumpDriverState.Suspended) { pumpState = PumpDriverState.Ready } aapsLogger.debug(LTag.PUMP, logPrefix + "isPumpSuspended: false") } medtronicHistoryData.processNewHistoryData() medtronicHistoryData.finalizeNewHistoryRecords() } private fun readPumpHistoryLogic() { val debugHistory = false val targetDate: LocalDateTime? if (lastPumpHistoryEntry == null) { // first read if (debugHistory) aapsLogger.debug(LTag.PUMP, logPrefix + "readPumpHistoryLogic(): lastPumpHistoryEntry: null") val lastPumpHistoryEntryTime = lastPumpEntryTime var timeMinus36h = LocalDateTime() timeMinus36h = timeMinus36h.minusHours(36) medtronicHistoryData.setIsInInit(true) if (lastPumpHistoryEntryTime == 0L) { if (debugHistory) aapsLogger.debug(LTag.PUMP, logPrefix + "readPumpHistoryLogic(): lastPumpHistoryEntryTime: 0L") targetDate = timeMinus36h } else { // LocalDateTime lastHistoryRecordTime = DateTimeUtil.toLocalDateTime(lastPumpHistoryEntryTime); if (debugHistory) aapsLogger.debug(LTag.PUMP, logPrefix + "readPumpHistoryLogic(): lastPumpHistoryEntryTime: " + lastPumpHistoryEntryTime) //medtronicHistoryData.setLastHistoryRecordTime(lastPumpHistoryEntryTime) var lastHistoryRecordTime = DateTimeUtil.toLocalDateTime(lastPumpHistoryEntryTime) lastHistoryRecordTime = lastHistoryRecordTime.minusHours(12) // we get last 12 hours of history to // determine pump state // (we don't process that data), we process only targetDate = if (timeMinus36h.isAfter(lastHistoryRecordTime)) timeMinus36h else lastHistoryRecordTime if (debugHistory) aapsLogger.debug(LTag.PUMP, logPrefix + "readPumpHistoryLogic(): targetDate: " + targetDate) } } else { // all other reads if (debugHistory) aapsLogger.debug(LTag.PUMP, logPrefix + "readPumpHistoryLogic(): lastPumpHistoryEntry: not null - " + medtronicUtil.gsonInstance.toJson(lastPumpHistoryEntry)) medtronicHistoryData.setIsInInit(false) // we need to read 35 minutes in the past so that we can repair any TBR or Bolus values if needed targetDate = LocalDateTime(DateTimeUtil.getMillisFromATDWithAddedMinutes(lastPumpHistoryEntry!!.atechDateTime, -35)) } //aapsLogger.debug(LTag.PUMP, "HST: Target Date: " + targetDate); @Suppress("UNCHECKED_CAST") val responseTask2 = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand( MedtronicCommandType.GetHistoryData, arrayListOf(/*lastPumpHistoryEntry*/ null, targetDate) as? ArrayList<Any>? ) if (debugHistory) aapsLogger.debug(LTag.PUMP, "HST: After task") val historyResult = responseTask2?.result as PumpHistoryResult? if (debugHistory) aapsLogger.debug(LTag.PUMP, "HST: History Result: " + historyResult.toString()) val latestEntry = historyResult!!.latestEntry if (debugHistory) aapsLogger.debug(LTag.PUMP, logPrefix + "Last entry: " + latestEntry) if (latestEntry == null) // no new history to read return lastPumpHistoryEntry = latestEntry sp.putLong(MedtronicConst.Statistics.LastPumpHistoryEntry, latestEntry.atechDateTime) if (debugHistory) aapsLogger.debug(LTag.PUMP, "HST: History: valid=" + historyResult.validEntries.size + ", unprocessed=" + historyResult.unprocessedEntries.size) medtronicHistoryData.addNewHistory(historyResult) medtronicHistoryData.filterNewEntries() // determine if first run, if yes determine how much of update do we need // - first run: // - get last history entry // - if not there download 1.5 days of data // - there: check if last entry is older than 1.5 days // - yes: download 1.5 days // - no: download with last entry TODO 5min // - not there: download 1.5 days // // upload all new entries to NightScout (TBR, Bolus) // determine pump status // save last entry // // - not first run: // - update to last entry TODO 5min // - save // - determine pump status } private val lastPumpEntryTime: Long get() { val lastPumpEntryTime = sp.getLong(MedtronicConst.Statistics.LastPumpHistoryEntry, 0L) return try { val localDateTime = DateTimeUtil.toLocalDateTime(lastPumpEntryTime) if (localDateTime.year != GregorianCalendar()[Calendar.YEAR]) { aapsLogger.warn(LTag.PUMP, "Saved LastPumpHistoryEntry was invalid. Year was not the same.") return 0L } lastPumpEntryTime } catch (ex: Exception) { aapsLogger.warn(LTag.PUMP, "Saved LastPumpHistoryEntry was invalid.") 0L } } private fun scheduleNextRefresh(refreshType: MedtronicStatusRefreshType, additionalTimeInMinutes: Int = 0) { when (refreshType) { MedtronicStatusRefreshType.RemainingInsulin -> { val remaining = medtronicPumpStatus.reservoirRemainingUnits val min: Int = if (remaining > 50) 4 * 60 else if (remaining > 20) 60 else 15 synchronized(statusRefreshMap) { statusRefreshMap[refreshType] = getTimeInFutureFromMinutes(min) } } MedtronicStatusRefreshType.PumpTime, MedtronicStatusRefreshType.Configuration, MedtronicStatusRefreshType.BatteryStatus, MedtronicStatusRefreshType.PumpHistory -> { synchronized(statusRefreshMap) { statusRefreshMap[refreshType] = getTimeInFutureFromMinutes(refreshType.refreshTime + additionalTimeInMinutes) } } } } private fun getTimeInFutureFromMinutes(minutes: Int): Long { return System.currentTimeMillis() + getTimeInMs(minutes) } private fun getTimeInMs(minutes: Int): Long { return minutes * 60 * 1000L } private fun readTBR(): TempBasalPair? { val responseTask = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.ReadTemporaryBasal) return if (responseTask?.hasData() == true) { val tbr = responseTask.result as TempBasalPair? // we sometimes get rate returned even if TBR is no longer running if (tbr != null) { if (tbr.durationMinutes == 0) { tbr.insulinRate = 0.0 } tbr } else null } else { null } } @Synchronized override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult { aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - started") if (isPumpNotReachable) { setRefreshButtonEnabled(true) return PumpEnactResult(injector) // .success(false) // .enacted(false) // .comment(R.string.medtronic_pump_status_pump_unreachable) } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) setRefreshButtonEnabled(false) val tbrCurrent = readTBR() if (tbrCurrent != null) { if (tbrCurrent.insulinRate > 0.0f && tbrCurrent.durationMinutes == 0) { aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - TBR already canceled.") finishAction("TBR") return PumpEnactResult(injector).success(true).enacted(false) } } else { aapsLogger.warn(LTag.PUMP, logPrefix + "cancelTempBasal - Could not read current TBR, canceling operation.") finishAction("TBR") return PumpEnactResult(injector).success(false).enacted(false) .comment(R.string.medtronic_cmd_cant_read_tbr) } val responseTask2 = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.CancelTBR) val response = responseTask2?.result as Boolean? finishAction("TBR") return if (response == null || !response) { aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - Cancel TBR failed.") PumpEnactResult(injector).success(false).enacted(false) // .comment(R.string.medtronic_cmd_cant_cancel_tbr) } else { aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - Cancel TBR successful.") val runningTBR = medtronicPumpStatus.runningTBR // TODO if (runningTBR != null) { if (medtronicHistoryData.isTBRActive(runningTBR)) { val differenceTime = System.currentTimeMillis() - runningTBR.date //val tbrData = runningTBR val result = pumpSync.syncTemporaryBasalWithPumpId( runningTBR.date, runningTBR.rate, differenceTime, runningTBR.isAbsolute, runningTBR.tbrType, runningTBR.pumpId!!, runningTBR.pumpType, runningTBR.serialNumber ) val differenceTimeMin = floor(differenceTime / (60.0 * 1000.0)) aapsLogger.debug( LTag.PUMP, "canceling running TBR - syncTemporaryBasalWithPumpId [date=${runningTBR.date}, " + "pumpId=${runningTBR.pumpId}, rate=${runningTBR.rate} U, duration=${differenceTimeMin.toInt()}, " + "pumpSerial=${medtronicPumpStatus.serialNumber}] - Result: $result" ) } } //cancelTBRWithTemporaryId() PumpEnactResult(injector).success(true).enacted(true) // .isTempCancel(true) } } override fun manufacturer(): ManufacturerType { return ManufacturerType.Medtronic } override fun model(): PumpType { return pumpDescription.pumpType } override fun serialNumber(): String { return medtronicPumpStatus.serialNumber } @Synchronized override fun setNewBasalProfile(profile: Profile): PumpEnactResult { aapsLogger.info(LTag.PUMP, logPrefix + "setNewBasalProfile") // this shouldn't be needed, but let's do check if profile setting we are setting is same as current one if (isProfileSame(profile)) { return PumpEnactResult(injector) // .success(true) // .enacted(false) // .comment(R.string.medtronic_cmd_basal_profile_not_set_is_same) } setRefreshButtonEnabled(false) if (isPumpNotReachable) { setRefreshButtonEnabled(true) return PumpEnactResult(injector) // .success(false) // .enacted(false) // .comment(R.string.medtronic_pump_status_pump_unreachable) } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) val basalProfile = convertProfileToMedtronicProfile(profile) aapsLogger.debug("Basal Profile: $basalProfile") val profileInvalid = isProfileValid(basalProfile) if (profileInvalid != null) { return PumpEnactResult(injector) // .success(false) // .enacted(false) // .comment(rh.gs(R.string.medtronic_cmd_set_profile_pattern_overflow, profileInvalid)) } val responseTask = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand( MedtronicCommandType.SetBasalProfileSTD, arrayListOf(basalProfile) ) val response = responseTask?.result as Boolean? aapsLogger.info(LTag.PUMP, logPrefix + "Basal Profile was set: " + response) return if (response == null || !response) { PumpEnactResult(injector).success(false).enacted(false) // .comment(R.string.medtronic_cmd_basal_profile_could_not_be_set) } else { PumpEnactResult(injector).success(true).enacted(true) } } private fun isProfileValid(basalProfile: BasalProfile): String? { val stringBuilder = StringBuilder() if (medtronicPumpStatus.maxBasal == null) return null for (profileEntry in basalProfile.getEntries()) { if (profileEntry.rate > medtronicPumpStatus.maxBasal!!) { stringBuilder.append(profileEntry.startTime!!.toString("HH:mm")) stringBuilder.append("=") stringBuilder.append(profileEntry.rate) } } return if (stringBuilder.isEmpty()) null else stringBuilder.toString() } private fun convertProfileToMedtronicProfile(profile: Profile): BasalProfile { val basalProfile = BasalProfile(aapsLogger) for (i in 0..23) { val rate = profile.getBasalTimeFromMidnight(i * 60 * 60) val v = pumpType.determineCorrectBasalSize(rate) val basalEntry = BasalProfileEntry(v, i, 0) basalProfile.addEntry(basalEntry) } basalProfile.generateRawDataFromEntries() return basalProfile } // OPERATIONS not supported by Pump or Plugin private var customActions: List<CustomAction>? = null private val customActionWakeUpAndTune = CustomAction( R.string.medtronic_custom_action_wake_and_tune, MedtronicCustomActionType.WakeUpAndTune ) private val customActionClearBolusBlock = CustomAction( R.string.medtronic_custom_action_clear_bolus_block, MedtronicCustomActionType.ClearBolusBlock, false ) private val customActionResetRLConfig = CustomAction( R.string.medtronic_custom_action_reset_rileylink, MedtronicCustomActionType.ResetRileyLinkConfiguration, true ) override fun getCustomActions(): List<CustomAction>? { if (customActions == null) { customActions = listOf( customActionWakeUpAndTune, // customActionClearBolusBlock, // customActionResetRLConfig ) } return customActions } override fun executeCustomAction(customActionType: CustomActionType) { when (customActionType as? MedtronicCustomActionType) { MedtronicCustomActionType.WakeUpAndTune -> { if (rileyLinkMedtronicService?.verifyConfiguration() == true) { serviceTaskExecutor.startTask(WakeAndTuneTask(injector)) } else { runAlarm(context, rh.gs(R.string.medtronic_error_operation_not_possible_no_configuration), rh.gs(R.string.medtronic_warning), R.raw.boluserror) } } MedtronicCustomActionType.ClearBolusBlock -> { busyTimestamps.clear() customActionClearBolusBlock.isEnabled = false refreshCustomActionsList() } MedtronicCustomActionType.ResetRileyLinkConfiguration -> { serviceTaskExecutor.startTask(ResetRileyLinkConfigurationTask(injector)) } null -> { } } } override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) { aapsLogger.warn(LTag.PUMP, logPrefix + "Time or TimeZone changed. ") hasTimeDateOrTimeZoneChanged = true } override fun setNeutralTempAtFullHour(): Boolean { return sp.getBoolean(R.string.key_set_neutral_temps, true) } @Suppress("SameParameterValue") private fun setEnableCustomAction(customAction: MedtronicCustomActionType, isEnabled: Boolean) { if (customAction === MedtronicCustomActionType.ClearBolusBlock) { customActionClearBolusBlock.isEnabled = isEnabled } else if (customAction === MedtronicCustomActionType.ResetRileyLinkConfiguration) { customActionResetRLConfig.isEnabled = isEnabled } refreshCustomActionsList() } }
agpl-3.0
99487e17fa364628ed0a87fc3242b1a6
46.168301
254
0.652313
5.539
false
false
false
false
trofimovilya/Alarmebble
Alarmebble-Android/app/src/main/kotlin/ru/ilyatrofimov/alarmebble/reciever/AlarmebbleReceiver.kt
1
2132
package ru.ilyatrofimov.alarmebble.reciever import android.content.Context import android.content.Intent import android.preference.PreferenceManager import android.provider.AlarmClock import com.getpebble.android.kit.PebbleKit import com.getpebble.android.kit.util.PebbleDictionary import ru.ilyatrofimov.alarmebble.R import java.util.* class AlarmebbleReceiver : PebbleKit.PebbleDataReceiver(APP_UUID) { private val STATUS_OK = 0 private val STATUS_ERROR = -2 override fun receiveData(context: Context, transactionId: Int, data: PebbleDictionary) { PebbleKit.sendAckToPebble(context, transactionId) val response = PebbleDictionary() // Get current alarm app val settings = PreferenceManager.getDefaultSharedPreferences(context); val processName = settings.getString(context.getString(R.string.key_process), "") val activityName = settings.getString(context.getString(R.string.key_activity), "") // Try to start set alarm intent and prepare response for pebble try { with (Intent(AlarmClock.ACTION_SET_ALARM)) { setClassName(processName, activityName) putExtra(AlarmClock.EXTRA_HOUR, data.getInteger(0).toInt()) putExtra(AlarmClock.EXTRA_MINUTES, data.getInteger(1).toInt()) putExtra(AlarmClock.EXTRA_SKIP_UI, true) flags = Intent.FLAG_ACTIVITY_NEW_TASK if (resolveActivity(context.packageManager) != null) { context.startActivity(this) response.addInt32(0, STATUS_OK) // OK } else { response.addInt32(0, STATUS_ERROR) // Error } } } catch (e: Exception) { response.addInt32(0, STATUS_ERROR) // Error } // Send response to Pebble PebbleKit.sendDataToPebbleWithTransactionId(context, APP_UUID, response, transactionId) } /** * Not secret Pebble APP_UUID */ companion object { private val APP_UUID = UUID.fromString("e44a8ca9-2d35-4d55-b9f2-cafd12788dbf") } }
mit
61988e40e78e8c654455ef1822833b4c
37.763636
95
0.657598
4.289738
false
false
false
false
java-opengl-labs/ogl-samples
src/main/kotlin/ogl_samples/tests/es300/es-300-texture-format-packed.kt
1
4900
package ogl_samples.tests.es300 import glm_.BYTES import glm_.glm import glm_.i import glm_.mat4x4.Mat4 import glm_.s import glm_.vec2.Vec2 import glm_.vec3.Vec3 import glm_.vec4.Vec4i import ogl_samples.framework.Compiler import ogl_samples.framework.TestA import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL12.GL_UNSIGNED_SHORT_4_4_4_4 import org.lwjgl.opengl.GL13.GL_TEXTURE0 import org.lwjgl.opengl.GL13.glActiveTexture import uno.buffer.bufferBig import uno.buffer.bufferOf import uno.caps.Caps.Profile import uno.glf.Vertex import uno.glf.glf import uno.glf.semantic import uno.gln.* /** * Created by GBarbieri on 30.03.2017. */ fun main(args: Array<String>) { es_300_texture_format_packed().loop() } private class es_300_texture_format_packed : TestA("es-300-texture-format-packed", Profile.ES, 3, 0) { val SHADER_SOURCE = "es-300/texture-format-packed" override var vertexCount = 8 override var vertexData = bufferOf( Vertex.pos2_tc2(Vec2(-1f, -1f), Vec2(0f, 0f)), Vertex.pos2_tc2(Vec2(-1f, 3f), Vec2(0f, 1f)), Vertex.pos2_tc2(Vec2(3f, -1f), Vec2(1f, 0f))) val viewport = arrayOf( Vec4i(0, 0, 320, 240), Vec4i(320, 0, 320, 240), Vec4i(0, 240, 320, 240), Vec4i(320, 240, 320, 240)) override fun initProgram(): Boolean { var validated = true val compiler = Compiler() val vertShaderName = compiler.create("$SHADER_SOURCE.vert") val fragShaderName = compiler.create("$SHADER_SOURCE.frag") validated = validated && compiler.check() initProgram(programName) { attach(vertShaderName, fragShaderName) "Position".attrib = semantic.attr.POSITION "Texcoord".attrib = semantic.attr.TEX_COORD "Color".fragData = semantic.frag.COLOR link() validated = validated && compiler checkProgram name Uniform.mvp = "MVP".uniform validated = validated && Uniform.mvp != -1 Uniform.diffuse = "Diffuse".uniform validated = validated && Uniform.diffuse != -1 } return validated && checkError("initProgram") } override fun initBuffer() = initArrayBuffer(vertexData) override fun initTexture(): Boolean { glPixelStorei(GL_UNPACK_ALIGNMENT, 1) initTextures2d(textureName) { val dataRGBA4 = bufferBig(Short.BYTES).putShort(0, 0xF80C.s) val dataRGBA8 = bufferBig(Int.BYTES).putInt(0, 0xCC0088FF.i) val dataBGRA4 = bufferBig(Short.BYTES).putShort(0, 0x08FC) val dataBGRA8 = bufferBig(Int.BYTES).putInt(0, 0xCCFF8800.i) at(Texture.RGBA4) { levels(base = 0, max = 0) filter(min = nearest, mag = nearest) image(GL_RGBA4, 1, 1, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, dataRGBA4) } at(Texture.RGBA4_REV) { levels(base = 0, max = 0) filter(min = nearest, mag = nearest) image(GL_RGBA8, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, dataRGBA8) } at(Texture.BGRA4) { levels(base = 0, max = 0) filter(min = nearest, mag = nearest) swizzle(r = blue, g = green, b = red, a = alpha) image(GL_RGBA4, 1, 1, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, dataBGRA4) } at(Texture.BGRA4_REV) { levels(base = 0, max = 0) filter(min = nearest, mag = nearest) swizzle(r = blue, g = green, b = red, a = alpha) image(GL_RGBA8, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, dataBGRA8) } } return checkError("initTexture") } override fun initVertexArray() = initVertexArray(glf.pos2_tc2) override fun render(): Boolean { val projection = glm.perspective(glm.PIf * 0.25f, 4f / 3f, 0.1f, 100f) val model = glm.scale(Mat4(), Vec3(3f)) val mvp = projection * view * model usingProgram(programName) { glUniform(Uniform.diffuse, semantic.sampler.DIFFUSE) glUniform(Uniform.mvp, mvp) glBindVertexArray(vertexArrayName) glActiveTexture(GL_TEXTURE0) glViewport(viewport[0]) glBindTexture(GL_TEXTURE_2D, Texture.RGBA4) glDrawArraysInstanced(vertexCount, 1) glViewport(viewport[1]) glBindTexture(GL_TEXTURE_2D, Texture.RGBA4_REV) glDrawArraysInstanced(vertexCount, 1) glViewport(viewport[2]) glBindTexture(GL_TEXTURE_2D, Texture.BGRA4) glDrawArraysInstanced(vertexCount, 1) glViewport(viewport[3]) glBindTexture(GL_TEXTURE_2D, Texture.BGRA4_REV) glDrawArraysInstanced(vertexCount, 1) } return true } }
mit
b35822fa2b4b1a24ebddbc4bf3919084
31.673333
102
0.597143
3.700906
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/builders/KotlinCompilationBuilder.kt
2
6722
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.gradleTooling.builders import org.gradle.api.Task import org.gradle.api.logging.Logging import org.jetbrains.kotlin.idea.gradleTooling.* import org.jetbrains.kotlin.idea.gradleTooling.arguments.buildCachedArgsInfo import org.jetbrains.kotlin.idea.gradleTooling.arguments.buildSerializedArgsInfo import org.jetbrains.kotlin.idea.gradleTooling.reflect.KotlinCompilationOutputReflection import org.jetbrains.kotlin.idea.gradleTooling.reflect.KotlinCompilationReflection import org.jetbrains.kotlin.idea.gradleTooling.reflect.KotlinNativeCompileReflection import org.jetbrains.kotlin.idea.projectModel.KotlinCompilation import org.jetbrains.kotlin.idea.projectModel.KotlinCompilationOutput import org.jetbrains.kotlin.idea.projectModel.KotlinPlatform class KotlinCompilationBuilder(val platform: KotlinPlatform, val classifier: String?) : KotlinModelComponentBuilder<KotlinCompilationReflection, MultiplatformModelImportingContext, KotlinCompilation> { override fun buildComponent( origin: KotlinCompilationReflection, importingContext: MultiplatformModelImportingContext ): KotlinCompilationImpl? { val compilationName = origin.compilationName val kotlinGradleSourceSets = origin.sourceSets ?: return null val kotlinSourceSets = kotlinGradleSourceSets.mapNotNull { importingContext.sourceSetByName(it.name) } val compileKotlinTask = origin.compileKotlinTaskName ?.let { importingContext.project.tasks.findByName(it) } ?: return null val output = origin.compilationOutput?.let { buildCompilationOutput(it, compileKotlinTask) } ?: return null val dependencies = buildCompilationDependencies(importingContext, origin, classifier) val kotlinTaskProperties = getKotlinTaskProperties(compileKotlinTask, classifier) val nativeExtensions = origin.konanTargetName?.let(::KotlinNativeCompilationExtensionsImpl) val allSourceSets = kotlinSourceSets .flatMap { sourceSet -> importingContext.resolveAllDependsOnSourceSets(sourceSet) } .union(kotlinSourceSets) val cachedArgsInfo = if (compileKotlinTask.isCompilerArgumentAware //TODO hotfix for KTIJ-21807. // Remove after proper implementation of org.jetbrains.kotlin.gradle.tasks.KotlinNativeCompile#setupCompilerArgs && !compileKotlinTask.isKotlinNativeCompileTask //TODO hotfix for KTIJ-21807. Replace after ) buildCachedArgsInfo(compileKotlinTask, importingContext.compilerArgumentsCacheMapper) else buildSerializedArgsInfo(compileKotlinTask, importingContext.compilerArgumentsCacheMapper, logger) val associateCompilations = origin.associateCompilations.mapNotNull { associateCompilation -> KotlinCompilationCoordinatesImpl( targetName = associateCompilation.target?.targetName ?: return@mapNotNull null, compilationName = associateCompilation.compilationName ) } @Suppress("DEPRECATION_ERROR") return KotlinCompilationImpl( name = compilationName, allSourceSets = allSourceSets, declaredSourceSets = if (platform == KotlinPlatform.ANDROID) allSourceSets else kotlinSourceSets, dependencies = dependencies.map { importingContext.dependencyMapper.getId(it) }.distinct().toTypedArray(), output = output, arguments = KotlinCompilationArgumentsImpl(emptyArray(), emptyArray()), dependencyClasspath = emptyArray(), cachedArgsInfo = cachedArgsInfo, kotlinTaskProperties = kotlinTaskProperties, nativeExtensions = nativeExtensions, associateCompilations = associateCompilations.toSet() ) } companion object { private val logger = Logging.getLogger(KotlinCompilationBuilder::class.java) private val compileDependenciesBuilder = object : KotlinMultiplatformDependenciesBuilder() { override val configurationNameAccessor: String = "getCompileDependencyConfigurationName" override val scope: String = "COMPILE" } private val runtimeDependenciesBuilder = object : KotlinMultiplatformDependenciesBuilder() { override val configurationNameAccessor: String = "getRuntimeDependencyConfigurationName" override val scope: String = "RUNTIME" } private const val COMPILER_ARGUMENT_AWARE_CLASS = "org.jetbrains.kotlin.gradle.internal.CompilerArgumentAware" private const val KOTLIN_NATIVE_COMPILE_CLASS = "org.jetbrains.kotlin.gradle.tasks.AbstractKotlinNativeCompile" private fun buildCompilationDependencies( importingContext: MultiplatformModelImportingContext, compilationReflection: KotlinCompilationReflection, classifier: String? ): Set<KotlinDependency> { return LinkedHashSet<KotlinDependency>().apply { this += compileDependenciesBuilder.buildComponent(compilationReflection.gradleCompilation, importingContext) this += runtimeDependenciesBuilder.buildComponent(compilationReflection.gradleCompilation, importingContext) .onlyNewDependencies(this) val sourceSet = importingContext.sourceSetByName(compilationFullName(compilationReflection.compilationName, classifier)) this += sourceSet?.dependencies?.mapNotNull { importingContext.dependencyMapper.getDependency(it) } ?: emptySet() } } private fun buildCompilationOutput( kotlinCompilationOutputReflection: KotlinCompilationOutputReflection, compileKotlinTask: Task ): KotlinCompilationOutput? { val compilationOutputBase = KotlinCompilationOutputBuilder.buildComponent(kotlinCompilationOutputReflection) ?: return null val destinationDir = KotlinNativeCompileReflection(compileKotlinTask).destinationDir return KotlinCompilationOutputImpl(compilationOutputBase.classesDirs, destinationDir, compilationOutputBase.resourcesDir) } private val Task.isCompilerArgumentAware: Boolean get() = javaClass.classLoader.loadClassOrNull(COMPILER_ARGUMENT_AWARE_CLASS)?.isAssignableFrom(javaClass) ?: false private val Task.isKotlinNativeCompileTask: Boolean get() = javaClass.classLoader.loadClassOrNull(KOTLIN_NATIVE_COMPILE_CLASS)?.isAssignableFrom(javaClass) ?: false } }
apache-2.0
400f8d56723f168041ecd697114698d5
55.966102
158
0.743677
6.224074
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LALR1/interpret/test/TestInterpret13.kt
1
11983
package com.bajdcc.LALR1.interpret.test import com.bajdcc.LALR1.grammar.Grammar import com.bajdcc.LALR1.grammar.runtime.RuntimeCodePage import com.bajdcc.LALR1.grammar.runtime.RuntimeException import com.bajdcc.LALR1.interpret.Interpreter import com.bajdcc.LALR1.syntax.handler.SyntaxException import com.bajdcc.util.lexer.error.RegexException import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream object TestInterpret13 { @JvmStatic fun main(args: Array<String>) { try { val codes = arrayOf("import \"sys.base\";\n" + "import \"sys.func\";\n" + "import \"sys.list\";\n" + "import \"sys.string\";\n" + "import \"sys.math\";\n" + "import \"sys.class\";\n" + "\n" + "var ctx = call g_create_context();\n" + "call g_register_class(ctx, \"shape\", lambda(this){\n" + "call g_create_property(this, \"type\", \"shape\");\n" + "call g_create_method(this, \"get_area\", lambda(this)->0);\n" + "call g_create_method(this, \"get_index\", lambda(this,i)->i);\n" + "}, g_null);\n" + "call g_register_class(ctx, \"square\", lambda(this){\n" + "call g_create_property(this, \"type\", \"square\");\n" + "call g_create_property(this, \"a\", 0);\n" + "call g_create_property(this, \"b\", 0);\n" + "call g_create_method(this, \"get_area\", lambda(this){\n" + "return call g_get_property(this, \"a\") * call g_get_property(this, \"b\");\n" + "});\n" + "call g_create_method(this, \"to_string\", lambda(this){\n" + "return \"\" + call g_get_property(this, \"type\")\n" + "+ \" a=\" + call g_get_property(this, \"a\")\n" + "+ \" b=\" + call g_get_property(this, \"b\")\n" + "+ \" area=\"\n" + "+ call g_invoke_method(this, \"get_area\");\n" + "});\n" + "}, \"shape\");\n" + "call g_register_class(ctx, \"circle\", lambda(this){\n" + "call g_create_property(this, \"type\", \"circle\");\n" + "call g_create_property(this, \"r\", 0);\n" + "call g_create_method(this, \"get_area\", lambda(this){\n" + "var r = call g_get_property(this, \"r\");\n" + "return 3.14 * r * r;\n" + "});\n" + "call g_create_method(this, \"to_string\", lambda(this){\n" + "return \"\" + call g_get_property(this, \"type\")\n" + "+ \" r=\" + call g_get_property(this, \"r\")\n" + "+ \" area=\"\n" + "+ call g_invoke_method(this, \"get_area\");\n" + "});\n" + "}, \"shape\");\n" + "\n" + "\n" + "var square = call g_create_class(ctx, \"square\");\n" + "call g_set_property(square, \"a\", 5);\n" + "call g_set_property(square, \"b\", 6);\n" + "call g_printn(\"\" + call g_get_property(square, \"type\")\n" + "+ \" a=\" + call g_get_property(square, \"a\")\n" + "+ \" b=\" + call g_get_property(square, \"b\")\n" + "+ \" area=\"\n" + "+ call g_invoke_method(square, \"get_area\"));\n" + "var circle = call g_create_class(ctx, \"circle\");\n" + "call g_set_property(circle, \"r\", 10);\n" + "call g_set_property(circle, \"s\", square);\n" + "call g_printn(\"\" + call g_get_property(circle, \"type\")\n" + "+ \" r=\" + call g_get_property(circle, \"r\")\n" + "+ \" area=\"\n" + "+ call g_invoke_method(circle, \"get_area\"));\n" + "call g_printn(call g_invoke_method(square, \"to_string\"));\n" + "call g_printn(call g_invoke_method(circle, \"to_string\"));\n" + "call g_printn(circle.\"r\");\n" + "call g_printn(circle.\"s\".\"__type__\");\n" + "call g_printn(circle.\"s\".\"a\");\n" + "call g_printn(circle.\"s\".\"b\");\n" + "call g_printn(circle.\"__type__\");\n" + "call g_printn(square.\"__type__\");\n" + "set square::\"a\" = 100;\n" + "set square::\"b\" = 120;\n" + "call g_printn(circle.\"s\".\"a\");\n" + "call g_printn(circle.\"s\".\"b\");\n" + "call g_printn(invoke circle::\"get_area\"());\n" + "call g_printn(invoke square::\"get_area\"());\n" + "call g_printn(invoke circle::\"get_index\"(1));\n" + "call g_printn(invoke square::\"get_index\"(2));\n" + "", "import \"sys.base\";\n" + "import \"sys.class\";\n" + "import \"std.base\";\n" + "var ctx = g_create_context();\n" + "g_import_std_base(ctx);\n" + "var a = g_create_class(ctx, \"list::array\");\n" + "var b = g_create_class(ctx, \"list::array\");\n" + "a.\"add\"(b);\n" + "b.\"add\"(0);\n" + "g_printn(a.\"get\"(0).\"size\"());\n" + "a.\"get\"(0).\"c\" := 2;\n" + "a.\"get\"(0).\"c\" *= 2;\n" + "a.\"get\"(0).\"c\" ++;\n" + "g_printn(a.\"get\"(0).\"c\"++);\n", "import \"sys.base\";\n" + "var move = func ~(i, x, y) {\n" + " g_printn(g_to_string(i) + \": \" + g_to_string(x) + \" -> \" + g_to_string(y));\n" + "};\n" + "var hanoi = func ~(f) {\n" + " var fk = func ~(i, a, b, c) {\n" + " if (i == 1) {\n" + " move(i, a, c);\n" + " } else {\n" + " f(i - 1, a, c, b);\n" + " move(i, a, c);\n" + " f(i - 1, b, a, c);\n" + " }\n" + " };\n" + " return fk;\n" + "};\n" + "var h = call (func ~(f) ->\n" + " call (func ~(h) -> h(h))(\n" + " lambda(x) -> lambda(i, a, b, c) ->\n" + " call (f(x(x)))(i, a, b, c)))(hanoi);\n" + "h(3, 'A', 'B', 'C');\n", "import \"sys.base\";\n" + "var c = yield ~(){throw 3;};\n" + "var b = yield ~(){\n" + "try{foreach(var k : c()){}yield 1;}\n" + "catch{\n" + " yield 4;throw 2;}};\n" + "/*g_set_debug(true);*/\n" + "try{foreach(var k : b()){g_printn(k);}}catch{g_printn(5);}\n", "import \"sys.base\";\n" + "var a = func ~(){ foreach (var i : g_range(1, 4)+1) {\n" + " foreach (var j : g_range(1, 5)+1) {\n" + " g_printn(i*j);\n" + " }\n" + "}};\n" + "g_printn(a());\n" + "g_printn(a());", "import \"sys.base\";\n" + "var b = func ~() { foreach (var j : g_range(1, 5)+1) {\n" + " g_printn(j);\n" + "}};\n" + "var a = func ~() { foreach (var i : g_range(1, 4)+1) {\n" + " b();\n" + "}};\n" + "g_printn(a());\n" + "g_printn(a());", "import \"sys.base\";\n" + "import \"sys.string\";\n" + "var a = func ~(){ foreach (var i : g_range_string(\"ertyrt\")) {\n" + " foreach (var j : g_range(1, 5)+1) {\n" + " g_printn(i);\n" + " }\n" + "}};\n" + "g_printn(a());\n" + "g_printn(a());", "import \"sys.base\";\n" + "import \"sys.string\";\n" + "var a = func ~(){ foreach (var i : g_range_string(\"ertyrt\")) {\n" + " foreach (var j : g_range(1, 5)+1) {\n" + " return i;\n" + " }\n" + "}};\n" + "g_printn(a());\n" + "g_printn(a());", "import \"sys.base\";\n" + "import \"sys.proc\";\n" + "g_proc_exec(\"" + "import \\\"user.base\\\";" + "import \\\"user.cparser\\\";" + "var code = \\\"abc\\ndef\\n\\\";" + "var s = g_new_class(\\\"clib::c::scanner\\\", [], [[\\\"init\\\", code]]);" + "while (s.\\\"next\\\"()) { g_printn(s.\\\"REPORT\\\"()); }" + "\");\n", "import \"sys.base\";\n" + "import \"sys.proc\";\n" + "g_proc_exec(\"" + "import \\\"user.base\\\";" + "import \\\"user.cparser\\\";" + "var code = \\\"abc int auto 123\\ndef 0xabcd 5.6e+78\\n+ 0x 4e 6ea 88. 7e-4\\n" + "//123\\\n/*345*/\\\n/*abc\\\ndef*/ /*\\\";" + "var s = g_new_class(\\\"clib::c::scanner\\\", [], [[\\\"init\\\", code]]);" + "var token; while (!(token := s.\\\"scan\\\"()).\\\"eof\\\"()) { g_printn(token.\\\"to_string\\\"()); }" + "g_printn(\\\"Errors: \\\" + s.\\\"ERROR\\\"());" + "\");\n") println(codes[codes.size - 1]) val interpreter = Interpreter() val grammar = Grammar(codes[codes.size - 1]) println(grammar.toString()) val page = grammar.codePage //System.out.println(page.toString()); val baos = ByteArrayOutputStream() RuntimeCodePage.exportFromStream(page, baos) val bais = ByteArrayInputStream(baos.toByteArray()) interpreter.run("test_1", bais) } catch (e: RegexException) { System.err.println() System.err.println(e.position.toString() + "," + e.message) e.printStackTrace() } catch (e: SyntaxException) { System.err.println() System.err.println(String.format("模块名:%s. 位置:%s. 错误:%s-%s(%s:%d)", e.pageName, e.position, e.message, e.info, e.fileName, e.position.line + 1)) e.printStackTrace() } catch (e: RuntimeException) { System.err.println() System.err.println(e.position.toString() + ": " + e.info) e.printStackTrace() } catch (e: Exception) { System.err.println() System.err.println(e.message) e.printStackTrace() } } }
mit
30d6b1539c78be969e3e0c71d63afe92
52.64574
126
0.354008
3.856544
false
false
false
false
PolymerLabs/arcs
java/arcs/core/util/random.kt
1
2517
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.util import kotlin.math.pow import kotlin.random.Random as KotlinRandom /** * Instance of [kotlin.random.Random] to use arcs-wide. * * TODO: Consider seeding the random object ourselves. Unfortunately kotlin.system.getTimeMillis * isn't in the common kotlin library. This will mean we need to make this an `expect` and * implement it for JVM, JS, and WASM targets. Bonus points for using SecureRandom when running in * JVM. */ val Random: KotlinRandom get() = RandomBuilder(null) /** * Generator of a kotlin random class instance. * * This variable is configurable so as to make it possible for tests to make predictable 'random' * behavior possible. */ var RandomBuilder: (seed: Long?) -> KotlinRandom = fn@{ seed -> val globalRandom = globalRandomInstance @Suppress("IfThenToElvis") // Because it's more readable like this. if (globalRandom != null) { // If we've already initialized the global random instance, use it. return@fn globalRandom } else { // Looks like we need to initialize it still, so - depending on whether or not we have a // seed, either return a seeded KotlinRandom, or the default. return@fn (seed?.let { KotlinRandom(seed) } ?: KotlinRandom.Default) // Stash it as the global instance. .also { globalRandomInstance = it } } } /** Gets the next Arcs-safe random long value. */ fun KotlinRandom.nextSafeRandomLong(): Long = Random.nextLong(MAX_SAFE_LONG) /** Gets the next String of [length] that can be safely encoded in a [VersionMap]. */ fun KotlinRandom.nextVersionMapSafeString(length: Int): String { return (1..length) .map { SAFE_CHARS.random(Random) } .joinToString("") } private val MAX_SAFE_LONG = 2.0.pow(50).toLong() private var globalRandomInstance: KotlinRandom? = null /** Set of strings not allowed in [VersionMaps], entity [Id]s and [StorageKey]s. */ val FORBIDDEN_STRINGS = setOf( "{", "}", ENTRIES_SEPARATOR.toString(), ACTOR_VERSION_DELIMITER.toString() ) // Readable chars are 33 '!' to 126 '~'. However, we want to exclude the [FORBIDDEN_STRINGS]. /** Chars that are safe to use in encoding. */ val SAFE_CHARS = ('!'..'~') - FORBIDDEN_STRINGS.map { s -> s[0] }
bsd-3-clause
66f1296f6defbad1ca1c5e2ad32d1378
33.958333
100
0.705602
3.890263
false
false
false
false
Maccimo/intellij-community
platform/core-ui/src/ui/HoledIcon.kt
3
1892
// 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.ui import com.intellij.openapi.util.ScalableIcon import com.intellij.util.IconUtil import org.jetbrains.annotations.ApiStatus import java.awt.* import java.awt.geom.Path2D import javax.swing.Icon @ApiStatus.Internal @ApiStatus.Experimental abstract class HoledIcon(private val icon: Icon) : RetrievableIcon, ScalableIcon { protected abstract fun copyWith(icon: Icon):Icon protected abstract fun createHole(width: Int, height: Int): Shape? protected abstract fun paintHole(g: Graphics2D, width: Int, height: Int) override fun retrieveIcon() = icon override fun getScale() = (icon as? ScalableIcon)?.scale ?: 1f override fun scale(factor: Float) = copyWith(IconUtil.scaleOrLoadCustomVersion(icon, factor)) override fun getIconWidth() = icon.iconWidth override fun getIconHeight() = icon.iconHeight override fun paintIcon(c: Component?, graphics: Graphics, x: Int, y: Int) { val width = iconWidth val height = iconHeight val g = graphics.create(x, y, width, height) try { val hole = createHole(width, height) if (hole != null) { val area = g.clip if (g is Graphics2D) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE) g.clip(hole) // do not allow painting outside the hole paintHole(g, width, height) } // subtract hole from old clip val path = Path2D.Float(Path2D.WIND_EVEN_ODD) path.append(area, false) path.append(hole, false) g.clip = path // safe because based on old clip } icon.paintIcon(c, g, 0, 0) } finally { g.dispose() } } }
apache-2.0
5a34648f6350061467d9397b50aabee3
34.698113
120
0.696089
3.901031
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/presentation/devdb/device/SubDevicePresenter.kt
1
1256
package forpdateam.ru.forpda.presentation.devdb.device import moxy.InjectViewState import forpdateam.ru.forpda.common.Utils import forpdateam.ru.forpda.common.mvp.BasePresenter import forpdateam.ru.forpda.entity.remote.devdb.Device import forpdateam.ru.forpda.model.repository.devdb.DevDbRepository import forpdateam.ru.forpda.presentation.IErrorHandler import forpdateam.ru.forpda.presentation.ILinkHandler import forpdateam.ru.forpda.presentation.Screen import forpdateam.ru.forpda.presentation.TabRouter import forpdateam.ru.forpda.ui.fragments.devdb.device.posts.PostsFragment /** * Created by radiationx on 11.11.17. */ @InjectViewState class SubDevicePresenter( private val router: TabRouter, private val linkHandler: ILinkHandler ) : BasePresenter<SubDeviceView>() { fun onCommentClick(item: Device.Comment) { linkHandler.handle("https://4pda.to/forum/index.php?showuser=${item.userId}", router) } fun onPostClick(item: Device.PostItem, source: Int) { val url = if (source == PostsFragment.SRC_NEWS) { "https://4pda.to/index.php?p=${item.id}" } else { "https://4pda.to/forum/index.php?showtopic=${item.id}" } linkHandler.handle(url, router) } }
gpl-3.0
75185e94c37edde19fc7c652cb59d3e6
32.945946
93
0.737261
3.840979
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ValToObjectIntention.kt
1
2231
// 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.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset class ValToObjectIntention : SelfTargetingIntention<KtProperty>( KtProperty::class.java, KotlinBundle.lazyMessage("convert.to.object.declaration") ) { override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean { if (element.isVar) return false if (!element.isTopLevel) return false val initializer = element.initializer as? KtObjectLiteralExpression ?: return false if (initializer.objectDeclaration.body == null) return false if (element.getter != null) return false if (element.annotationEntries.isNotEmpty()) return false // disable if has non-Kotlin usages return ReferencesSearch.search(element).all { it is KtReference && it.element.parent !is KtCallableReferenceExpression } } override fun applyTo(element: KtProperty, editor: Editor?) { val name = element.name ?: return val objectLiteral = element.initializer as? KtObjectLiteralExpression ?: return val declaration = objectLiteral.objectDeclaration val superTypeList = declaration.getSuperTypeList() val body = declaration.body ?: return val prefix = element.modifierList?.text?.plus(" ") ?: "" val superTypesText = superTypeList?.text?.plus(" ") ?: "" val replacementText = "${prefix}object $name: $superTypesText${body.text}" val replaced = element.replaced(KtPsiFactory(element).createDeclarationByPattern<KtObjectDeclaration>(replacementText)) editor?.caretModel?.moveToOffset(replaced.nameIdentifier?.endOffset ?: return) } }
apache-2.0
7a70803e52a6f98bd0ce7b904d9ecf45
46.489362
158
0.744957
4.892544
false
false
false
false
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-4/app/src/main/java/dev/mfazio/pennydrop/viewmodels/GameViewModel.kt
2
6487
package dev.mfazio.pennydrop.viewmodels import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dev.mfazio.pennydrop.game.GameHandler import dev.mfazio.pennydrop.game.TurnEnd import dev.mfazio.pennydrop.game.TurnResult import dev.mfazio.pennydrop.types.Player import dev.mfazio.pennydrop.types.Slot import dev.mfazio.pennydrop.types.clear import kotlinx.coroutines.delay import kotlinx.coroutines.launch class GameViewModel : ViewModel() { private var players: List<Player> = emptyList() val slots = MutableLiveData( (1..6).map { slotNum -> Slot(slotNum, slotNum != 6) } ) val currentPlayer = MutableLiveData<Player?>() val canRoll = MutableLiveData(false) val canPass = MutableLiveData(false) val currentTurnText = MutableLiveData("") val currentStandingsText = MutableLiveData("") private var clearText = false fun startGame(playersForNewGame: List<Player>) { this.players = playersForNewGame this.currentPlayer.value = this.players.firstOrNull().apply { this?.isRolling = true } canRoll.value = true canPass.value = false slots.value?.clear() slots.notifyChange() currentTurnText.value = "The game has begun!\n" currentStandingsText.value = generateCurrentStandings(this.players) } fun roll() { slots.value?.let { currentSlots -> // Comparing against true saves us a null check val currentPlayer = players.firstOrNull { it.isRolling } if (currentPlayer != null && canRoll.value == true) { updateFromGameHandler( GameHandler.roll(players, currentPlayer, currentSlots) ) } } } fun pass() { val currentPlayer = players.firstOrNull { it.isRolling } if (currentPlayer != null && canPass.value == true) { updateFromGameHandler(GameHandler.pass(players, currentPlayer)) } } private fun updateFromGameHandler(result: TurnResult) { if (result.currentPlayer != null) { currentPlayer.value?.addPennies(result.coinChangeCount ?: 0) currentPlayer.value = result.currentPlayer this.players.forEach { player -> player.isRolling = result.currentPlayer == player } } if (result.lastRoll != null) { slots.value?.let { currentSlots -> updateSlots(result, currentSlots, result.lastRoll) } } currentTurnText.value = generateTurnText(result) currentStandingsText.value = generateCurrentStandings(this.players) canRoll.value = result.canRoll canPass.value = result.canPass if (!result.isGameOver && result.currentPlayer?.isHuman == false) { canRoll.value = false canPass.value = false playAITurn() } } private fun updateSlots( result: TurnResult, currentSlots: List<Slot>, lastRoll: Int ) { if (result.clearSlots) currentSlots.clear() currentSlots.firstOrNull { it.lastRolled }?.apply { lastRolled = false } currentSlots.getOrNull(lastRoll - 1)?.also { slot -> if (!result.clearSlots && slot.canBeFilled) slot.isFilled = true slot.lastRolled = true } slots.notifyChange() } private fun generateCurrentStandings( players: List<Player>, headerText: String = "Current Standings:" ) = players.sortedBy { it.pennies }.joinToString( separator = "\n", prefix = "$headerText\n" ) { "\t${it.playerName} - ${it.pennies} pennies" } private fun generateTurnText(result: TurnResult): String { if (clearText) currentTurnText.value = "" clearText = result.turnEnd != null val currentText = currentTurnText.value ?: "" val currentPlayerName = result.currentPlayer?.playerName ?: "???" return when { result.isGameOver -> """Game Over! |$currentPlayerName is the winner! | |${generateCurrentStandings(this.players, "Final Scores:\n")} """.trimMargin() result.turnEnd == TurnEnd.Bust -> "${ohNoPhrases.shuffled().first()} ${result.previousPlayer?.playerName} rolled a ${result.lastRoll}. They collected ${result.coinChangeCount} pennies for a total of ${result.previousPlayer?.pennies}.\n$currentText" result.turnEnd == TurnEnd.Pass -> "${result.previousPlayer?.playerName} passed. They currently have ${result.previousPlayer?.pennies} pennies.\n$currentText" result.lastRoll != null -> "$currentPlayerName rolled a ${result.lastRoll}.\n$currentText" else -> "" } } private fun playAITurn() { viewModelScope.launch { delay(1000) slots.value?.let { currentSlots -> val currentPlayer = players.firstOrNull { it.isRolling } if (currentPlayer != null && !currentPlayer.isHuman) { GameHandler.playAITurn( players, currentPlayer, currentSlots, canPass.value == true )?.let { result -> updateFromGameHandler(result) } } } } } // I added this at the request of my wife, who wanted to see a bunch of "oh no!" phrases added in. // They make me smile. private val ohNoPhrases = listOf( "Oh no!", "Bummer!", "Dang.", "Whoops.", "Ah, fiddlesticks.", "Oh, kitty cats.", "Piffle.", "Well, crud.", "Ah, cinnamon bits.", "Ooh, bad luck.", "Shucks!", "Woopsie daisy.", "Nooooooo!", "Aw, rats and bats.", "Blood and thunder!", "Gee whillikins.", "Well that's disappointing.", "I find your lack of luck disturbing.", "That stunk, huh?", "Uff da." ) // This is included because changing a single item in a list won't automatically update. private fun <T> MutableLiveData<List<T>>.notifyChange() { this.value = this.value } }
apache-2.0
d5f6d8a24bdb277aa02bdfa38c894a29
32.271795
261
0.586249
4.815887
false
false
false
false
byu-oit/android-byu-suite-v2
support/src/main/java/edu/byu/support/client/campusLocation/model/RoomResponseWrapper.kt
2
1665
package edu.byu.support.client.campusLocation.model import com.google.gson.annotations.SerializedName import edu.byu.support.utils.toTitleCase /** * Created by cwoodfie on 11/28/16. */ data class RoomResponseWrapper( @SerializedName("room") val rooms: List<Room>? = null ) { data class Room( @SerializedName("@room") val room: String? = null, @SerializedName("@building") val building: String? = null ): Comparable<Room> { companion object { private const val REGEX = "[^\\d]*(\\d+)[^\\d]*" private const val REPLACEMENT = "$1" } @SerializedName("@roomDesc") val roomDesc: String? = null //Custom getter cleans up the descriptions returned get() = field?.toTitleCase() ?.replace("(?<=(Wom|M)en)(s'? | )".toRegex(), "'s ") ?.replace("Rest Room|Rrm".toRegex(), "Restroom") ?.replace("Handicapd".toRegex(), "Handicapped") ?.replace("Vesitbule|Vestibuile".toRegex(), "Vestibule") ?.replace("([Rr])[om]( |$)".toRegex(), "$1oom$2") ?.replace("Crmry ".toRegex(), "") ?.replace("(?<!\\s)\\(".toRegex(), " (") val roomValue get() = room?.let { // The parseInt will crash if the string is empty so we check for that val numberString = it.replaceFirst(REGEX.toRegex(), REPLACEMENT) if (numberString.isNotEmpty()) { Integer.parseInt(numberString) } else { null } } override fun compareTo(other: Room): Int { val returnValue = compareValues(roomValue, other.roomValue) return if (returnValue == 0) { //If the room numbers are the same, sort by string to take into account letters compareValues(room, other.room) } else returnValue } } }
apache-2.0
f42a98aa4a60ad4aa79fe5746a18374e
28.210526
83
0.642643
3.363636
false
false
false
false
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-12/app-code/app/src/main/java/dev/mfazio/abl/settings/SettingsFragment.kt
1
8995
package dev.mfazio.abl.settings import android.os.Bundle import android.util.Log import android.util.TypedValue import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.preference.* import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.workDataOf import dev.mfazio.abl.R import dev.mfazio.abl.api.services.getDefaultABLService import dev.mfazio.abl.teams.UITeam import kotlinx.coroutines.launch class SettingsFragment : PreferenceFragmentCompat() { private lateinit var favoriteTeamPreference: DropDownPreference private lateinit var favoriteTeamColorPreference: SwitchPreferenceCompat private lateinit var startingScreenPreference: DropDownPreference private lateinit var usernamePreference: EditTextPreference override fun onCreatePreferences( savedInstanceState: Bundle?, rootKey: String? ) { val ctx = preferenceManager.context val screen = preferenceManager.createPreferenceScreen(ctx) this.usernamePreference = EditTextPreference(ctx).apply { key = usernamePreferenceKey title = getString(R.string.user_name) summaryProvider = EditTextPreference.SimpleSummaryProvider.getInstance() onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> loadSettings(newValue?.toString()) true } } screen.addPreference(usernamePreference) this.favoriteTeamPreference = DropDownPreference(ctx).apply { key = favoriteTeamPreferenceKey title = getString(R.string.favorite_team) entries = (listOf(getString(R.string.none)) + UITeam.allTeams.map { it.teamName }).toTypedArray() entryValues = (listOf("") + UITeam.allTeams.map { it.teamId }).toTypedArray() setDefaultValue("") summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() } this.favoriteTeamColorPreference = SwitchPreferenceCompat(ctx).apply { key = favoriteTeamColorsPreferenceKey title = getString(R.string.team_color_nav_bar) setDefaultValue(false) } favoriteTeamPreference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> val teamId = newValue?.toString() if (favoriteTeamColorPreference.isChecked) { setNavBarColorForTeam(teamId) } if (teamId != null) { favoriteTeamPreference.icon = getIconForTeam(teamId) } saveSettings(favoriteTeam = teamId) true } screen.addPreference(favoriteTeamPreference) favoriteTeamColorPreference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> val useFavoriteTeamColor = newValue as? Boolean setNavBarColorForTeam( if (useFavoriteTeamColor == true) { favoriteTeamPreference.value } else null ) saveSettings(useFavoriteTeamColor = useFavoriteTeamColor) true } screen.addPreference(favoriteTeamColorPreference) this.startingScreenPreference = DropDownPreference(ctx).apply { key = startingScreenPreferenceKey title = getString(R.string.starting_location) entries = startingScreens.keys.toTypedArray() entryValues = startingScreens.keys.toTypedArray() summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() setDefaultValue(R.id.scoreboardFragment.toString()) onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> saveSettings(startingScreen = newValue?.toString()) true } } screen.addPreference(startingScreenPreference) val aboutCategory = PreferenceCategory(ctx).apply { key = aboutPreferenceCategoryKey title = getString(R.string.about) } screen.addPreference(aboutCategory) val aboutTheAppPreference = Preference(ctx).apply { key = aboutTheAppPreferenceKey title = getString(R.string.about_the_app) summary = getString(R.string.info_about_the_app) onPreferenceClickListener = Preference.OnPreferenceClickListener { [email protected]().navigate( R.id.aboutTheAppFragment ) true } } aboutCategory.addPreference(aboutTheAppPreference) val creditsPreference = Preference(ctx).apply { key = creditsPreferenceKey title = getString(R.string.credits) summary = getString(R.string.image_credits) onPreferenceClickListener = Preference.OnPreferenceClickListener { [email protected]().navigate( R.id.imageCreditsFragment ) true } } aboutCategory.addPreference(creditsPreference) preferenceScreen = screen } override fun onBindPreferences() { favoriteTeamPreference.icon = getIconForTeam(favoriteTeamPreference.value) } private fun getIconForTeam(teamId: String) = UITeam.fromTeamId(teamId)?.let { team -> ContextCompat.getDrawable(requireContext(), team.logoId) } private fun setNavBarColorForTeam(teamId: String?) { val color = UITeam.getTeamPalette(requireContext(), teamId) ?.dominantSwatch ?.rgb ?: getDefaultColor() activity?.window?.navigationBarColor = color } private fun getDefaultColor(): Int { val colorValue = TypedValue() activity?.theme?.resolveAttribute( R.attr.colorPrimary, colorValue, true ) return colorValue.data } private fun saveSettings( userName: String? = usernamePreference.text, favoriteTeam: String? = favoriteTeamPreference.value, useFavoriteTeamColor: Boolean? = favoriteTeamColorPreference.isChecked, startingScreen: String? = startingScreenPreference.value ) { if (userName != null) { WorkManager.getInstance(requireContext()).enqueue( OneTimeWorkRequestBuilder<SaveSettingsWorker>() .setInputData( workDataOf( SaveSettingsWorker.userNameKey to userName, SaveSettingsWorker.favoriteTeamKey to favoriteTeam, SaveSettingsWorker.favoriteTeamColorCheckKey to useFavoriteTeamColor, SaveSettingsWorker.startingScreenKey to startingScreen ) ).build() ) } } private fun loadSettings(userName: String? = null) { if (userName != null) { viewLifecycleOwner.lifecycleScope.launch { try { val apiResult = getDefaultABLService().getAppSettingsForUser(userName) with(favoriteTeamPreference) { value = apiResult.favoriteTeamId icon = getIconForTeam(apiResult.favoriteTeamId) } setNavBarColorForTeam( if (apiResult.useTeamColorNavBar) { apiResult.favoriteTeamId } else null ) favoriteTeamColorPreference.isChecked = apiResult.useTeamColorNavBar startingScreenPreference.value = apiResult.startingLocation } catch (ex: Exception) { Log.i( TAG, """Settings not found. |This may just mean they haven't been initialized yet. |""".trimMargin() ) saveSettings(userName) } } } } companion object { const val TAG = "SettingsFragment" const val aboutPreferenceCategoryKey = "aboutCategory" const val aboutTheAppPreferenceKey = "aboutTheApp" const val creditsPreferenceKey = "credits" const val favoriteTeamPreferenceKey = "favoriteTeam" const val favoriteTeamColorsPreferenceKey = "useFavoriteTeamColors" const val startingScreenPreferenceKey = "startingScreen" const val usernamePreferenceKey = "username" } }
apache-2.0
79f65f5147bd8544990b6ab4de33d977
36.173554
103
0.611673
6.29021
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/player/usecase/FindPlayerRankUseCase.kt
1
1863
package io.ipoli.android.player.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.player.data.Player import io.ipoli.android.player.data.Player.Rank class FindPlayerRankUseCase : UseCase<FindPlayerRankUseCase.Params, FindPlayerRankUseCase.Result> { override fun execute(parameters: Params): Result { val attrLevels = parameters.playerAttributes.map { it.value.level } val level = parameters.playerLevel return when { level >= 100 && attrLevels.all { it >= 100 } -> Result(Rank.DIVINITY, null) level >= 90 && attrLevels.all { it >= 90 } -> Result(Rank.TITAN, Rank.DIVINITY) level >= 80 && attrLevels.all { it >= 80 } -> Result(Rank.DEMIGOD, Rank.TITAN) level >= 70 && attrLevels.all { it >= 70 } -> Result(Rank.IMMORTAL, Rank.DEMIGOD) level >= 60 && attrLevels.all { it >= 60 } -> Result(Rank.LEGEND, Rank.IMMORTAL) level >= 50 && attrLevels.all { it >= 50 } -> Result(Rank.MASTER, Rank.LEGEND) level >= 40 && attrLevels.all { it >= 40 } -> Result(Rank.EXPERT, Rank.MASTER) level >= 30 && attrLevels.all { it >= 30 } -> Result(Rank.SPECIALIST, Rank.EXPERT) level >= 20 && attrLevels.all { it >= 20 } -> Result(Rank.ADEPT, Rank.SPECIALIST) level >= 10 && attrLevels.all { it >= 10 } -> Result(Rank.APPRENTICE, Rank.ADEPT) else -> Result(Rank.NOVICE, Rank.APPRENTICE) } } data class Params( val playerAttributes: Map<Player.AttributeType, Player.Attribute>, val playerLevel: Int ) data class Result(val currentRank: Rank, val nextRank: Rank?) }
gpl-3.0
76015adbbe95a2b6c16c5041cf8d91fc
31.137931
74
0.561997
4.041215
false
false
false
false
Turbo87/intellij-emberjs
src/main/kotlin/com/emberjs/hbs/HbsLinkToReference.kt
1
1821
package com.emberjs.hbs import com.emberjs.index.EmberNameIndex import com.emberjs.lookup.EmberLookupElementBuilder import com.emberjs.resolver.EmberName import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementResolveResult.createResults import com.intellij.psi.PsiManager import com.intellij.psi.PsiPolyVariantReferenceBase import com.intellij.psi.ResolveResult import com.intellij.psi.search.ProjectScope class HbsLinkToReference(element: PsiElement, range: TextRange, val moduleName: String) : PsiPolyVariantReferenceBase<PsiElement>(element, range, true) { private val project = element.project private val scope = ProjectScope.getAllScope(project) private val psiManager: PsiManager by lazy { PsiManager.getInstance(project) } override fun getVariants(): Array<out Any> { // Collect all components from the index return EmberNameIndex.getFilteredProjectKeys(scope) { matches(it) } // Convert search results for LookupElements .map { EmberLookupElementBuilder.create(it) } .toTypedArray() } override fun multiResolve(incompleteCode: Boolean): Array<out ResolveResult> { // Collect all components from the index return EmberNameIndex.getFilteredFiles(scope) { matches(it) && it.name == moduleName } // Convert search results for LookupElements .mapNotNull { psiManager.findFile(it) } .let(::createResults) } fun matches(module: EmberName): Boolean { if (module.type == "template") return !module.name.startsWith("components/") return module.type in MODULE_TYPES } companion object { val MODULE_TYPES = arrayOf("controller", "route") } }
apache-2.0
8aa2632ec90bcc7d8fe238940e9cd962
36.9375
94
0.7095
4.882038
false
false
false
false
fuzz-productions/Salvage
salvage-processor/src/main/java/com/fuzz/android/salvage/StringUtils.kt
1
580
package com.fuzz.android.salvage /** * Description: */ fun String?.isNullOrEmpty(): Boolean { return this == null || this.trim { it <= ' ' }.isEmpty() || this == "null" } fun String?.capitalizeFirstLetter(): String { if (this == null || this.trim { it <= ' ' }.isEmpty()) { return this ?: "" } return this.substring(0, 1).toUpperCase() + this.substring(1) } fun String?.lower(): String { if (this == null || this.trim { it <= ' ' }.isEmpty()) { return this ?: "" } return this.substring(0, 1).toLowerCase() + this.substring(1) }
apache-2.0
629e756f04634ea51013d8cc9bd774fc
23.166667
78
0.567241
3.515152
false
false
false
false
ktorio/ktor
ktor-network/jvm/test/io/ktor/network/selector/ActorSelectorManagerTest.kt
1
1169
/* * Copyright 2014-2022 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 io.mockk.* import kotlinx.coroutines.* import org.junit.* import org.junit.Test import java.io.* import kotlin.test.* class ActorSelectorManagerTest { val manager = ActorSelectorManager(Dispatchers.Default) @After fun tearDown() { manager.close() } @Test fun testSelectableIsClosed(): Unit = runBlocking { val selectable: Selectable = mockk() every { selectable.interestedOps } returns SelectInterest.READ.flag every { selectable.isClosed } returns true assertFailsWith<IOException> { manager.select(selectable, SelectInterest.READ) } } @Test fun testSelectOnWrongInterest(): Unit = runBlocking { val selectable: Selectable = mockk() every { selectable.interestedOps } returns SelectInterest.READ.flag every { selectable.isClosed } returns false assertFailsWith<IllegalStateException> { manager.select(selectable, SelectInterest.WRITE) } } }
apache-2.0
ee62b2e36c91aa7aed67abd4a513b929
26.186047
119
0.681779
4.566406
false
true
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/widget/TachiyomiTextInputEditText.kt
2
2251
package eu.kanade.tachiyomi.widget import android.content.Context import android.util.AttributeSet import android.widget.EditText import androidx.core.view.inputmethod.EditorInfoCompat import com.google.android.material.textfield.TextInputEditText import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.util.preference.asImmediateFlow import eu.kanade.tachiyomi.widget.TachiyomiTextInputEditText.Companion.setIncognito import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.launchIn import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get /** * A custom [TextInputEditText] that sets [EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING] to imeOptions * if [PreferencesHelper.incognitoMode] is true. Some IMEs may not respect this flag. * * @see setIncognito */ class TachiyomiTextInputEditText @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.editTextStyle ) : TextInputEditText(context, attrs, defStyleAttr) { private var scope: CoroutineScope? = null override fun onAttachedToWindow() { super.onAttachedToWindow() scope = CoroutineScope(SupervisorJob() + Dispatchers.Main) setIncognito(scope!!) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() scope?.cancel() scope = null } companion object { /** * Sets Flow to this [EditText] that sets [EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING] to imeOptions * if [PreferencesHelper.incognitoMode] is true. Some IMEs may not respect this flag. */ fun EditText.setIncognito(viewScope: CoroutineScope) { Injekt.get<PreferencesHelper>().incognitoMode().asImmediateFlow { imeOptions = if (it) { imeOptions or EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING } else { imeOptions and EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING.inv() } }.launchIn(viewScope) } } }
apache-2.0
a4a722dbc01da2b6096f3060232d1714
35.901639
116
0.725011
4.779193
false
false
false
false
JetBrains-Research/viktor
src/main/kotlin/org/jetbrains/bio/viktor/Serialization.kt
1
782
package org.jetbrains.bio.viktor import org.jetbrains.bio.npy.NpyArray import org.jetbrains.bio.npy.NpyFile import org.jetbrains.bio.npy.NpzFile import java.nio.file.Path /** Returns a view of the [NpyArray] as an n-dimensional array. */ fun NpyArray.asF64Array() = asDoubleArray().asF64Array().reshape(*shape) /** Writes a given matrix to [path] in NPY format. */ fun NpyFile.write(path: Path, a: F64Array) { val dense = if (a.isFlattenable) a else a.copy() write(path, dense.flatten().toDoubleArray(), shape = a.shape) } /** Writes a given array into an NPZ file under the specified [name]. */ fun NpzFile.Writer.write(name: String, a: F64Array) { val dense = if (a.isFlattenable) a else a.copy() write(name, dense.flatten().toDoubleArray(), shape = a.shape) }
mit
ba3bef2bb6af7461c72ef4ea2e80e2b6
36.285714
72
0.717391
3.066667
false
false
false
false
Doctoror/ParticleConstellationsLiveWallpaper
app/src/main/java/com/doctoror/particleswallpaper/userprefs/density/DensityPreference.kt
1
2126
/* * Copyright (C) 2017 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.density import android.content.Context import android.util.AttributeSet import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import com.doctoror.particleswallpaper.framework.di.inject import com.doctoror.particleswallpaper.framework.preference.SeekBarPreference import com.doctoror.particleswallpaper.framework.preference.SeekBarPreferenceView import org.koin.core.parameter.parametersOf class DensityPreference @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : SeekBarPreference(context, attrs, defStyle), SeekBarPreferenceView, LifecycleObserver { private val presenter: DensityPreferencePresenter by inject( context = context, parameters = { parametersOf(this as SeekBarPreferenceView) } ) init { isPersistent = false setOnPreferenceChangeListener { _, v -> presenter.onPreferenceChange(v as Int?) true } } @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onStart() { presenter.onStart() } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onStop() { presenter.onStop() } override fun setMaxInt(max: Int) { this.max = max } override fun setProgressInt(progress: Int) { this.progress = progress this.summary = (progress + 1).toString() } override fun getMaxInt() = max }
apache-2.0
6b0edc6c6319cd6179b138ca33b64961
30.731343
91
0.723424
4.693157
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/bridge/JavaScriptActionHandler.kt
1
8137
package org.wikipedia.bridge import android.content.Context import org.wikipedia.BuildConfig import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.auth.AccountUtil import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.page.Namespace import org.wikipedia.page.PageTitle import org.wikipedia.page.PageViewModel import org.wikipedia.settings.Prefs import org.wikipedia.util.DimenUtil import org.wikipedia.util.DimenUtil.densityScalar import org.wikipedia.util.DimenUtil.leadImageHeightForDevice import org.wikipedia.util.L10nUtil import java.util.* import java.util.concurrent.TimeUnit import kotlin.math.roundToInt object JavaScriptActionHandler { @JvmStatic fun setTopMargin(top: Int): String { return String.format(Locale.ROOT, "pcs.c1.Page.setMargins({ top:'%dpx', right:'%dpx', bottom:'%dpx', left:'%dpx' })", top + 16, 16, 48, 16) } @JvmStatic fun getTextSelection(): String { return "pcs.c1.InteractionHandling.getSelectionInfo()" } @JvmStatic fun getOffsets(): String { return "pcs.c1.Sections.getOffsets(document.body);" } @JvmStatic fun getSections(): String { return "pcs.c1.Page.getTableOfContents()" } @JvmStatic fun getProtection(): String { return "pcs.c1.Page.getProtection()" } @JvmStatic fun getRevision(): String { return "pcs.c1.Page.getRevision();" } @JvmStatic fun expandCollapsedTables(expand: Boolean): String { return "pcs.c1.Page.expandOrCollapseTables($expand);" + "var hideableSections = document.getElementsByClassName('pcs-section-hideable-header'); " + "for (var i = 0; i < hideableSections.length; i++) { " + " pcs.c1.Sections.setHidden(hideableSections[i].parentElement.getAttribute('data-mw-section-id'), ${!expand});" + "}" } @JvmStatic fun scrollToFooter(context: Context): String { return "window.scrollTo(0, document.getElementById('pcs-footer-container-menu').offsetTop - ${DimenUtil.getNavigationBarHeight(context)});" } @JvmStatic fun scrollToAnchor(anchorLink: String): String { val anchor = if (anchorLink.contains("#")) anchorLink.substring(anchorLink.indexOf("#") + 1) else anchorLink return "var el = document.getElementById('$anchor');" + "window.scrollTo(0, el.offsetTop - (screen.height / 2));" + "setTimeout(function(){ el.style.backgroundColor='#fc3';" + " setTimeout(function(){ el.style.backgroundColor=null; }, 500);" + "}, 250);" } @JvmStatic fun prepareToScrollTo(anchorLink: String, highlight: Boolean): String { return "pcs.c1.Page.prepareForScrollToAnchor(\"${anchorLink.replace("\"", "\\\"")}\", { highlight: $highlight } )" } @JvmStatic fun setUp(context: Context, title: PageTitle, isPreview: Boolean, toolbarMargin: Int): String { val app: WikipediaApp = WikipediaApp.getInstance() val topActionBarHeight = if (isPreview) 0 else DimenUtil.roundedPxToDp(toolbarMargin.toFloat()) val res = L10nUtil.getStringsForArticleLanguage(title, intArrayOf(R.string.description_edit_add_description, R.string.table_infobox, R.string.table_other, R.string.table_close)) val leadImageHeight = if (isPreview) 0 else (if (DimenUtil.isLandscape(context) || !Prefs.isImageDownloadEnabled()) 0 else (leadImageHeightForDevice(context) / densityScalar).roundToInt() - topActionBarHeight) val topMargin = topActionBarHeight + 16 return String.format(Locale.ROOT, "{" + " \"platform\": \"android\"," + " \"clientVersion\": \"${BuildConfig.VERSION_NAME}\"," + " \"l10n\": {" + " \"addTitleDescription\": \"${res[R.string.description_edit_add_description]}\"," + " \"tableInfobox\": \"${res[R.string.table_infobox]}\"," + " \"tableOther\": \"${res[R.string.table_other]}\"," + " \"tableClose\": \"${res[R.string.table_close]}\"" + " }," + " \"theme\": \"${app.currentTheme.funnelName}\"," + " \"bodyFont\": \"${Prefs.getFontFamily()}\"," + " \"dimImages\": ${(app.currentTheme.isDark && Prefs.shouldDimDarkModeImages())}," + " \"margins\": { \"top\": \"%dpx\", \"right\": \"%dpx\", \"bottom\": \"%dpx\", \"left\": \"%dpx\" }," + " \"leadImageHeight\": \"%dpx\"," + " \"areTablesInitiallyExpanded\": ${!Prefs.isCollapseTablesEnabled()}," + " \"textSizeAdjustmentPercentage\": \"100%%\"," + " \"loadImages\": ${Prefs.isImageDownloadEnabled()}," + " \"userGroups\": \"${AccountUtil.groups}\"" + "}", topMargin, 16, 48, 16, leadImageHeight) } @JvmStatic fun setUpEditButtons(isEditable: Boolean, isProtected: Boolean): String { return "pcs.c1.Page.setEditButtons($isEditable, $isProtected)" } @JvmStatic fun setFooter(model: PageViewModel): String { if (model.page == null) { return "" } val showTalkLink = !(model.page!!.title.namespace() === Namespace.TALK) val showMapLink = model.page!!.pageProperties.geo != null val editedDaysAgo = TimeUnit.MILLISECONDS.toDays(Date().time - model.page!!.pageProperties.lastModified.time) // TODO: page-library also supports showing disambiguation ("similar pages") links and // "page issues". We should be mindful that they exist, even if we don't want them for now. val baseURL = ServiceFactory.getRestBasePath(model.title?.wikiSite!!).trimEnd('/') return "pcs.c1.Footer.add({" + " platform: \"android\"," + " clientVersion: \"${BuildConfig.VERSION_NAME}\"," + " menu: {" + " items: [" + "pcs.c1.Footer.MenuItemType.lastEdited, " + (if (showTalkLink) "pcs.c1.Footer.MenuItemType.talkPage, " else "") + (if (showMapLink) "pcs.c1.Footer.MenuItemType.coordinate, " else "") + " pcs.c1.Footer.MenuItemType.referenceList " + " ]," + " fragment: \"pcs-menu\"," + " editedDaysAgo: $editedDaysAgo" + " }," + " readMore: { " + " itemCount: 3," + " baseURL: \"$baseURL\"," + " fragment: \"pcs-read-more\"" + " }" + "})" } @JvmStatic fun mobileWebChromeShim(): String { return "(function() {" + "let style = document.createElement('style');" + "style.innerHTML = '.header-chrome { visibility: hidden; margin-top: 48px; height: 0px; } #page-secondary-actions { display: none; } .mw-footer { padding-bottom: 72px; } .page-actions-menu { display: none; } .minerva__tab-container { display: none; }';" + "document.head.appendChild(style);" + "})();" } @JvmStatic fun getElementAtPosition(x: Int, y: Int): String { return "(function() {" + " let element = document.elementFromPoint($x, $y);" + " let result = {};" + " result.left = element.getBoundingClientRect().left;" + " result.top = element.getBoundingClientRect().top;" + " result.width = element.clientWidth;" + " result.height = element.clientHeight;" + " result.src = element.src;" + " return result;" + "})();" } data class ImageHitInfo(val left: Float = 0f, val top: Float = 0f, val width: Float = 0f, val height: Float = 0f, val src: String = "", val centerCrop: Boolean = false) }
apache-2.0
0ba1c5b7a21c92ad569be18eb0febeeb
45.497143
271
0.570849
4.316711
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/repl/src/org/jetbrains/kotlin/console/HistoryUpdater.kt
6
3295
// 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.console import com.intellij.execution.console.LanguageConsoleImpl import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.markup.HighlighterLayer import com.intellij.openapi.editor.markup.HighlighterTargetArea import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.console.gutter.ConsoleIndicatorRenderer import org.jetbrains.kotlin.console.gutter.ReplIcons class HistoryUpdater(private val runner: KotlinConsoleRunner) { private val consoleView: LanguageConsoleImpl by lazy { runner.consoleView as LanguageConsoleImpl } fun printNewCommandInHistory(trimmedCommandText: String): TextRange { val historyEditor = consoleView.historyViewer addLineBreakIfNeeded(historyEditor) val startOffset = historyEditor.document.textLength addCommandTextToHistoryEditor(trimmedCommandText) val endOffset = historyEditor.document.textLength addFoldingRegion(historyEditor, startOffset, endOffset, trimmedCommandText) historyEditor.markupModel.addRangeHighlighter( startOffset, endOffset, HighlighterLayer.LAST, null, HighlighterTargetArea.EXACT_RANGE ).apply { val historyMarker = if (runner.isReadLineMode) ReplIcons.READLINE_MARKER else ReplIcons.COMMAND_MARKER gutterIconRenderer = ConsoleIndicatorRenderer(historyMarker) } historyEditor.scrollingModel.scrollVertically(endOffset) return TextRange(startOffset, endOffset) } private fun addCommandTextToHistoryEditor(trimmedCommandText: String) { val consoleEditor = consoleView.consoleEditor val consoleDocument = consoleEditor.document consoleDocument.setText(trimmedCommandText) LanguageConsoleImpl.printWithHighlighting(consoleView, consoleEditor, TextRange(0, consoleDocument.textLength)) consoleView.flushDeferredText() consoleDocument.setText("") } private fun addLineBreakIfNeeded(historyEditor: EditorEx) { if (runner.isReadLineMode) return val historyDocument = historyEditor.document val historyText = historyDocument.text val textLength = historyText.length if (!historyText.endsWith('\n')) { historyDocument.insertString(textLength, "\n") if (textLength == 0) // this will work first time after 'Clear all' action runner.addGutterIndicator(historyEditor, ReplIcons.HISTORY_INDICATOR) else historyDocument.insertString(textLength + 1, "\n") } else if (!historyText.endsWith("\n\n")) { historyDocument.insertString(textLength, "\n") } } private fun addFoldingRegion(historyEditor: EditorEx, startOffset: Int, endOffset: Int, command: String) { val cmdLines = command.lines() val linesCount = cmdLines.size if (linesCount < 2) return val foldingModel = historyEditor.foldingModel foldingModel.runBatchFoldingOperation { foldingModel.addFoldRegion(startOffset, endOffset, "${cmdLines[0]} ...") } } }
apache-2.0
f5b17f87c6c0c2f17f20d51f86f5d9ba
41.805195
158
0.729287
5.22187
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinRedundantOverrideInspection.kt
1
9134
// 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.inspections import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.getDeepestSuperDeclarations import org.jetbrains.kotlin.idea.util.hasNonSuppressAnnotation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.JavaDescriptorVisibilities import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import org.jetbrains.kotlin.synthetic.canBePropertyAccessor import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.types.typeUtil.makeNotNullable class KotlinRedundantOverrideInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = namedFunctionVisitor(fun(function) { val funKeyword = function.funKeyword ?: return val modifierList = function.modifierList ?: return if (!modifierList.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return if (MODIFIER_EXCLUDE_OVERRIDE.any { modifierList.hasModifier(it) }) return if (function.hasNonSuppressAnnotation) return if (function.containingClass()?.isData() == true) return val bodyExpression = function.bodyExpression ?: return val qualifiedExpression = when (bodyExpression) { is KtDotQualifiedExpression -> bodyExpression is KtBlockExpression -> { when (val body = bodyExpression.statements.singleOrNull()) { is KtReturnExpression -> body.returnedExpression is KtDotQualifiedExpression -> body.takeIf { _ -> function.typeReference.let { it == null || it.text == "Unit" } } else -> null } } else -> null } as? KtDotQualifiedExpression ?: return val superExpression = qualifiedExpression.receiverExpression as? KtSuperExpression ?: return if (superExpression.superTypeQualifier != null) return val superCallElement = qualifiedExpression.selectorExpression as? KtCallElement ?: return if (!isSameFunctionName(superCallElement, function)) return if (!isSameArguments(superCallElement, function)) return val context = function.analyze() val functionDescriptor = context[BindingContext.FUNCTION, function] ?: return val functionParams = functionDescriptor.valueParameters val superCallDescriptor = superCallElement.resolveToCall()?.resultingDescriptor ?: return val superCallFunctionParams = superCallDescriptor.valueParameters if (functionParams.size == superCallFunctionParams.size && functionParams.zip(superCallFunctionParams).any { it.first.type != it.second.type } ) return if (function.hasDerivedProperty(functionDescriptor, context)) return val overriddenDescriptors = functionDescriptor.original.overriddenDescriptors if (overriddenDescriptors.any { it is JavaMethodDescriptor && it.visibility == JavaDescriptorVisibilities.PACKAGE_VISIBILITY }) return if (overriddenDescriptors.any { it.modality == Modality.ABSTRACT }) { if (superCallDescriptor.fqNameSafe in METHODS_OF_ANY) return if (superCallDescriptor.isOverridingMethodOfAny() && !superCallDescriptor.isImplementedInContainingClass()) return } if (function.isAmbiguouslyDerived(overriddenDescriptors, context)) return val descriptor = holder.manager.createProblemDescriptor( function, TextRange(modifierList.startOffsetInParent, funKeyword.endOffset - function.startOffset), KotlinBundle.message("redundant.overriding.method"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, RedundantOverrideFix() ) holder.registerProblem(descriptor) }) private fun isSameArguments(superCallElement: KtCallElement, function: KtNamedFunction): Boolean { val arguments = superCallElement.valueArguments val parameters = function.valueParameters if (arguments.size != parameters.size) return false return arguments.zip(parameters).all { (argument, parameter) -> argument.getArgumentExpression()?.text == parameter.name } } private fun isSameFunctionName(superSelectorExpression: KtCallElement, function: KtNamedFunction): Boolean { val superCallMethodName = superSelectorExpression.getCallNameExpression()?.text ?: return false return function.name == superCallMethodName } private fun CallableDescriptor.isOverridingMethodOfAny() = (this as? CallableMemberDescriptor)?.getDeepestSuperDeclarations().orEmpty().any { it.fqNameSafe in METHODS_OF_ANY } private fun CallableDescriptor.isImplementedInContainingClass() = (containingDeclaration as? LazyClassDescriptor)?.declaredCallableMembers.orEmpty().any { it == this } private fun KtNamedFunction.hasDerivedProperty(functionDescriptor: FunctionDescriptor?, context: BindingContext): Boolean { if (functionDescriptor == null) return false val functionName = nameAsName ?: return false if (!canBePropertyAccessor(functionName.asString())) return false val functionType = functionDescriptor.returnType val isSetter = functionType?.isUnit() == true val valueParameters = valueParameters val singleValueParameter = valueParameters.singleOrNull() if (isSetter && singleValueParameter == null || !isSetter && valueParameters.isNotEmpty()) return false val propertyType = (if (isSetter) context[BindingContext.VALUE_PARAMETER, singleValueParameter]?.type else functionType)?.makeNotNullable() return SyntheticJavaPropertyDescriptor.propertyNamesByAccessorName(functionName).any { val propertyName = it.asString() containingClassOrObject?.declarations?.find { d -> d is KtProperty && d.name == propertyName && d.resolveToDescriptorIfAny()?.type?.makeNotNullable() == propertyType } != null } } private class RedundantOverrideFix : LocalQuickFix { override fun getName() = KotlinBundle.message("redundant.override.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { descriptor.psiElement.delete() } } companion object { private val MODIFIER_EXCLUDE_OVERRIDE = KtTokens.MODIFIER_KEYWORDS_ARRAY.asList() - KtTokens.OVERRIDE_KEYWORD private val METHODS_OF_ANY = listOf("equals", "hashCode", "toString").map { FqName("kotlin.Any.$it") } } } private fun KtNamedFunction.isAmbiguouslyDerived(overriddenDescriptors: Collection<FunctionDescriptor>?, context: BindingContext): Boolean { if (overriddenDescriptors == null || overriddenDescriptors.size < 2) return false // Two+ functions // At least one default in interface or abstract in class, or just something from Java if (overriddenDescriptors.any { overriddenFunction -> overriddenFunction is JavaMethodDescriptor || when ((overriddenFunction.containingDeclaration as? ClassDescriptor)?.kind) { ClassKind.CLASS -> overriddenFunction.modality == Modality.ABSTRACT ClassKind.INTERFACE -> overriddenFunction.modality != Modality.ABSTRACT else -> false } } ) return true val delegatedSuperTypeEntries = containingClassOrObject?.superTypeListEntries?.filterIsInstance<KtDelegatedSuperTypeEntry>() ?: return false if (delegatedSuperTypeEntries.isEmpty()) return false val delegatedSuperDeclarations = delegatedSuperTypeEntries.mapNotNull { entry -> context[BindingContext.TYPE, entry.typeReference]?.constructor?.declarationDescriptor } return overriddenDescriptors.any { it.containingDeclaration in delegatedSuperDeclarations } }
apache-2.0
23635378c872d8f04a28c9dc6d2385b1
53.047337
146
0.711189
5.832695
false
false
false
false
PaulWoitaschek/MaterialAudiobookPlayer
app/src/main/java/de/ph1b/audiobook/features/MainActivity.kt
1
5449
package de.ph1b.audiobook.features import android.content.Context import android.content.Intent import android.os.Bundle import android.view.ViewGroup import com.bluelinelabs.conductor.Conductor import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.Router import com.bluelinelabs.conductor.RouterTransaction import de.ph1b.audiobook.R import de.ph1b.audiobook.data.repo.BookRepository import de.ph1b.audiobook.features.bookOverview.BookOverviewController import de.ph1b.audiobook.features.bookPlaying.BookPlayController import de.ph1b.audiobook.features.bookSearch.BookSearchHandler import de.ph1b.audiobook.features.bookSearch.BookSearchParser import de.ph1b.audiobook.injection.PrefKeys import de.ph1b.audiobook.injection.appComponent import de.ph1b.audiobook.misc.PermissionHelper import de.ph1b.audiobook.misc.Permissions import de.ph1b.audiobook.misc.RouterProvider import de.ph1b.audiobook.misc.conductor.asTransaction import de.ph1b.audiobook.persistence.pref.Pref import de.ph1b.audiobook.playback.PlayerController import kotlinx.android.synthetic.main.activity_book.* import java.util.UUID import javax.inject.Inject import javax.inject.Named /** * Activity that coordinates the book shelf and play screens. */ class MainActivity : BaseActivity(), RouterProvider { private lateinit var permissionHelper: PermissionHelper private lateinit var permissions: Permissions @field:[Inject Named(PrefKeys.CURRENT_BOOK)] lateinit var currentBookIdPref: Pref<UUID> @field:[Inject Named(PrefKeys.SINGLE_BOOK_FOLDERS)] lateinit var singleBookFolderPref: Pref<Set<String>> @field:[Inject Named(PrefKeys.COLLECTION_BOOK_FOLDERS)] lateinit var collectionBookFolderPref: Pref<Set<String>> @Inject lateinit var playerController: PlayerController @Inject lateinit var repo: BookRepository @Inject lateinit var bookSearchParser: BookSearchParser @Inject lateinit var bookSearchHandler: BookSearchHandler private lateinit var router: Router override fun onCreate(savedInstanceState: Bundle?) { appComponent.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_book) permissions = Permissions(this) permissionHelper = PermissionHelper(this, permissions) router = Conductor.attachRouter(this, root, savedInstanceState) if (!router.hasRootController()) { setupRouter() } router.addChangeListener( object : ControllerChangeHandler.ControllerChangeListener { override fun onChangeStarted( to: Controller?, from: Controller?, isPush: Boolean, container: ViewGroup, handler: ControllerChangeHandler ) { from?.setOptionsMenuHidden(true) } override fun onChangeCompleted( to: Controller?, from: Controller?, isPush: Boolean, container: ViewGroup, handler: ControllerChangeHandler ) { from?.setOptionsMenuHidden(false) } } ) setupFromIntent(intent) } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) setupFromIntent(intent) } private fun setupFromIntent(intent: Intent?) { bookSearchParser.parse(intent)?.let { bookSearchHandler.handle(it) } } private fun setupRouter() { // if we should enter a book set the backstack and return early intent.getStringExtra(NI_GO_TO_BOOK) ?.let(UUID::fromString) ?.let(repo::bookById) ?.let { val bookShelf = RouterTransaction.with(BookOverviewController()) val bookPlay = BookPlayController(it.id).asTransaction() router.setBackstack(listOf(bookShelf, bookPlay), null) return } // if we should play the current book, set the backstack and return early if (intent?.action == "playCurrent") { repo.bookById(currentBookIdPref.value)?.let { val bookShelf = RouterTransaction.with(BookOverviewController()) val bookPlay = BookPlayController(it.id).asTransaction() router.setBackstack(listOf(bookShelf, bookPlay), null) playerController.play() return } } val rootTransaction = RouterTransaction.with(BookOverviewController()) router.setRoot(rootTransaction) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) this.permissions.onRequestPermissionsResult(requestCode, permissions, grantResults) } override fun provideRouter() = router override fun onStart() { super.onStart() val anyFolderSet = collectionBookFolderPref.value.size + singleBookFolderPref.value.size > 0 if (anyFolderSet) { permissionHelper.storagePermission() } } override fun onBackPressed() { if (router.backstackSize == 1) { super.onBackPressed() } else router.handleBack() } companion object { private const val NI_GO_TO_BOOK = "niGotoBook" /** Returns an intent that lets you go directly to the playback screen for a certain book **/ fun goToBookIntent(c: Context, bookId: UUID) = Intent(c, MainActivity::class.java).apply { putExtra(NI_GO_TO_BOOK, bookId.toString()) flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK } } }
lgpl-3.0
0e4f38ed12aabe5209e2c3b33cd7eb4e
31.825301
97
0.736282
4.510762
false
false
false
false
Masterzach32/SwagBot
src/main/kotlin/extensions/AudioTrack.kt
1
735
package xyz.swagbot.extensions import com.sedmelluq.discord.lavaplayer.track.* import discord4j.common.util.* import discord4j.core.`object`.entity.* import discord4j.core.`object`.entity.channel.* import xyz.swagbot.features.music.* val AudioTrack.context: TrackContext get() = getUserData(TrackContext::class.java) fun AudioTrack.setTrackContext(member: Member, channel: MessageChannel) = setTrackContext(member.id, channel.id) fun AudioTrack.setTrackContext(memberId: Snowflake, channelId: Snowflake) { userData = TrackContext(memberId, channelId) } val AudioTrack.formattedPosition: String get() = getFormattedTime(position/1000) val AudioTrack.formattedLength: String get() = getFormattedTime(duration/1000)
gpl-2.0
8d7037eb9adc84374abc3e6a71e3a82d
32.409091
112
0.791837
4.038462
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreatePropertyDelegateAccessorsActionFactory.kt
1
4710
// 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.createCallable import com.intellij.util.SmartList import org.jetbrains.kotlin.builtins.ReflectionTypes import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.VariableAccessorDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptorWithAccessors import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.util.OperatorNameConventions object CreatePropertyDelegateAccessorsActionFactory : CreateCallableMemberFromUsageFactory<KtExpression>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtExpression? { return diagnostic.psiElement as? KtExpression } override fun extractFixData(element: KtExpression, diagnostic: Diagnostic): List<CallableInfo> { val context = element.analyze() fun isApplicableForAccessor(accessor: VariableAccessorDescriptor?): Boolean = accessor != null && context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, accessor] == null val property = element.getNonStrictParentOfType<KtProperty>() ?: return emptyList() val propertyDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, property] as? VariableDescriptorWithAccessors ?: return emptyList() if (propertyDescriptor is LocalVariableDescriptor && !element.languageVersionSettings.supportsFeature(LanguageFeature.LocalDelegatedProperties) ) { return emptyList() } val propertyReceiver = propertyDescriptor.extensionReceiverParameter ?: propertyDescriptor.dispatchReceiverParameter val propertyType = propertyDescriptor.type val accessorReceiverType = TypeInfo(element, Variance.IN_VARIANCE) val builtIns = propertyDescriptor.builtIns val thisRefParam = ParameterInfo(TypeInfo(propertyReceiver?.type ?: builtIns.nullableNothingType, Variance.IN_VARIANCE)) val kPropertyStarType = ReflectionTypes.createKPropertyStarType(propertyDescriptor.module) ?: return emptyList() val metadataParam = ParameterInfo(TypeInfo(kPropertyStarType, Variance.IN_VARIANCE), "property") val callableInfos = SmartList<CallableInfo>() val psiFactory = KtPsiFactory(element.project) if (isApplicableForAccessor(propertyDescriptor.getter)) { val getterInfo = FunctionInfo( name = OperatorNameConventions.GET_VALUE.asString(), receiverTypeInfo = accessorReceiverType, returnTypeInfo = TypeInfo(propertyType, Variance.OUT_VARIANCE), parameterInfos = listOf(thisRefParam, metadataParam), modifierList = psiFactory.createModifierList(KtTokens.OPERATOR_KEYWORD) ) callableInfos.add(getterInfo) } if (propertyDescriptor.isVar && isApplicableForAccessor(propertyDescriptor.setter)) { val newValueParam = ParameterInfo(TypeInfo(propertyType, Variance.IN_VARIANCE)) val setterInfo = FunctionInfo( name = OperatorNameConventions.SET_VALUE.asString(), receiverTypeInfo = accessorReceiverType, returnTypeInfo = TypeInfo(builtIns.unitType, Variance.OUT_VARIANCE), parameterInfos = listOf(thisRefParam, metadataParam, newValueParam), modifierList = psiFactory.createModifierList(KtTokens.OPERATOR_KEYWORD) ) callableInfos.add(setterInfo) } return callableInfos } }
apache-2.0
0683166154d0114bc6c887bbba337747
52.522727
158
0.763057
5.674699
false
false
false
false
youdonghai/intellij-community
platform/projectModel-api/src/org/jetbrains/concurrency/AsyncPromise.kt
1
8273
/* * Copyright 2000-2016 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.concurrency import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Getter import com.intellij.util.Consumer import com.intellij.util.Function import org.jetbrains.concurrency.Promise.State import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import java.util.concurrent.atomic.AtomicReference private val LOG = Logger.getInstance(AsyncPromise::class.java) open class AsyncPromise<T> : Promise<T>, Getter<T> { private val doneRef = AtomicReference<Consumer<in T>?>() private val rejectedRef = AtomicReference<Consumer<in Throwable>?>() private val stateRef = AtomicReference(State.PENDING) // result object or error message @Volatile private var result: Any? = null override fun getState() = stateRef.get()!! override fun done(done: Consumer<in T>): Promise<T> { setHandler(doneRef, done, State.FULFILLED) return this } override fun rejected(rejected: Consumer<Throwable>): Promise<T> { setHandler(rejectedRef, rejected, State.REJECTED) return this } @Suppress("UNCHECKED_CAST") override fun get() = if (state == State.FULFILLED) result as T? else null override fun <SUB_RESULT> then(handler: Function<in T, out SUB_RESULT>): Promise<SUB_RESULT> { @Suppress("UNCHECKED_CAST") when (state) { State.PENDING -> { } State.FULFILLED -> return DonePromise<SUB_RESULT>(handler.`fun`(result as T?)) State.REJECTED -> return rejectedPromise(result as Throwable) } val promise = AsyncPromise<SUB_RESULT>() addHandlers(Consumer({ result -> promise.catchError { if (handler is Obsolescent && handler.isObsolete) { promise.cancel() } else { promise.setResult(handler.`fun`(result)) } } }), Consumer({ promise.setError(it) })) return promise } override fun notify(child: AsyncPromise<in T>) { LOG.assertTrue(child !== this) when (state) { State.PENDING -> { addHandlers(Consumer({ child.catchError { child.setResult(it) } }), Consumer({ child.setError(it) })) } State.FULFILLED -> { @Suppress("UNCHECKED_CAST") child.setResult(result as T) } State.REJECTED -> { child.setError((result as Throwable?)!!) } } } override fun <SUB_RESULT> thenAsync(handler: Function<in T, Promise<SUB_RESULT>>): Promise<SUB_RESULT> { @Suppress("UNCHECKED_CAST") when (state) { State.PENDING -> { } State.FULFILLED -> return handler.`fun`(result as T?) State.REJECTED -> return rejectedPromise(result as Throwable) } val promise = AsyncPromise<SUB_RESULT>() val rejectedHandler = Consumer<Throwable>({ promise.setError(it) }) addHandlers(Consumer({ promise.catchError { handler.`fun`(it) .done { promise.catchError { promise.setResult(it) } } .rejected(rejectedHandler) } }), rejectedHandler) return promise } override fun processed(fulfilled: AsyncPromise<in T>): Promise<T> { when (state) { State.PENDING -> { addHandlers(Consumer({ result -> fulfilled.catchError { fulfilled.setResult(result) } }), Consumer({ fulfilled.setError(it) })) } State.FULFILLED -> { @Suppress("UNCHECKED_CAST") fulfilled.setResult(result as T) } State.REJECTED -> { fulfilled.setError((result as Throwable?)!!) } } return this } private fun addHandlers(done: Consumer<T>, rejected: Consumer<Throwable>) { setHandler(doneRef, done, State.FULFILLED) setHandler(rejectedRef, rejected, State.REJECTED) } fun setResult(result: T?) { if (!stateRef.compareAndSet(State.PENDING, State.FULFILLED)) { return } this.result = result val done = doneRef.getAndSet(null) rejectedRef.set(null) if (done != null && !isObsolete(done)) { done.consume(result) } } fun setError(error: String) = setError(createError(error)) fun cancel() { setError(OBSOLETE_ERROR) } open fun setError(error: Throwable): Boolean { if (!stateRef.compareAndSet(State.PENDING, State.REJECTED)) { LOG.errorIfNotMessage(error) return false } result = error val rejected = rejectedRef.getAndSet(null) doneRef.set(null) if (rejected == null) { LOG.errorIfNotMessage(error) } else if (!isObsolete(rejected)) { rejected.consume(error) } return true } override fun processed(processed: Consumer<in T>): Promise<T> { done(processed) rejected { processed.consume(null) } return this } override fun blockingGet(timeout: Int, timeUnit: TimeUnit): T? { if (isPending) { val latch = CountDownLatch(1) processed { latch.countDown() } if (!latch.await(timeout.toLong(), timeUnit)) { throw TimeoutException() } } @Suppress("UNCHECKED_CAST") if (isRejected) { throw (result as Throwable) } else { return result as T? } } private fun <T> setHandler(ref: AtomicReference<Consumer<in T>?>, newConsumer: Consumer<in T>, targetState: State) { if (isObsolete(newConsumer)) { return } if (state != State.PENDING) { if (state == targetState) { @Suppress("UNCHECKED_CAST") newConsumer.consume(result as T?) } return } while (true) { val oldConsumer = ref.get() val newEffectiveConsumer = when (oldConsumer) { null -> newConsumer is CompoundConsumer<*> -> { @Suppress("UNCHECKED_CAST") val compoundConsumer = oldConsumer as CompoundConsumer<T> var executed = true synchronized(compoundConsumer) { compoundConsumer.consumers?.let { it.add(newConsumer) executed = false } } // clearHandlers was called - just execute newConsumer if (executed) { if (state == targetState) { @Suppress("UNCHECKED_CAST") newConsumer.consume(result as T?) } return } compoundConsumer } else -> CompoundConsumer(oldConsumer, newConsumer) } if (ref.compareAndSet(oldConsumer, newEffectiveConsumer)) { break } } if (state == targetState) { ref.getAndSet(null)?.let { @Suppress("UNCHECKED_CAST") it.consume(result as T?) } } } } private class CompoundConsumer<T>(c1: Consumer<in T>, c2: Consumer<in T>) : Consumer<T> { var consumers: MutableList<Consumer<in T>>? = ArrayList() init { synchronized(this) { consumers!!.add(c1) consumers!!.add(c2) } } override fun consume(t: T) { val list = synchronized(this) { val list = consumers consumers = null list } ?: return for (consumer in list) { if (!isObsolete(consumer)) { consumer.consume(t) } } } } internal fun isObsolete(consumer: Consumer<*>?) = consumer is Obsolescent && consumer.isObsolete inline fun <T> AsyncPromise<*>.catchError(runnable: () -> T): T? { try { return runnable() } catch (e: Throwable) { setError(e) return null } }
apache-2.0
c8e45c41456df2095c4b8cb39d0867e3
27.238908
135
0.608485
4.457435
false
false
false
false
allotria/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.kt
1
6157
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.ex import com.intellij.diff.util.DiffUtil import com.intellij.diff.util.Side import com.intellij.ide.GeneralSettings import com.intellij.ide.lightEdit.LightEditCompatible import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.markup.MarkupEditorFilter import com.intellij.openapi.editor.markup.MarkupEditorFilterFactory import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.ex.DocumentTracker.Block import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.concurrency.annotations.RequiresEdt import org.jetbrains.annotations.CalledInAny import java.awt.Point import java.util.* interface LineStatusTracker<out R : Range> : LineStatusTrackerI<R> { override val project: Project override val virtualFile: VirtualFile @RequiresEdt fun isAvailableAt(editor: Editor): Boolean { return editor.settings.isLineMarkerAreaShown && !DiffUtil.isDiffEditor(editor) } @RequiresEdt fun scrollAndShowHint(range: Range, editor: Editor) @RequiresEdt fun showHint(range: Range, editor: Editor) } interface LocalLineStatusTracker<R : Range> : LineStatusTracker<R> { fun release() @CalledInAny fun freeze() @CalledInAny fun unfreeze() var mode: Mode class Mode(val isVisible: Boolean, val showErrorStripeMarkers: Boolean, val detectWhitespaceChangedLines: Boolean) @RequiresEdt override fun isAvailableAt(editor: Editor): Boolean { return mode.isVisible && super.isAvailableAt(editor) } } abstract class LocalLineStatusTrackerImpl<R : Range>( final override val project: Project, document: Document, final override val virtualFile: VirtualFile ) : LineStatusTrackerBase<R>(project, document), LocalLineStatusTracker<R> { abstract override val renderer: LocalLineStatusMarkerRenderer private val innerRangesHandler = MyInnerRangesDocumentTrackerHandler() override var mode: LocalLineStatusTracker.Mode = LocalLineStatusTracker.Mode(true, true, false) set(value) { if (value == mode) return field = value innerRangesHandler.resetInnerRanges() updateHighlighters() } init { documentTracker.addHandler(LocalDocumentTrackerHandler()) documentTracker.addHandler(innerRangesHandler) } @RequiresEdt override fun isDetectWhitespaceChangedLines(): Boolean = mode.isVisible && mode.detectWhitespaceChangedLines override fun isClearLineModificationFlagOnRollback(): Boolean = true protected abstract var Block.innerRanges: List<Range.InnerRange>? @RequiresEdt abstract fun setBaseRevision(vcsContent: CharSequence) override fun scrollAndShowHint(range: Range, editor: Editor) { renderer.scrollAndShow(editor, range) } override fun showHint(range: Range, editor: Editor) { renderer.showAfterScroll(editor, range) } protected open class LocalLineStatusMarkerRenderer(open val tracker: LocalLineStatusTrackerImpl<*>) : LineStatusMarkerPopupRenderer(tracker) { override fun getEditorFilter(): MarkupEditorFilter? = MarkupEditorFilterFactory.createIsNotDiffFilter() override fun shouldPaintGutter(): Boolean { return tracker.mode.isVisible } override fun shouldPaintErrorStripeMarkers(): Boolean { return tracker.mode.isVisible && tracker.mode.showErrorStripeMarkers } override fun createToolbarActions(editor: Editor, range: Range, mousePosition: Point?): List<AnAction> { val actions = ArrayList<AnAction>() actions.add(ShowPrevChangeMarkerAction(editor, range)) actions.add(ShowNextChangeMarkerAction(editor, range)) actions.add(RollbackLineStatusRangeAction(editor, range)) actions.add(ShowLineStatusRangeDiffAction(editor, range)) actions.add(CopyLineStatusRangeAction(editor, range)) actions.add(ToggleByWordDiffAction(editor, range, mousePosition)) return actions } private inner class RollbackLineStatusRangeAction(editor: Editor, range: Range) : RangeMarkerAction(editor, range, IdeActions.SELECTED_CHANGES_ROLLBACK), LightEditCompatible { override fun isEnabled(editor: Editor, range: Range): Boolean = true override fun actionPerformed(editor: Editor, range: Range) { RollbackLineStatusAction.rollback(tracker, range, editor) } } } private inner class LocalDocumentTrackerHandler : DocumentTracker.Handler { override fun afterBulkRangeChange(isDirty: Boolean) { if (blocks.isEmpty()) { fireFileUnchanged() } } @RequiresEdt private fun fireFileUnchanged() { if (GeneralSettings.getInstance().isSaveOnFrameDeactivation) { // later to avoid saving inside document change event processing and deadlock with CLM. ApplicationManager.getApplication().invokeLater(Runnable { FileDocumentManager.getInstance().saveDocument(document) }, project.disposed) } } } private inner class MyInnerRangesDocumentTrackerHandler : InnerRangesDocumentTrackerHandler() { override fun isDetectWhitespaceChangedLines(): Boolean = mode.let { it.isVisible && it.detectWhitespaceChangedLines } override var Block.innerRanges: List<Range.InnerRange>? get() { val block = this with(this@LocalLineStatusTrackerImpl) { return block.innerRanges } } set(value) { val block = this with(this@LocalLineStatusTrackerImpl) { block.innerRanges = value } } } @CalledInAny override fun freeze() { documentTracker.freeze(Side.LEFT) documentTracker.freeze(Side.RIGHT) } @RequiresEdt override fun unfreeze() { documentTracker.unfreeze(Side.LEFT) documentTracker.unfreeze(Side.RIGHT) } }
apache-2.0
8240875e0017e79854d8added723f85a
32.644809
140
0.752639
4.840409
false
false
false
false
Polidea/Polithings
a4988/src/main/java/com/polidea/androidthings/driver/a4988/driver/A4988.kt
1
5212
package com.polidea.androidthings.driver.a4988.driver import android.util.Log import com.polidea.androidthings.driver.steppermotor.Direction import com.polidea.androidthings.driver.steppermotor.awaiter.Awaiter import com.polidea.androidthings.driver.steppermotor.awaiter.DefaultAwaiter import com.polidea.androidthings.driver.steppermotor.driver.StepDuration import com.polidea.androidthings.driver.steppermotor.driver.StepperMotorDriver import com.polidea.androidthings.driver.steppermotor.gpio.GpioFactory import com.polidea.androidthings.driver.steppermotor.gpio.StepperMotorGpio import java.io.IOException class A4988 internal constructor(private val stepGpioId: String, private val dirGpioId: String?, private val ms1GpioId: String?, private val ms2GpioId: String?, private val ms3GpioId: String?, private val enGpioId: String?, private val gpioFactory: GpioFactory, private val awaiter: Awaiter) : StepperMotorDriver() { constructor(stepGpioId: String) : this(stepGpioId, null, null, null, null, null, GpioFactory(), DefaultAwaiter()) constructor(stepGpioId: String, dirGpioId: String) : this(stepGpioId, dirGpioId, null, null, null, null, GpioFactory(), DefaultAwaiter()) constructor(stepGpioId: String, dirGpioId: String?, ms1GpioId: String?, ms2GpioId: String?, ms3GpioId: String?, enGpioId: String?) : this(stepGpioId, dirGpioId, ms1GpioId, ms2GpioId, ms3GpioId, enGpioId, GpioFactory(), DefaultAwaiter()) override var direction = Direction.CLOCKWISE set(value) { setDirectionOnBoard(value) field = value } var resolution = A4988Resolution.SIXTEENTH set(value) { setResolutionOnBoard(value) field = value } var enabled = false set(value) { setEnabledOnBoard(value) field = value } private lateinit var stepGpio: StepperMotorGpio private var dirGpio: StepperMotorGpio? = null private var ms1Gpio: StepperMotorGpio? = null private var ms2Gpio: StepperMotorGpio? = null private var ms3Gpio: StepperMotorGpio? = null private var enGpio: StepperMotorGpio? = null private var gpiosOpened = false override fun open() { if (gpiosOpened) { return } try { stepGpio = stepGpioId.openGpio()!! dirGpio = dirGpioId.openGpio() ms1Gpio = ms1GpioId.openGpio() ms2Gpio = ms2GpioId.openGpio() ms3Gpio = ms3GpioId.openGpio() enGpio = enGpioId.openGpio() gpiosOpened = true } catch (e: Exception) { close() throw e } direction = Direction.CLOCKWISE resolution = A4988Resolution.SIXTEENTH enabled = false } override fun close() { arrayOf(stepGpio, dirGpio, ms1Gpio, ms2Gpio, ms3Gpio, enGpio).forEach { try { it?.close() } catch (e: IOException) { Log.e(TAG, "Couldn't close a gpio correctly.", e.cause) } } gpiosOpened = false } override fun performStep(stepDuration: StepDuration) { if (enGpio != null && !enabled) { throw IllegalStateException("A4988 is disabled. Enable it before performing a stepDuration.") } val pulseDurationMillis = stepDuration.millis / 2 val pulseDurationNanos = stepDuration.nanos / 2 stepGpio.value = true awaiter.await(pulseDurationMillis, pulseDurationNanos) stepGpio.value = false awaiter.await(pulseDurationMillis, pulseDurationNanos) } private fun setDirectionOnBoard(direction: Direction) { when (direction) { Direction.CLOCKWISE -> dirGpio?.value = true Direction.COUNTERCLOCKWISE -> dirGpio?.value = false } } private fun setResolutionOnBoard(a4988Resolution: A4988Resolution) { when (a4988Resolution) { A4988Resolution.FULL -> setResolutionGpios(true, true, true) A4988Resolution.HALF -> setResolutionGpios(true, true, false) A4988Resolution.QUARTER -> setResolutionGpios(false, true, false) A4988Resolution.EIGHT -> setResolutionGpios(true, false, false) A4988Resolution.SIXTEENTH -> setResolutionGpios(false, false, false) } } private fun setEnabledOnBoard(enabled: Boolean) { enGpio?.value = !enabled } private fun setResolutionGpios(ms1Value: Boolean, ms2Value: Boolean, ms3Value: Boolean) { ms1Gpio?.value = ms1Value ms2Gpio?.value = ms2Value ms3Gpio?.value = ms3Value } private fun String?.openGpio(): StepperMotorGpio? = if (this != null) StepperMotorGpio(gpioFactory.openGpio(this)) else null companion object { val TAG = "A4988" } }
mit
0b16aec16b604a69194ff27fa473bca5
34.951724
115
0.620299
4.86648
false
false
false
false
F43nd1r/acra-backend
acrarium/src/main/kotlin/com/faendir/acra/ui/view/error/ErrorView.kt
1
2196
package com.faendir.acra.ui.view.error import com.faendir.acra.i18n.Messages import com.faendir.acra.navigation.View import com.faendir.acra.ui.component.Translatable import com.faendir.acra.ui.ext.SizeUnit import com.faendir.acra.ui.ext.flexLayout import com.faendir.acra.ui.ext.paragraph import com.faendir.acra.ui.ext.setMargin import com.faendir.acra.ui.ext.translatableButton import com.faendir.acra.ui.ext.translatableParagraph import com.faendir.acra.ui.view.Overview import com.vaadin.flow.component.HasComponents import com.vaadin.flow.component.HasSize import com.vaadin.flow.component.html.Paragraph import com.vaadin.flow.component.orderedlayout.FlexComponent import com.vaadin.flow.component.orderedlayout.FlexLayout import com.vaadin.flow.router.BeforeEnterEvent import com.vaadin.flow.router.ErrorParameter import com.vaadin.flow.router.HasErrorParameter import com.vaadin.flow.router.NotFoundException import com.vaadin.flow.router.RouterLink import com.vaadin.flow.spring.annotation.SpringComponent import com.vaadin.flow.spring.annotation.UIScope import com.vaadin.flow.spring.router.SpringRouteNotFoundError @Suppress("LeakingThis") @View class ErrorView : SpringRouteNotFoundError() /*need to extend RouteNotFoundError due to vaadin-spring bug: TODO: Remove when https://github.com/vaadin/spring/issues/661 is fixed*/, HasErrorParameter<NotFoundException>, HasComponents, HasSize { init { setSizeFull() flexLayout { setSizeFull() setFlexDirection(FlexLayout.FlexDirection.COLUMN) alignItems = FlexComponent.Alignment.CENTER justifyContentMode = FlexComponent.JustifyContentMode.CENTER paragraph("404") { style["font-size"] = "200px" style["line-height"] = "80%" setMargin(0, SizeUnit.PIXEL) } translatableParagraph(Messages.URL_NOT_FOUND) add(RouterLink("", Overview::class.java).apply { translatableButton(Messages.GO_HOME) }) } } override fun setErrorParameter(event: BeforeEnterEvent?, parameter: ErrorParameter<NotFoundException>): Int = 404 }
apache-2.0
a75d963c2901b2a1f48ec468b47a62b1
40.45283
117
0.744536
4.066667
false
false
false
false
leafclick/intellij-community
platform/platform-tests/testSrc/com/intellij/internal/statistics/whitelist/validator/ProductivityValidatorTest.kt
1
3154
// 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.internal.statistics.whitelist.validator import com.intellij.featureStatistics.* import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.validator.ValidationResultType import com.intellij.internal.statistic.eventLog.validator.rules.EventContext import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomWhiteListRule import com.intellij.openapi.application.ApplicationManager import com.intellij.testFramework.registerExtension import junit.framework.TestCase import org.junit.Test class ProductivityValidatorTest : ProductivityFeaturesTest() { private fun doValidateEventData(validator: CustomWhiteListRule, name: String, eventData: FeatureUsageData) { val context = EventContext.create("event_id", eventData.build()) val data = context.eventData[name] as String TestCase.assertEquals(ValidationResultType.ACCEPTED, validator.validate(data, context)) } override fun setUp() { super.setUp() ApplicationManager.getApplication().registerExtension( ProductivityFeaturesProvider.EP_NAME, TestProductivityFeatureProvider(), testRootDisposable ) } @Test fun `test validate productivity feature by id`() { val validator = FeatureUsageTrackerImpl.ProductivityUtilValidator() val data = FeatureUsageData().addData("id", "testFeatureId").addData("group", "testFeatureGroup") doValidateEventData(validator, "id", data) } @Test fun `test validate productivity feature by group`() { val validator = FeatureUsageTrackerImpl.ProductivityUtilValidator() val data = FeatureUsageData().addData("id", "testFeatureId").addData("group", "testFeatureGroup") doValidateEventData(validator, "group", data) } @Test fun `test validate productivity feature by id without group`() { val validator = FeatureUsageTrackerImpl.ProductivityUtilValidator() val data = FeatureUsageData().addData("id", "secondTestFeatureId").addData("group", "unknown") doValidateEventData(validator, "id", data) } @Test fun `test validate productivity feature by unknown group`() { val validator = FeatureUsageTrackerImpl.ProductivityUtilValidator() val data = FeatureUsageData().addData("id", "secondTestFeatureId").addData("group", "unknown") doValidateEventData(validator, "group", data) } } class TestProductivityFeatureProvider : ProductivityFeaturesProvider() { override fun getFeatureDescriptors(): Array<FeatureDescriptor> { val withGroup = FeatureDescriptor("testFeatureId", "testFeatureGroup", "TestTip.html", "test", 0, 0, null, 0, this) val noGroup = FeatureDescriptor("secondTestFeatureId", null, "TestTip.html", "test", 0, 0, null, 0, this) return arrayOf(withGroup, noGroup) } override fun getGroupDescriptors(): Array<GroupDescriptor> { return arrayOf(GroupDescriptor("testFeatureGroup", "test")) } override fun getApplicabilityFilters(): Array<ApplicabilityFilter?> { return arrayOfNulls(0) } }
apache-2.0
4e898c86bf048234981fb393d370a292
42.219178
140
0.768865
4.742857
false
true
false
false
tsagi/JekyllForAndroid
app/src/main/java/gr/tsagi/jekyllforandroid/app/utils/GetAccessToken.kt
2
3081
package gr.tsagi.jekyllforandroid.app.utils import android.util.Log import org.apache.http.NameValuePair import org.apache.http.client.ClientProtocolException import org.apache.http.client.entity.UrlEncodedFormEntity import org.apache.http.client.methods.HttpPost import org.apache.http.impl.client.DefaultHttpClient import org.apache.http.message.BasicNameValuePair import org.json.JSONException import org.json.JSONObject import java.io.* import java.util.* /** \* Created with IntelliJ IDEA. \* User: jchanghong \* Date: 7/7/14 \* Time: 15:14 \*/ class GetAccessToken { internal var jsondel = "" internal var params: MutableList<NameValuePair> = ArrayList() lateinit internal var httpClient: DefaultHttpClient lateinit internal var httpPost: HttpPost fun gettoken(address: String, token: String, client_id: String, client_secret: String, redirect_uri: String, grant_type: String): JSONObject { // Making HTTP request try { // DefaultHttpClient httpClient = DefaultHttpClient() httpPost = HttpPost(address) params.add(BasicNameValuePair("code", token)) params.add(BasicNameValuePair("client_id", client_id)) params.add(BasicNameValuePair("client_secret", client_secret)) params.add(BasicNameValuePair("redirect_uri", redirect_uri)) params.add(BasicNameValuePair("grant_type", grant_type)) httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded") httpPost.entity = UrlEncodedFormEntity(params) val httpResponse = httpClient.execute(httpPost) val httpEntity = httpResponse.entity `is` = httpEntity.content } catch (e: UnsupportedEncodingException) { e.printStackTrace() } catch (e: ClientProtocolException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } try { val reader = BufferedReader(InputStreamReader( `is`!!, "iso-8859-1"), 8) val sb = StringBuilder() var line: String? = reader.readLine() while (line != null) { sb.append(line + "n") line = reader.readLine() } `is`!!.close() json = sb.toString() Log.e("JSONStr", json) jsondel = json.replace("&", "\",\"").replace("=", "\"=\"") Log.e("JSONStrDel", jsondel) } catch (e: Exception) { e.message Log.e("Buffer Error", "Error converting result " + e.toString()) } // Parse the String to a JSON Object try { jObj = JSONObject("{\"$jsondel\"}") } catch (e: JSONException) { Log.e("JSON Parser", "Error parsing data " + e.toString()) } // Return JSON String return jObj!! } companion object { internal var `is`: InputStream? = null internal var jObj: JSONObject? = null internal var json = "" } }
gpl-2.0
94b1d8beae0f7d4eec6328fdde2c1e4b
34.425287
146
0.605323
4.510981
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/constants/kt9532.kt
1
781
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: NATIVE object A { const val a: String = "$" const val b = "1234$a" const val c = 10000 val bNonConst = "1234$a" val bNullable: String? = "1234$a" } object B { const val a: String = "$" const val b = "1234$a" const val c = 10000 val bNonConst = "1234$a" val bNullable: String? = "1234$a" } fun box(): String { if (A.a !== B.a) return "Fail 1: A.a !== B.a" if (A.b !== B.b) return "Fail 2: A.b !== B.b" if (A.c !== B.c) return "Fail 3: A.c !== B.c" if (A.bNonConst !== B.bNonConst) return "Fail 4: A.bNonConst !== B.bNonConst" if (A.bNullable !== B.bNullable) return "Fail 5: A.bNullable !== B.bNullable" return "OK" }
apache-2.0
1b3c689b780b4b8d1e1c50ce9c487af7
22.69697
81
0.568502
2.871324
false
false
false
false
byoutline/kickmaterial
app/src/main/java/com/byoutline/kickmaterial/features/projectdetails/ProjectDetailsScrollListener.kt
1
2737
package com.byoutline.kickmaterial.features.projectdetails import android.content.Context import android.util.TypedValue import com.byoutline.kickmaterial.R import com.byoutline.kickmaterial.databinding.ActivityProjectDetailsBinding import com.byoutline.secretsauce.utils.ViewUtils class ProjectDetailsScrollListener(context: Context, private val binding: ActivityProjectDetailsBinding) : ObservableScrollView.Callbacks { private val minTitlesMarginTop: Int private val maxTitlesMarginTop: Int private val maxTitlesMarginLeft: Int private val maxParallaxValue: Int private val titleFontMaxSize: Int private val titleFontMinSize: Int private val maxTitlePaddingRight: Int init { val applicationContext = context.applicationContext val res = context.resources minTitlesMarginTop = ViewUtils.dpToPx(32f, applicationContext) maxTitlesMarginTop = res.getDimensionPixelSize(R.dimen.titles_container_margin_top) - res.getDimensionPixelSize(R.dimen.status_bar_height) maxTitlesMarginLeft = ViewUtils.dpToPx(32f, applicationContext) maxTitlePaddingRight = ViewUtils.dpToPx(72f, applicationContext) maxParallaxValue = res.getDimensionPixelSize(R.dimen.project_details_photo_height) / 3 titleFontMaxSize = res.getDimensionPixelSize(R.dimen.font_21) titleFontMinSize = res.getDimensionPixelSize(R.dimen.font_16) } override fun onScrollChanged(deltaX: Int, deltaY: Int) { val scrollY = (binding.scrollView.scrollY * 0.6f).toInt() val newTitleLeft = Math.min(maxTitlesMarginLeft.toFloat(), scrollY * 0.5f) val newTitleTop = Math.min(maxTitlesMarginTop, scrollY).toFloat() val newTitlePaddingRight = Math.min(maxTitlePaddingRight, scrollY) binding.projectTitleTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, Math.max(titleFontMaxSize - scrollY * 0.05f, titleFontMinSize.toFloat())) binding.projectTitleTv.setPadding(0, 0, newTitlePaddingRight, 0) binding.projectDetailsTitleContainer.translationX = newTitleLeft binding.projectDetailsTitleContainer.translationY = -newTitleTop binding.detailsContainer.translationY = -newTitleTop binding.playVideoBtn.translationY = -newTitleTop /** Content of scroll view is hiding to early during scroll so we move it also by * changing to padding */ binding.scrollView.setPadding(0, (newTitleTop * 0.6f).toInt(), 0, 0) // Move background photo (parallax effect) val parallax = (scrollY * .3f).toInt() if (maxParallaxValue > parallax) { binding.projectPhotoContainer.translationY = (-parallax).toFloat() } } }
apache-2.0
8e86e94c9faa2601f128e1f2854eb7a4
45.40678
146
0.734015
4.776614
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/casts/intersectionTypeMultipleBounds.kt
2
378
interface A { fun foo(): Any? fun bar(): String } interface B { fun foo(): String } fun <T> bar(x: T): String where T : A, T : B { if (x.foo().length != 2 || x.foo() != "OK") return "fail 1" if (x.bar() != "ok") return "fail 2" return "OK" } class C : A, B { override fun foo() = "OK" override fun bar() = "ok" } fun box(): String = bar(C())
apache-2.0
dcc4453341a93c1b6f15b5989e850294
16.227273
63
0.502646
2.759124
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspections/dfa/TypeCast.kt
9
1025
// WITH_STDLIB fun castMayFail(b: Boolean) { val x : Any = if (b) "x" else 5 val y = x as String if (<weak_warning descr="Value of 'b' is always true">b</weak_warning>) {} println(y) } fun castWillFail(b: Boolean) { val x : Any = if (b) X() else Y() val y : Any = if (b) x <warning descr="Cast will always fail">as</warning> Y else X() println(y) } fun castNumber() { val c: Number = 1 c <warning descr="Cast will always fail">as</warning> Float } fun castIntToFloat(c: Int) { c <warning descr="[CAST_NEVER_SUCCEEDS] This cast can never succeed">as</warning> Float } fun safeCast(b: Boolean) { val x : Any = if (b) "x" else 5 val y = x as? String if (y == null) { if (<weak_warning descr="Value of 'b' is always false">b</weak_warning>) {} } } fun nullAsNullableVoid() { // No warning: cast to set type val x = null as Void? println(x) } fun safeAs(v : Any?) { val b = (v as? String) if (v == null) { } println(b) } class X {} class Y {}
apache-2.0
54ce7a6ac20dc5024e8a0eaf0467443c
26
91
0.588293
3.014706
false
false
false
false
smmribeiro/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/Entities.kt
2
15849
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl import com.intellij.util.ReflectionUtil import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.bridgeEntities.ModifiableModuleEntity import com.intellij.workspaceModel.storage.bridgeEntities.ModuleDependencyItem import com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex import com.intellij.workspaceModel.storage.url.VirtualFileUrl import kotlin.properties.ReadWriteProperty import kotlin.reflect.KClass import kotlin.reflect.KProperty import kotlin.reflect.full.memberProperties /** * For creating a new entity, you should perform the following steps: * * - Choose the name of the entity, e.g. MyModuleEntity * - Create [WorkspaceEntity] representation: * - The entity should inherit [WorkspaceEntityBase] * - Properties (not references to other entities) should be listed in a primary constructor as val's * - If the entity has PersistentId, the entity should extend [WorkspaceEntityWithPersistentId] * - If the entity has references to other entities, they should be implement using property delegation objects listed in [com.intellij.workspaceModel.storage.impl.references] package. * E.g. [OneToMany] or [ManyToOne.NotNull] * * Example: * * ```kotlin * class MyModuleEntity(val name: String) : WorkspaceEntityBase(), WorkspaceEntityWithPersistentId { * * val childModule: MyModuleEntity? by OneToOneParent.Nullable(MyModuleEntity::class.java, true) * * fun persistentId() = NameId(name) * } * ``` * * The above entity describes an entity with `name` property, persistent id and the reference to "ChildModule" * * This object will be used by users and it's returned by methods like `resolve`, `entities` and so on. * * ------------------------------------------------------------------------------------------------------------------------------- * * - Create EntityData representation: * - Entity data should have the name ${entityName}Data. E.g. MyModuleEntityData. * - Entity data should inherit [WorkspaceEntityData] * - Properties (not references to other entities) should be listed in the body as lateinit var's or with default value (null, 0, false). * - If the entity has PersistentId, the Entity data should extend [WorkspaceEntityData.WithCalculablePersistentId] * - References to other entities should not be listed in entity data. * * - If the entity contains soft references to other entities (persistent id to other entities), entity data should extend SoftLinkable * interface and implement the required methods. Check out the [FacetEntityData] implementation, but keep in mind the this might * be more complicated like in [ModuleEntityData]. * - Entity data should implement [WorkspaceEntityData.createEntity] method. This method should return an instance of * [WorkspaceEntity]. This instance should be passed to [addMetaData] after creation! * E.g.: * * override fun createEntity(snapshot: WorkspaceEntityStorage): ModuleEntity = ModuleEntity(name, type, dependencies).also { * addMetaData(it, snapshot) * } * * Example: * * ```kotlin * class MyModuleEntityData : WorkspaceEntityData.WithCalculablePersistentId<MyModuleEntity>() { * lateinit var name: String * * override fun persistentId(): NameId = NameId(name) * * override fun createEntity(snapshot: WorkspaceEntityStorage): MyModuleEntity = MyModuleEntity(name).also { * addMetaData(it, snapshot) * } * } * ``` * * This is an internal representation of WorkspaceEntity. It's not passed to users. * * ------------------------------------------------------------------------------------------------------------------------------- * * - Create [ModifiableWorkspaceEntity] representation: * - The name should be: Modifiable${entityName}. E.g. ModifiableMyModuleEntity * - This should be inherited from [ModifiableWorkspaceEntityBase] * - Properties (not references to other entities) should be listed in the body as delegation to [EntityDataDelegation()] * - References to other entities should be listed as in [WorkspaceEntity], but with corresponding modifiable delegates * * Example: * * ```kotlin * class ModifiableMyModuleEntity : ModifiableWorkspaceEntityBase<MyModuleEntity>() { * var name: String by EntityDataDelegation() * * var childModule: MyModuleEntity? by MutableOneToOneParent.NotNull(MyModuleEntity::class.java, MyModuleEntity::class.java, true) * } * ``` */ abstract class WorkspaceEntityBase : ReferableWorkspaceEntity, Any() { override lateinit var entitySource: EntitySource internal set internal var id: EntityId = 0 internal lateinit var snapshot: AbstractEntityStorage override fun hasEqualProperties(e: WorkspaceEntity): Boolean { if (this.javaClass != e.javaClass) return false this::class.memberProperties.forEach { if (it.name == WorkspaceEntityBase::id.name) return@forEach if (it.name == WorkspaceEntityBase::snapshot.name) return@forEach if (it.getter.call(this) != it.getter.call(e)) return false } return true } override fun <R : WorkspaceEntity> referrers(entityClass: Class<R>, propertyName: String): Sequence<R> { val connectionId = snapshot.refs.findConnectionId(this::class.java, entityClass) if (connectionId == null) return emptySequence() return when (connectionId.connectionType) { ConnectionId.ConnectionType.ONE_TO_MANY -> snapshot.extractOneToManyChildren(connectionId, id) ConnectionId.ConnectionType.ONE_TO_ONE -> snapshot.extractOneToOneChild<R>(connectionId, id)?.let { sequenceOf(it) } ?: emptySequence() ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY -> snapshot.extractOneToAbstractManyChildren(connectionId, id.asParent()) ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE -> snapshot.extractAbstractOneToOneChild<R>(connectionId, id.asParent())?.let { sequenceOf(it) } ?: emptySequence() } } override fun <E : WorkspaceEntity> createReference(): EntityReference<E> { return EntityReferenceImpl(this.id) } override fun toString(): String = id.asString() override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as WorkspaceEntityBase if (id != other.id) return false if (this.snapshot.entityDataById(id) !== other.snapshot.entityDataById(other.id)) return false return true } override fun hashCode(): Int = id.hashCode() } abstract class ModifiableWorkspaceEntityBase<T : WorkspaceEntityBase> : WorkspaceEntityBase(), ModifiableWorkspaceEntity<T> { internal lateinit var original: WorkspaceEntityData<T> lateinit var diff: WorkspaceEntityStorageBuilder internal val modifiable = ThreadLocal.withInitial { false } internal inline fun allowModifications(action: () -> Unit) { modifiable.set(true) try { action() } finally { modifiable.remove() } } open fun getEntityClass(): KClass<T> = ClassConversion.modifiableEntityToEntity(this::class) open fun applyToBuilder(builder: WorkspaceEntityStorageBuilder, entitySource: EntitySource) { throw NotImplementedError() } open fun getEntityData(): WorkspaceEntityData<T> { throw NotImplementedError() } // For generated entities @Suppress("unused") fun addToBuilder() { val builder = diff as WorkspaceEntityStorageBuilderImpl builder.putEntity(getEntityData()) } // For generated entities @Suppress("unused") fun applyRef(connectionId: ConnectionId, child: WorkspaceEntityData<*>?, children: List<WorkspaceEntityData<*>>?) { val builder = diff as WorkspaceEntityStorageBuilderImpl when (connectionId.connectionType) { ConnectionId.ConnectionType.ONE_TO_ONE -> builder.updateOneToOneChildOfParent(connectionId, id, child!!.createEntityId().asChild()) ConnectionId.ConnectionType.ONE_TO_MANY -> builder.updateOneToManyChildrenOfParent(connectionId, id, children!!.map { it.createEntityId().asChild() }.asSequence()) ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY -> builder.updateOneToAbstractManyChildrenOfParent(connectionId, id.asParent(), children!!.map { it.createEntityId().asChild() }.asSequence()) ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE -> builder.updateOneToAbstractOneChildOfParent(connectionId, id.asParent(), child!!.createEntityId().asChild()) } } // For generated entities @Suppress("unused") fun index(entity: WorkspaceEntity, propertyName: String, virtualFileUrl: VirtualFileUrl?) { val builder = diff as WorkspaceEntityStorageBuilderImpl builder.getMutableVirtualFileUrlIndex().index(entity, propertyName, virtualFileUrl) } // For generated entities @Suppress("unused") fun index(entity: WorkspaceEntity, propertyName: String, virtualFileUrls: Set<VirtualFileUrl>) { val builder = diff as WorkspaceEntityStorageBuilderImpl (builder.getMutableVirtualFileUrlIndex() as VirtualFileIndex.MutableVirtualFileIndex).index((entity as WorkspaceEntityBase).id, propertyName, virtualFileUrls) } // For generated entities @Suppress("unused") fun indexJarDirectories(entity: WorkspaceEntity, virtualFileUrls: Set<VirtualFileUrl>) { val builder = diff as WorkspaceEntityStorageBuilderImpl (builder.getMutableVirtualFileUrlIndex() as VirtualFileIndex.MutableVirtualFileIndex).indexJarDirectories( (entity as WorkspaceEntityBase).id, virtualFileUrls) } } interface SoftLinkable { fun getLinks(): Set<PersistentEntityId<*>> fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean } abstract class WorkspaceEntityData<E : WorkspaceEntity> : Cloneable { lateinit var entitySource: EntitySource var id: Int = -1 internal fun createEntityId(): EntityId = createEntityId(id, ClassConversion.entityDataToEntity(javaClass).toClassId()) abstract fun createEntity(snapshot: WorkspaceEntityStorage): E fun addMetaData(res: E, snapshot: WorkspaceEntityStorage) { (res as WorkspaceEntityBase).entitySource = entitySource (res as WorkspaceEntityBase).id = createEntityId() (res as WorkspaceEntityBase).snapshot = snapshot as AbstractEntityStorage } fun addMetaData(res: E, snapshot: WorkspaceEntityStorage, classId: Int) { (res as WorkspaceEntityBase).entitySource = entitySource (res as WorkspaceEntityBase).id = createEntityId(id, classId) (res as WorkspaceEntityBase).snapshot = snapshot as AbstractEntityStorage } internal fun wrapAsModifiable(diff: WorkspaceEntityStorageBuilderImpl): ModifiableWorkspaceEntity<E> { val returnClass = ClassConversion.entityDataToModifiableEntity(this::class) val res = returnClass.java.getDeclaredConstructor().newInstance() res as ModifiableWorkspaceEntityBase res.original = this res.diff = diff res.id = createEntityId() res.entitySource = this.entitySource return res } @Suppress("UNCHECKED_CAST") public override fun clone(): WorkspaceEntityData<E> = super.clone() as WorkspaceEntityData<E> override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false return ReflectionUtil.collectFields(this.javaClass).filterNot { it.name == WorkspaceEntityData<*>::id.name } .onEach { it.isAccessible = true } .all { it.get(this) == it.get(other) } } open fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false return ReflectionUtil.collectFields(this.javaClass) .filterNot { it.name == WorkspaceEntityData<*>::id.name } .filterNot { it.name == WorkspaceEntityData<*>::entitySource.name } .onEach { it.isAccessible = true } .all { it.get(this) == it.get(other) } } override fun hashCode(): Int { return ReflectionUtil.collectFields(this.javaClass).filterNot { it.name == WorkspaceEntityData<*>::id.name } .onEach { it.isAccessible = true } .mapNotNull { it.get(this)?.hashCode() } .fold(31) { acc, i -> acc * 17 + i } } override fun toString(): String { val fields = ReflectionUtil.collectFields(this.javaClass).toList().onEach { it.isAccessible = true } .joinToString(separator = ", ") { f -> "${f.name}=${f.get(this)}" } return "${this::class.simpleName}($fields, id=${this.id})" } /** * Temporally solution. * Get persistent Id without creating of TypedEntity. Should be in sync with TypedEntityWithPersistentId. * But it doesn't everywhere. E.g. FacetEntity where we should resolve module before creating persistent id. */ abstract class WithCalculablePersistentId<E : WorkspaceEntity> : WorkspaceEntityData<E>() { abstract fun persistentId(): PersistentEntityId<*> } } fun WorkspaceEntityData<*>.persistentId(): PersistentEntityId<*>? = when (this) { is WorkspaceEntityData.WithCalculablePersistentId -> this.persistentId() else -> null } class EntityDataDelegation<A : ModifiableWorkspaceEntityBase<*>, B> : ReadWriteProperty<A, B> { override fun getValue(thisRef: A, property: KProperty<*>): B { val field = thisRef.original.javaClass.getDeclaredField(property.name) field.isAccessible = true @Suppress("UNCHECKED_CAST") return field.get(thisRef.original) as B } override fun setValue(thisRef: A, property: KProperty<*>, value: B) { if (!thisRef.modifiable.get()) { throw IllegalStateException("Modifications are allowed inside 'addEntity' and 'modifyEntity' methods only!") } val field = thisRef.original.javaClass.getDeclaredField(property.name) field.isAccessible = true field.set(thisRef.original, value) } } class ModuleDependencyEntityDataDelegation : ReadWriteProperty<ModifiableModuleEntity, List<ModuleDependencyItem>> { override fun getValue(thisRef: ModifiableModuleEntity, property: KProperty<*>): List<ModuleDependencyItem> { val field = thisRef.original.javaClass.getDeclaredField(property.name) field.isAccessible = true @Suppress("UNCHECKED_CAST") return field.get(thisRef.original) as List<ModuleDependencyItem> } override fun setValue(thisRef: ModifiableModuleEntity, property: KProperty<*>, value: List<ModuleDependencyItem>) { if (!thisRef.modifiable.get()) { throw IllegalStateException("Modifications are allowed inside 'addEntity' and 'modifyEntity' methods only!") } val field = thisRef.original.javaClass.getDeclaredField(property.name) thisRef.dependencyChanged = true field.isAccessible = true field.set(thisRef.original, value) } } /** * This interface is a solution for checking consistency of some entities that can't be checked automatically * * For example, we can mark LibraryPropertiesEntityData with this interface and check that entity source of properties is the same as * entity source of the library itself. * * Interface should be applied to *entity data*. * * [assertConsistency] method is called during [WorkspaceEntityStorageBuilderImpl.assertConsistency]. */ interface WithAssertableConsistency { fun assertConsistency(storage: WorkspaceEntityStorage) }
apache-2.0
45863eabd409cf61bf92517fd9f1dbfb
42.905817
197
0.722064
5.012334
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/ScrollPane.kt
1
8099
package de.fabmax.kool.modules.ui2 import de.fabmax.kool.math.clamp import de.fabmax.kool.util.Time import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.round open class ScrollState { val xScrollDp = mutableStateOf(0f) val yScrollDp = mutableStateOf(0f) val xScrollDpDesired = mutableStateOf(0f) val yScrollDpDesired = mutableStateOf(0f) val contentWidthDp = mutableStateOf(0f) val contentHeightDp = mutableStateOf(0f) val viewWidthDp = mutableStateOf(0f) val viewHeightDp = mutableStateOf(0f) val relativeBarLenX: Float get() = (round(viewWidthDp.value) / round(contentWidthDp.value)).clamp() val relativeBarLenY: Float get() = (round(viewHeightDp.value) / round(contentHeightDp.value)).clamp() val relativeBarPosX: Float get() { val div = xScrollDp.value + contentWidthDp.value - (xScrollDp.value + viewWidthDp.value) return if (div == 0f) 1f else (xScrollDp.value / div) } val relativeBarPosY: Float get() { val div = yScrollDp.value + contentHeightDp.value - (yScrollDp.value + viewHeightDp.value) return if (div == 0f) 0f else (yScrollDp.value / (div)) } val remainingSpaceTop: Float get() = yScrollDp.value val remainingSpaceBottom: Float get() = contentHeightDp.value - (yScrollDp.value + viewHeightDp.value) val remainingSpaceStart: Float get() = xScrollDp.value val remainingSpaceEnd: Float get() = contentWidthDp.value - (xScrollDp.value + viewWidthDp.value) fun scrollDpX(amount: Float, smooth: Boolean = true) { if (smooth) { val x = min(max(0f, xScrollDpDesired.value + amount), contentWidthDp.value - viewWidthDp.value) xScrollDpDesired.set(x) } else { val x = min(max(0f, xScrollDp.value + amount), contentWidthDp.value - viewWidthDp.value) xScrollDp.set(x) xScrollDpDesired.set(x) } } fun scrollDpY(amount: Float, smooth: Boolean = true) { if (smooth) { val y = min(max(0f, yScrollDpDesired.value + amount), contentHeightDp.value - viewHeightDp.value) yScrollDpDesired.set(y) } else { val y = min(max(0f, yScrollDp.value + amount), contentHeightDp.value - viewHeightDp.value) yScrollDp.set(y) yScrollDpDesired.set(y) } } fun scrollRelativeX(relativeX: Float, smooth: Boolean = true) { val width = max(contentWidthDp.value, viewWidthDp.value) xScrollDpDesired.set((width - viewWidthDp.value) * relativeX) if (!smooth) { xScrollDp.set(xScrollDpDesired.value) } } fun scrollRelativeY(relativeY: Float, smooth: Boolean = true) { val height = max(contentHeightDp.value, viewHeightDp.value) yScrollDpDesired.set((height - viewHeightDp.value) * relativeY) if (!smooth) { yScrollDp.set(yScrollDpDesired.value) } } fun computeSmoothScrollPosDpX(): Float { return xScrollDp.value + computeSmoothScrollAmountDpX() } fun computeSmoothScrollPosDpY(): Float { return yScrollDp.value + computeSmoothScrollAmountDpY() } fun computeSmoothScrollAmountDpX(): Float { val error = xScrollDpDesired.value - xScrollDp.value return if (abs(error) < 1f) { error } else { var step = error * SMOOTHING_FAC * Time.deltaT if (abs(step) > abs(error)) { step = error } step } } fun computeSmoothScrollAmountDpY(): Float { val error = yScrollDpDesired.value - yScrollDp.value return if (abs(error) < 1f) { error } else { var step = error * SMOOTHING_FAC * Time.deltaT if (abs(step) > abs(error)) { step = error } step } } fun setSmoothScrollAmountDpX(step: Float) { val error = step / (SMOOTHING_FAC * Time.deltaT) xScrollDpDesired.set(xScrollDp.value + error) } fun setSmoothScrollAmountDpY(step: Float) { val error = step / (SMOOTHING_FAC * Time.deltaT) yScrollDpDesired.set(yScrollDp.value + error) } companion object { private const val SMOOTHING_FAC = 15f } } interface ScrollPaneScope : UiScope { override val modifier: ScrollPaneModifier } open class ScrollPaneModifier(surface: UiSurface) : UiModifier(surface) { var onScrollPosChanged: ((Float, Float) -> Unit)? by property(null) var allowOverscrollX by property(false) var allowOverscrollY by property(false) } fun <T: ScrollPaneModifier> T.allowOverScroll(x: Boolean, y: Boolean): T { allowOverscrollX = x allowOverscrollY = y return this } fun <T: ScrollPaneModifier> T.onScrollPosChanged(block: (Float, Float) -> Unit): T { onScrollPosChanged = block return this } inline fun UiScope.ScrollPane(state: ScrollState, block: ScrollPaneScope.() -> Unit): ScrollPaneScope { val scrollPane = uiNode.createChild(ScrollPaneNode::class, ScrollPaneNode.factory) scrollPane.state = state scrollPane.block() return scrollPane } open class ScrollPaneNode(parent: UiNode?, surface: UiSurface) : UiNode(parent, surface), ScrollPaneScope { override val modifier = ScrollPaneModifier(surface) lateinit var state: ScrollState override fun setBounds(minX: Float, minY: Float, maxX: Float, maxY: Float) { updateScrollPos() val scrollX = round(state.xScrollDp.use() * UiScale.measuredScale) val scrollY = round(state.yScrollDp.use() * UiScale.measuredScale) super.setBounds(minX - scrollX, minY - scrollY, maxX - scrollX, maxY - scrollY) } protected open fun updateScrollPos() { var currentScrollX = state.xScrollDp.use() var currentScrollY = state.yScrollDp.use() var desiredScrollX = state.xScrollDpDesired.use() var desiredScrollY = state.yScrollDpDesired.use() if (parent != null) { state.viewWidthDp.set(parent.widthPx / UiScale.measuredScale) state.viewHeightDp.set(parent.heightPx / UiScale.measuredScale) state.contentWidthDp.set(contentWidthPx / UiScale.measuredScale) state.contentHeightDp.set(contentHeightPx / UiScale.measuredScale) // clamp scroll positions to content size if (!modifier.allowOverscrollX) { if (currentScrollX + state.viewWidthDp.value > state.contentWidthDp.value) { currentScrollX = state.contentWidthDp.value - state.viewWidthDp.value } if (desiredScrollX + state.viewWidthDp.value > state.contentWidthDp.value) { desiredScrollX = state.contentWidthDp.value - state.viewWidthDp.value } state.xScrollDp.set(max(0f, currentScrollX)) state.xScrollDpDesired.set(max(0f, desiredScrollX)) } if (!modifier.allowOverscrollY) { if (currentScrollY + state.viewHeightDp.value > state.contentHeightDp.value) { currentScrollY = state.contentHeightDp.value - state.viewHeightDp.value } if (desiredScrollY + state.viewHeightDp.value > state.contentHeightDp.value) { desiredScrollY = state.contentHeightDp.value - state.viewHeightDp.value } state.yScrollDp.set(max(0f, currentScrollY)) state.yScrollDpDesired.set(max(0f, desiredScrollY)) } } state.xScrollDp.set(state.computeSmoothScrollPosDpX()) state.yScrollDp.set(state.computeSmoothScrollPosDpY()) if (state.xScrollDp.isStateChanged || state.yScrollDp.isStateChanged) { modifier.onScrollPosChanged?.invoke(state.xScrollDp.value, state.yScrollDp.value) } } companion object { val factory: (UiNode, UiSurface) -> ScrollPaneNode = { parent, surface -> ScrollPaneNode(parent, surface) } } }
apache-2.0
9193f365b560cb163a7f41ae02e57343
36.5
115
0.644524
4.496946
false
false
false
false
fabmax/kool
kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/physics/collision/CollisionDemo.kt
1
15491
package de.fabmax.kool.demo.physics.collision import de.fabmax.kool.AssetManager import de.fabmax.kool.KoolContext import de.fabmax.kool.demo.* import de.fabmax.kool.demo.menu.DemoMenu import de.fabmax.kool.math.* import de.fabmax.kool.math.spatial.BoundingBox import de.fabmax.kool.modules.ui2.* import de.fabmax.kool.physics.* import de.fabmax.kool.physics.geometry.* import de.fabmax.kool.pipeline.Attribute import de.fabmax.kool.pipeline.Texture2d import de.fabmax.kool.pipeline.ao.AoPipeline import de.fabmax.kool.pipeline.ibl.EnvironmentHelper import de.fabmax.kool.pipeline.ibl.EnvironmentMaps import de.fabmax.kool.pipeline.shadermodel.PbrMaterialNode import de.fabmax.kool.pipeline.shadermodel.StageInterfaceNode import de.fabmax.kool.pipeline.shadermodel.fragmentStage import de.fabmax.kool.pipeline.shadermodel.vertexStage import de.fabmax.kool.pipeline.shading.PbrMaterialConfig import de.fabmax.kool.pipeline.shading.PbrShader import de.fabmax.kool.pipeline.shading.pbrShader import de.fabmax.kool.scene.* import de.fabmax.kool.toString import de.fabmax.kool.util.* import kotlin.math.max import kotlin.math.roundToInt class CollisionDemo : DemoScene("Physics - Collision") { private lateinit var aoPipeline: AoPipeline private lateinit var ibl: EnvironmentMaps private lateinit var groundAlbedo: Texture2d private lateinit var groundNormal: Texture2d private val shadows = mutableListOf<ShadowMap>() private val shapeTypes = mutableListOf(*ShapeType.values()) private val selectedShapeType = mutableStateOf(6) private val numSpawnBodies = mutableStateOf(450) private val friction = mutableStateOf(0.5f) private val restitution = mutableStateOf(0.2f) private val drawBodyState = mutableStateOf(false) private val physicsTimeTxt = mutableStateOf("0.00 ms") private val activeActorsTxt = mutableStateOf("0") private val timeFactorTxt = mutableStateOf("1.00 x") private lateinit var physicsWorld: PhysicsWorld private val physicsStepper = SimplePhysicsStepper() private val bodies = mutableMapOf<ShapeType, MutableList<ColoredBody>>() private val shapeGenCtx = ShapeType.ShapeGeneratorContext() override suspend fun AssetManager.loadResources(ctx: KoolContext) { ibl = EnvironmentHelper.hdriEnvironment(mainScene, "${DemoLoader.hdriPath}/colorful_studio_1k.rgbe.png", this) groundAlbedo = loadAndPrepareTexture("${DemoLoader.materialPath}/tile_flat/tiles_flat_fine.png") groundNormal = loadAndPrepareTexture("${DemoLoader.materialPath}/tile_flat/tiles_flat_fine_normal.png") Physics.awaitLoaded() [email protected] = PhysicsWorld().apply { simStepper = physicsStepper } } override fun Scene.setupMainScene(ctx: KoolContext) { defaultCamTransform().apply { zoomMethod = OrbitInputTransform.ZoomMethod.ZOOM_TRANSLATE panMethod = yPlanePan() translationBounds = BoundingBox(Vec3f(-50f), Vec3f(50f)) minHorizontalRot = -90.0 maxHorizontalRot = -20.0 setZoom(75.0, min = 10.0) } (camera as PerspectiveCamera).apply { clipNear = 0.5f clipFar = 500f } val shadowMap = CascadedShadowMap(this, 0, maxRange = 300f) shadows.add(shadowMap) aoPipeline = AoPipeline.createForward(this) lighting.singleLight { setDirectional(Vec3f(0.8f, -1.2f, 1f)) } makeGround(ibl, physicsWorld) shapeGenCtx.material = Material(friction.value, friction.value, restitution.value) resetPhysics() shapeTypes.forEach { if (it != ShapeType.MIXED) { it.mesh.shader = instancedBodyShader(ibl) +it.mesh } } val matBuf = Mat4f() val removeBodies = mutableListOf<ColoredBody>() onUpdate += { for (i in shapeTypes.indices) { shapeTypes[i].instances.clear() } val activeColor = MutableColor(MdColor.RED.toLinear()) val inactiveColor = MutableColor(MdColor.LIGHT_GREEN.toLinear()) bodies.forEach { (type, typeBodies) -> type.instances.addInstances(typeBodies.size) { buf -> for (i in typeBodies.indices) { val body = typeBodies[i] matBuf.set(body.rigidActor.transform).scale(body.scale) buf.put(matBuf.matrix) if (drawBodyState.value) { if (body.rigidActor.isActive) { buf.put(activeColor.array) } else { buf.put(inactiveColor.array) } } else { buf.put(body.color.array) } if (body.rigidActor.position.length() > 500f) { removeBodies += body } } } if (removeBodies.isNotEmpty()) { removeBodies.forEach { body -> logI { "Removing out-of-range body" } typeBodies.remove(body) physicsWorld.removeActor(body.rigidActor) body.rigidActor.release() } removeBodies.clear() } } physicsTimeTxt.set("${physicsStepper.perfCpuTime.toString(2)} ms") activeActorsTxt.set("${physicsWorld.activeActors}") timeFactorTxt.set("${physicsStepper.perfTimeFactor.toString(2)} x") } +Skybox.cube(ibl.reflectionMap, 1f) physicsWorld.registerHandlers(this) } override fun dispose(ctx: KoolContext) { super.dispose(ctx) physicsWorld.clear() physicsWorld.release() shapeGenCtx.material.release() groundAlbedo.dispose() groundNormal.dispose() } private fun resetPhysics() { bodies.values.forEach { typedBodies -> typedBodies.forEach { physicsWorld.removeActor(it.rigidActor) it.rigidActor.release() } } bodies.clear() val types = if (shapeTypes[selectedShapeType.value] == ShapeType.MIXED) { ShapeType.values().toList().filter { it != ShapeType.MIXED } } else { listOf(shapeTypes[selectedShapeType.value]) } shapeGenCtx.material.release() shapeGenCtx.material = Material(friction.value, friction.value, restitution.value) val stacks = max(1, numSpawnBodies.value / 50) val centers = makeCenters(stacks) val rand = Random(39851564) for (i in 0 until numSpawnBodies.value) { val layer = i / stacks val stack = i % stacks val color = MdColor.PALETTE[layer % MdColor.PALETTE.size].toLinear() val x = centers[stack].x * 10f + rand.randomF(-1f, 1f) val z = centers[stack].y * 10f + rand.randomF(-1f, 1f) val y = layer * 5f + 10f val type = types[rand.randomI(types.indices)] val shapes = type.generateShapes(shapeGenCtx) val body = RigidDynamic(shapes.mass) shapes.primitives.forEach { s -> body.attachShape(s) // after shape is attached, geometry can be released s.geometry.release() } body.updateInertiaFromShapesAndMass() body.position = Vec3f(x, y, z) body.setRotation(Mat3f().rotate(rand.randomF(-90f, 90f), rand.randomF(-90f, 90f), rand.randomF(-90f, 90f))) physicsWorld.addActor(body) val coloredBody = ColoredBody(body, color, shapes) bodies.getOrPut(type) { mutableListOf() } += coloredBody } } private fun makeCenters(stacks: Int): List<Vec2f> { val dir = MutableVec2f(1f, 0f) val centers = mutableListOf(Vec2f(0f, 0f)) var steps = 1 var stepsSteps = 1 while (centers.size < stacks) { for (i in 1..steps) { centers += MutableVec2f(centers.last()).add(dir) if (centers.size == stacks) { break } } dir.rotate(90f) if (stepsSteps++ == 2) { stepsSteps = 1 steps++ } } return centers } private fun Scene.makeGround(ibl: EnvironmentMaps, physicsWorld: PhysicsWorld) { val frame = mutableListOf<RigidStatic>() val frameSimFilter = FilterData { setCollisionGroup(1) clearCollidesWith(1) } val groundMaterial = Material(0.5f, 0.5f, 0.2f) val groundShape = BoxGeometry(Vec3f(100f, 1f, 100f)) val ground = RigidStatic().apply { attachShape(Shape(groundShape, groundMaterial)) position = Vec3f(0f, -0.5f, 0f) simulationFilterData = frameSimFilter } physicsWorld.addActor(ground) val frameLtShape = BoxGeometry(Vec3f(3f, 6f, 100f)) val frameLt = RigidStatic().apply { attachShape(Shape(frameLtShape, groundMaterial)) position = Vec3f(-51.5f, 2f, 0f) simulationFilterData = frameSimFilter } physicsWorld.addActor(frameLt) frame += frameLt val frameRtShape = BoxGeometry(Vec3f(3f, 6f, 100f)) val frameRt = RigidStatic().apply { attachShape(Shape(frameRtShape, groundMaterial)) position = Vec3f(51.5f, 2f, 0f) simulationFilterData = frameSimFilter } physicsWorld.addActor(frameRt) frame += frameRt val frameFtShape = BoxGeometry(Vec3f(106f, 6f, 3f)) val frameFt = RigidStatic().apply { attachShape(Shape(frameFtShape, groundMaterial)) position = Vec3f(0f, 2f, 51.5f) simulationFilterData = frameSimFilter } physicsWorld.addActor(frameFt) frame += frameFt val frameBkShape = BoxGeometry(Vec3f(106f, 6f, 3f)) val frameBk = RigidStatic().apply { attachShape(Shape(frameBkShape, groundMaterial)) position = Vec3f(0f, 2f, -51.5f) simulationFilterData = frameSimFilter } physicsWorld.addActor(frameBk) frame += frameBk // render textured ground box +textureMesh(isNormalMapped = true) { generate { vertexModFun = { texCoord.set(x / 10, z / 10) } cube { size.set(groundShape.size) origin.set(size).scale(-0.5f).add(ground.position) } } shader = pbrShader { roughness = 0.75f shadowMaps += shadows useImageBasedLighting(ibl) useScreenSpaceAmbientOcclusion(aoPipeline.aoMap) useAlbedoMap(groundAlbedo) useNormalMap(groundNormal) } } // render frame +colorMesh { generate { frame.forEach { val shape = it.shapes[0].geometry as BoxGeometry cube { size.set(shape.size) origin.set(size).scale(-0.5f).add(it.position) } } } shader = pbrShader { roughness = 0.75f shadowMaps += shadows useImageBasedLighting(ibl) useScreenSpaceAmbientOcclusion(aoPipeline.aoMap) useStaticAlbedo(MdColor.BLUE_GREY toneLin 700) } } } private fun instancedBodyShader(ibl: EnvironmentMaps): PbrShader { val cfg = PbrMaterialConfig().apply { roughness = 1f isInstanced = true shadowMaps += shadows useImageBasedLighting(ibl) useScreenSpaceAmbientOcclusion(aoPipeline.aoMap) useStaticAlbedo(Color.WHITE) } val model = PbrShader.defaultPbrModel(cfg).apply { val ifInstColor: StageInterfaceNode vertexStage { ifInstColor = stageInterfaceNode("ifInstColor", instanceAttributeNode(Attribute.COLORS).output) } fragmentStage { findNodeByType<PbrMaterialNode>()!!.apply { inAlbedo = ifInstColor.output } } } return PbrShader(cfg, model) } private class ColoredBody(val rigidActor: RigidActor, val color: MutableColor, bodyShapes: ShapeType.CollisionShapes) { val scale = MutableVec3f() init { when (val shape = rigidActor.shapes[0].geometry) { is BoxGeometry -> { if (rigidActor.shapes.size == 1) { // Box scale.set(shape.size) } else { // Multi shape val s = shape.size.z / 2f scale.set(s, s, s) } } is CapsuleGeometry -> scale.set(shape.radius, shape.radius, shape.radius) is ConvexMeshGeometry -> { val s = bodyShapes.scale scale.set(s, s, s) } is CylinderGeometry -> scale.set(shape.length, shape.radius, shape.radius) is SphereGeometry -> scale.set(shape.radius, shape.radius, shape.radius) } } } override fun createMenu(menu: DemoMenu, ctx: KoolContext) = menuSurface { MenuRow { Text("Body shape") { labelStyle() } ComboBox { modifier .width(Grow.Std) .margin(start = sizes.largeGap) .items(shapeTypes) .selectedIndex(selectedShapeType.use()) .onItemSelected { selectedShapeType.set(it) } } } MenuSlider2("Number of Bodies", numSpawnBodies.use().toFloat(), 50f, 2000f, { "${it.roundToInt()}" }) { numSpawnBodies.set(it.roundToInt()) } MenuSlider2("Friction", friction.use(), 0f, 2f) { friction.set(it) } MenuSlider2("Restitution", restitution.use(), 0f, 1f) { restitution.set(it) } Button("Apply settings") { modifier .alignX(AlignmentX.Center) .width(Grow.Std) .margin(horizontal = 16.dp, vertical = 24.dp) .onClick { resetPhysics() } } Text("Statistics") { sectionTitleStyle() } MenuRow { LabeledSwitch("Show body state", drawBodyState) } MenuRow { Text("Active actors") { labelStyle(Grow.Std) } Text(activeActorsTxt.use()) { labelStyle() } } MenuRow { Text("Physics step CPU time") { labelStyle(Grow.Std) } Text(physicsTimeTxt.use()) { labelStyle() } } MenuRow { Text("Time factor") { labelStyle(Grow.Std) } Text(timeFactorTxt.use()) { labelStyle() } } } }
apache-2.0
a6ee3357eb09234839fc416e0bd9313a
35.885714
123
0.566393
4.558858
false
false
false
false
dpisarenko/econsim-tr01
src/main/java/cc/altruix/econsimtr01/Simulation1.kt
1
2221
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 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. * * econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01 import org.joda.time.DateTime /** * @author Dmitri Pisarenko ([email protected]) * @version $Id$ * @since 1.0 */ class Simulation1(val logTarget:StringBuilder, val flows:MutableList<ResourceFlow>, simParametersProvider: SimParametersProvider) : DefaultSimulation(simParametersProvider) { val foodStorage = DefaultResourceStorage("FoodStorage") val farmer = Farmer( foodStorage, flows, simParametersProvider.maxDaysWithoutFood, simParametersProvider.dailyPotatoConsumption ) override fun createSensors(): List<ISensor> = listOf( Accountant( foodStorage, farmer, logTarget) ) override fun createAgents(): List<IAgent> { foodStorage.put( Resource.POTATO.name, (simParametersProvider as SimParametersProvider).initialAmountOfPotatoes ) val agents = listOf( farmer, Field(), Nature() ) return agents } override fun continueCondition(tick: DateTime): Boolean = farmer.alive }
gpl-3.0
847524ac731b06410e8c478043b0e988
29.424658
108
0.6362
4.627083
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/editor/TypedHandlerTest.kt
1
35943
// 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.editor import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.testFramework.EditorTestUtil import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.formatter.KotlinObsoleteCodeStyle import org.jetbrains.kotlin.idea.formatter.kotlinCommonSettings import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.configureCodeStyleAndRun import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class TypedHandlerTest : KotlinLightCodeInsightFixtureTestCase() { private val dollar = '$' fun testTypeStringTemplateStart() = doTypeTest( '{', """val x = "$<caret>" """, """val x = "$dollar{}" """ ) fun testAutoIndentRightOpenBrace() = doTypeTest( '{', "fun test() {\n" + "<caret>\n" + "}", "fun test() {\n" + " {<caret>}\n" + "}" ) fun testAutoIndentLeftOpenBrace() = doTypeTest( '{', "fun test() {\n" + " <caret>\n" + "}", "fun test() {\n" + " {<caret>}\n" + "}" ) fun testTypeStringTemplateStartWithCloseBraceAfter() = doTypeTest( '{', """fun foo() { "$<caret>" }""", """fun foo() { "$dollar{}" }""" ) fun testTypeStringTemplateStartBeforeStringWithExistingDollar() = doTypeTest( '{', """fun foo() { "$<caret>something" }""", """fun foo() { "$dollar{something" }""" ) fun testTypeStringTemplateStartBeforeStringWithNoDollar() = doTypeTest( "$dollar{", """fun foo() { "<caret>something" }""", """fun foo() { "$dollar{<caret>}something" }""" ) fun testTypeStringTemplateWithUnmatchedBrace() = doTypeTest( "$dollar{", """val a = "<caret>bar}foo"""", """val a = "$dollar{<caret>bar}foo"""" ) fun testTypeStringTemplateWithUnmatchedBraceComplex() = doTypeTest( "$dollar{", """val a = "<caret>bar + more}foo"""", """val a = "$dollar{<caret>}bar + more}foo"""" ) fun testTypeStringTemplateStartInStringWithBraceLiterals() = doTypeTest( "$dollar{", """val test = "{ code <caret>other }"""", """val test = "{ code $dollar{<caret>}other }"""" ) fun testTypeStringTemplateStartInEmptyString() = doTypeTest( '{', """fun foo() { "$<caret>" }""", """fun foo() { "$dollar{<caret>}" }""" ) fun testKT3575() = doTypeTest( '{', """val x = "$<caret>]" """, """val x = "$dollar{}]" """ ) fun testAutoCloseRawStringInEnd() = doTypeTest( '"', """val x = ""<caret>""", """val x = ""${'"'}<caret>""${'"'}""" ) fun testNoAutoCloseRawStringInEnd() = doTypeTest( '"', """val x = ""${'"'}<caret>""", """val x = ""${'"'}"""" ) fun testAutoCloseRawStringInMiddle() = doTypeTest( '"', """ val x = ""<caret> val y = 12 """.trimIndent(), """ val x = ""${'"'}<caret>""${'"'} val y = 12 """.trimIndent() ) fun testNoAutoCloseBetweenMultiQuotes() = doTypeTest( '"', """val x = ""${'"'}<caret>${'"'}""/**/""", """val x = ""${'"'}${'"'}<caret>""/**/""" ) fun testNoAutoCloseBetweenMultiQuotes1() = doTypeTest( '"', """val x = ""${'"'}"<caret>"${'"'}/**/""", """val x = ""${'"'}""<caret>${'"'}/**/""" ) fun testNoAutoCloseAfterEscape() = doTypeTest( '"', """val x = "\""<caret>""", """val x = "\""${'"'}<caret>"""" ) fun testAutoCloseBraceInFunctionDeclaration() = doTypeTest( '{', "fun foo() <caret>", "fun foo() {<caret>}" ) fun testAutoCloseBraceInLocalFunctionDeclaration() = doTypeTest( '{', "fun foo() {\n" + " fun bar() <caret>\n" + "}", "fun foo() {\n" + " fun bar() {<caret>}\n" + "}" ) fun testAutoCloseBraceInAssignment() = doTypeTest( '{', "fun foo() {\n" + " val a = <caret>\n" + "}", "fun foo() {\n" + " val a = {<caret>}\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedIfSurroundOnSameLine() = doTypeTest( '{', "fun foo() {\n" + " if() <caret>foo()\n" + "}", "fun foo() {\n" + " if() {foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedElseSurroundOnSameLine() = doTypeTest( '{', "fun foo() {\n" + " if(true) {} else <caret>foo()\n" + "}", "fun foo() {\n" + " if(true) {} else {foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedTryOnSameLine() = doTypeTest( '{', "fun foo() {\n" + " try <caret>foo()\n" + "}", "fun foo() {\n" + " try {foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedCatchOnSameLine() = doTypeTest( '{', "fun foo() {\n" + " try {} catch (e: Exception) <caret>foo()\n" + "}", "fun foo() {\n" + " try {} catch (e: Exception) {foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedFinallyOnSameLine() = doTypeTest( '{', "fun foo() {\n" + " try {} catch (e: Exception) finally <caret>foo()\n" + "}", "fun foo() {\n" + " try {} catch (e: Exception) finally {foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedWhileSurroundOnSameLine() = doTypeTest( '{', "fun foo() {\n" + " while() <caret>foo()\n" + "}", "fun foo() {\n" + " while() {foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedWhileSurroundOnNewLine() = doTypeTest( '{', "fun foo() {\n" + " while()\n" + "<caret>\n" + " foo()\n" + "}", "fun foo() {\n" + " while()\n" + " {\n" + " foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedIfSurroundOnOtherLine() = doTypeTest( '{', "fun foo() {\n" + " if(true) <caret>\n" + " foo()\n" + "}", "fun foo() {\n" + " if(true) {<caret>\n" + " foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedElseSurroundOnOtherLine() = doTypeTest( '{', "fun foo() {\n" + " if(true) {} else <caret>\n" + " foo()\n" + "}", "fun foo() {\n" + " if(true) {} else {<caret>\n" + " foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedTryOnOtherLine() = doTypeTest( '{', "fun foo() {\n" + " try <caret>\n" + " foo()\n" + "}", "fun foo() {\n" + " try {<caret>\n" + " foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedIfSurroundOnNewLine() = doTypeTest( '{', "fun foo() {\n" + " if(true)\n" + " <caret>\n" + " foo()\n" + "}", "fun foo() {\n" + " if(true)\n" + " {<caret>\n" + " foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedElseSurroundOnNewLine() = doTypeTest( '{', "fun foo() {\n" + " if(true) {} else\n" + " <caret>\n" + " foo()\n" + "}", "fun foo() {\n" + " if(true) {} else\n" + " {<caret>\n" + " foo()\n" + "}" ) fun testDoNotAutoCloseBraceInUnfinishedTryOnNewLine() = doTypeTest( '{', "fun foo() {\n" + " try\n" + " <caret>\n" + " foo()\n" + "}", "fun foo() {\n" + " try\n" + " {<caret>\n" + " foo()\n" + "}" ) fun testAutoCloseBraceInsideFor() = doTypeTest( '{', "fun foo() {\n" + " for (elem in some.filter <caret>) {\n" + " }\n" + "}", "fun foo() {\n" + " for (elem in some.filter {<caret>}) {\n" + " }\n" + "}" ) fun testAutoCloseBraceInsideForAfterCloseParen() = doTypeTest( '{', "fun foo() {\n" + " for (elem in some.foo(true) <caret>) {\n" + " }\n" + "}", "fun foo() {\n" + " for (elem in some.foo(true) {<caret>}) {\n" + " }\n" + "}" ) fun testAutoCloseBraceBeforeIf() = doTypeTest( '{', "fun foo() {\n" + " <caret>if (true) {}\n" + "}", "fun foo() {\n" + " {<caret>if (true) {}\n" + "}" ) fun testAutoCloseBraceInIfCondition() = doTypeTest( '{', "fun foo() {\n" + " if (some.hello (12) <caret>)\n" + "}", "fun foo() {\n" + " if (some.hello (12) {<caret>})\n" + "}" ) fun testInsertSpaceAfterRightBraceOfNestedLambda() = doTypeTest( '{', "val t = Array(100) { Array(200) <caret>}", "val t = Array(100) { Array(200) {<caret>} }" ) fun testAutoInsertParenInStringLiteral() = doTypeTest( '(', """fun f() { println("$dollar{f<caret>}") }""", """fun f() { println("$dollar{f(<caret>)}") }""" ) fun testAutoInsertParenInCode() = doTypeTest( '(', """fun f() { val a = f<caret> }""", """fun f() { val a = f(<caret>) }""" ) fun testSplitStringByEnter() = doTypeTest( '\n', """val s = "foo<caret>bar"""", "val s = \"foo\" +\n" + " \"bar\"" ) fun testSplitStringByEnterEmpty() = doTypeTest( '\n', """val s = "<caret>"""", "val s = \"\" +\n" + " \"\"" ) fun testSplitStringByEnterBeforeEscapeSequence() = doTypeTest( '\n', """val s = "foo<caret>\nbar"""", "val s = \"foo\" +\n" + " \"\\nbar\"" ) fun testSplitStringByEnterBeforeSubstitution() = doTypeTest( '\n', """val s = "foo<caret>${dollar}bar"""", "val s = \"foo\" +\n" + " \"${dollar}bar\"" ) fun testSplitStringByEnterAddParentheses() = doTypeTest( '\n', """val l = "foo<caret>bar".length()""", "val l = (\"foo\" +\n" + " \"bar\").length()" ) fun testSplitStringByEnterExistingParentheses() = doTypeTest( '\n', """val l = ("asdf" + "foo<caret>bar").length()""", "val l = (\"asdf\" + \"foo\" +\n" + " \"bar\").length()" ) fun testTypeLtInFunDeclaration() { doLtGtTest("fun <caret>") } fun testTypeLtInOngoingConstructorCall() { doLtGtTest("fun test() { Collection<caret> }") } fun testTypeLtInClassDeclaration() { doLtGtTest("class Some<caret> {}") } fun testTypeLtInPropertyType() { doLtGtTest("val a: List<caret> ") } fun testTypeLtInExtensionFunctionReceiver() { doLtGtTest("fun <T> Collection<caret> ") } fun testTypeLtInFunParam() { doLtGtTest("fun some(a : HashSet<caret>)") } fun testTypeLtInFun() { doLtGtTestNoAutoClose("fun some() { <<caret> }") } fun testTypeLtInLess() { doLtGtTestNoAutoClose("fun some() { val a = 12; a <<caret> }") } fun testColonOfSuperTypeList() { doTypeTest( ':', """ |open class A |class B |<caret> """, """ |open class A |class B | :<caret> """ ) } fun testColonOfSuperTypeListInObject() { doTypeTest( ':', """ |interface A |object B |<caret> """, """ |interface A |object B | :<caret> """ ) } fun testColonOfSuperTypeListInCompanionObject() { doTypeTest( ':', """ |interface A |class B { | companion object | <caret> |} """, """ |interface A |class B { | companion object | :<caret> |} """ ) } fun testColonOfSuperTypeListBeforeBody() { doTypeTest( ':', """ |open class A |class B |<caret> { |} """, """ |open class A |class B | :<caret> { |} """ ) } fun testColonOfSuperTypeListNotNullIndent() { doTypeTest( ':', """ |fun test() { | open class A | class B | <caret> |} """, """ |fun test() { | open class A | class B | :<caret> |} """ ) } fun testChainCallContinueWithDot() { doTypeTest( '.', """ |class Test{ fun test() = this } |fun some() { | Test() | <caret> |} """, """ |class Test{ fun test() = this } |fun some() { | Test() | .<caret> |} """, enableKotlinObsoleteCodeStyle, ) } fun testChainCallContinueWithDotWithOfficialCodeStyle() { doTypeTest( '.', """ |class Test{ fun test() = this } |fun some() { | Test() | <caret> |} """, """ |class Test{ fun test() = this } |fun some() { | Test() | .<caret> |} """, ) } fun testChainCallContinueWithSafeCall() { doTypeTest( '.', """ |class Test{ fun test() = this } |fun some() { | Test() | ?<caret> |} """, """ |class Test{ fun test() = this } |fun some() { | Test() | ?.<caret> |} """, enableKotlinObsoleteCodeStyle ) } fun testChainCallContinueWithSafeCallWithOfficialCodeStyle() { doTypeTest( '.', """ |class Test{ fun test() = this } |fun some() { | Test() | ?<caret> |} """, """ |class Test{ fun test() = this } |fun some() { | Test() | ?.<caret> |} """, enableKotlinObsoleteCodeStyle ) } fun testContinueWithElvis() { doTypeTest( ':', """ |fun test(): Any? = null |fun some() { | test() | ?<caret> |} """, """ |fun test(): Any? = null |fun some() { | test() | ?:<caret> |} """, enableKotlinObsoleteCodeStyle ) } fun testContinueWithElvisWithOfficialCodeStyle() { doTypeTest( ':', """ |fun test(): Any? = null |fun some() { | test() | ?<caret> |} """, """ |fun test(): Any? = null |fun some() { | test() | ?:<caret> |} """ ) } fun testContinueWithOr() { doTypeTest( '|', """ |fun some() { | if (true | |<caret>) |} """, """ |fun some() { | if (true | ||<caret>) |} """, enableKotlinObsoleteCodeStyle ) } fun testContinueWithOrWithOfficialCodeStyle() { doTypeTest( '|', """ |fun some() { | if (true | |<caret>) |} """, """ |fun some() { | if (true | ||<caret>) |} """ ) } fun testContinueWithAnd() { doTypeTest( '&', """ |fun some() { | val test = true | &<caret> |} """, """ |fun some() { | val test = true | &&<caret> |} """ ) } fun testSpaceAroundRange() { doTypeTest( '.', """ | val test = 1 <caret> """, """ | val test = 1 .<caret> """ ) } fun testIndentBeforeElseWithBlock() { doTypeTest( '\n', """ |fun test(b: Boolean) { | if (b) { | }<caret> | else if (!b) { | } |} """, """ |fun test(b: Boolean) { | if (b) { | } | <caret> | else if (!b) { | } |} """ ) } fun testIndentBeforeElseWithoutBlock() { doTypeTest( '\n', """ |fun test(b: Boolean) { | if (b) | foo()<caret> | else { | } |} """, """ |fun test(b: Boolean) { | if (b) | foo() | <caret> | else { | } |} """ ) } fun testIndentOnFinishedVariableEndAfterEquals() { doTypeTest( '\n', """ |fun test() { | val a =<caret> | foo() |} """, """ |fun test() { | val a = | <caret> | foo() |} """, enableKotlinObsoleteCodeStyle ) } fun testIndentOnFinishedVariableEndAfterEqualsWithOfficialCodeStyle() { doTypeTest( '\n', """ |fun test() { | val a =<caret> | foo() |} """, """ |fun test() { | val a = | <caret> | foo() |} """ ) } fun testIndentNotFinishedVariableEndAfterEquals() { doTypeTest( '\n', """ |fun test() { | val a =<caret> |} """, """ |fun test() { | val a = | <caret> |} """, enableKotlinObsoleteCodeStyle ) } fun testIndentNotFinishedVariableEndAfterEqualsWithOfficialCodeStyle() { doTypeTest( '\n', """ |fun test() { | val a =<caret> |} """, """ |fun test() { | val a = | <caret> |} """ ) } fun testSmartEnterWithTabsOnConstructorParameters() { doTypeTest( '\n', """ |class A( | a: Int,<caret> |) """, """ |class A( | a: Int, | <caret> |) """ ) { enableSmartEnter(it) enableTabs(it) } } fun testSmartEnterWithTabsInMethodParameters() { doTypeTest( '\n', """ |fun method( | arg1: String,<caret> |) {} """, """ |fun method( | arg1: String, | <caret> |) {} """ ) { enableSmartEnter(it) enableTabs(it) } } fun testEnterWithoutLineBreakBeforeClosingBracketInMethodParameters() { doTypeTest( '\n', """ |fun method( | arg1: String,<caret>) {} """, """ |fun method( | arg1: String, |<caret>) {} """, enableSmartEnter ) } fun testSmartEnterWithTrailingCommaAndWhitespaceBeforeLineBreak() { doTypeTest( '\n', """ |fun method( | arg1: String, <caret> |) {} """, """ |fun method( | arg1: String, | <caret> |) {} """, enableSmartEnter ) } fun testSmartEnterBetweenOpeningAndClosingBrackets() { doTypeTest( '\n', """ |fun method(<caret>) {} """, """ |fun method( | <caret> |) {} """ ) { enableKotlinObsoleteCodeStyle(it) enableSmartEnter(it) } } fun testSmartEnterBetweenOpeningAndClosingBracketsWithOfficialCodeStyle() { doTypeTest( '\n', """ |fun method(<caret>) {} """, """ |fun method( | <caret> |) {} """, enableSmartEnter ) } private val enableSettingsWithInvertedAlignWhenMultiline: (CodeStyleSettings) -> Unit get() = { val settings = it.kotlinCommonSettings settings.ALIGN_MULTILINE_PARAMETERS = !settings.ALIGN_MULTILINE_PARAMETERS settings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS = !settings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS } fun testSmartEnterWithTabsOnConstructorParametersWithInvertedAlignWhenMultiline() { doTypeTest( '\n', """ |class A( | a: Int,<caret> |) """, """ |class A( | a: Int, | <caret> |) """ ) { enableKotlinObsoleteCodeStyle(it) enableSettingsWithInvertedAlignWhenMultiline(it) enableSmartEnter(it) enableTabs(it) } } fun testSmartEnterWithTabsOnConstructorParametersWithInvertedAlignWhenMultilineWithOfficialCodeStyle() { doTypeTest( '\n', """ |class A( | a: Int,<caret> |) """, """ |class A( | a: Int, | <caret> |) """ ) { enableSettingsWithInvertedAlignWhenMultiline(it) enableSmartEnter(it) enableTabs(it) } } fun testSmartEnterWithTabsInMethodParametersWithInvertedAlignWhenMultiline() { doTypeTest( '\n', """ |fun method( | arg1: String,<caret> |) {} """, """ |fun method( | arg1: String, | <caret> |) {} """ ) { enableKotlinObsoleteCodeStyle(it) enableSettingsWithInvertedAlignWhenMultiline(it) enableSmartEnter(it) enableTabs(it) } } fun testEnterWithoutLineBreakBeforeClosingBracketInMethodParametersWithInvertedAlignWhenMultiline() { doTypeTest( '\n', """ |fun method( | arg1: String,<caret>) {} """, """ |fun method( | arg1: String, |<caret>) {} """, enableSettingsWithInvertedAlignWhenMultiline ) } fun testEnterWithTrailingCommaAndWhitespaceBeforeLineBreakWithInvertedAlignWhenMultiline() { doTypeTest( '\n', """ |fun method( | arg1: String, <caret> |) {} """, """ |fun method( | arg1: String, | <caret> |) {} """, enableSettingsWithInvertedAlignWhenMultiline ) } fun testSmartEnterBetweenOpeningAndClosingBracketsWithInvertedAlignWhenMultiline() { doTypeTest( '\n', """ |fun method(<caret>) {} """, """ |fun method( | <caret> |) {} """ ) { enableKotlinObsoleteCodeStyle(it) enableSettingsWithInvertedAlignWhenMultiline(it) enableSmartEnter(it) } } fun testSmartEnterBetweenOpeningAndClosingBracketsWithInvertedAlignWhenMultilineWithOfficialCodeStyle() { doTypeTest( '\n', """ |fun method(<caret>) {} """, """ |fun method( | <caret> |) {} """ ) { enableSettingsWithInvertedAlignWhenMultiline(it) enableSmartEnter(it) } } fun testAutoIndentInWhenClause() { doTypeTest( '\n', """ |fun test() { | when (2) { | is Int -><caret> | } |} """, """ |fun test() { | when (2) { | is Int -> | <caret> | } |} """ ) } fun testValInserterOnClass() = testValInserter(',', """data class xxx(val x: Int<caret>)""", """data class xxx(val x: Int,<caret>)""") fun testValInserterOnSimpleDataClass() = testValInserter(',', """data class xxx(x: Int<caret>)""", """data class xxx(val x: Int,<caret>)""") fun testValInserterOnValWithComment() = testValInserter(',', """data class xxx(x: Int /*comment*/ <caret>)""", """data class xxx(val x: Int /*comment*/ ,<caret>)""") fun testValInserterOnValWithInitializer() = testValInserter(',', """data class xxx(x: Int = 2<caret>)""", """data class xxx(val x: Int = 2,<caret>)""") fun testValInserterOnValWithInitializerWithOutType() = testValInserter(',', """data class xxx(x = 2<caret>)""", """data class xxx(x = 2,<caret>)""") fun testValInserterOnValWithGenericType() = testValInserter(',', """data class xxx(x: A<B><caret>)""", """data class xxx(val x: A<B>,<caret>)""") fun testValInserterOnValWithNoType() = testValInserter(',', """data class xxx(x<caret>)""", """data class xxx(x,<caret>)""") fun testValInserterOnValWithIncompleteGenericType() = testValInserter(',', """data class xxx(x: A<B,C<caret>)""", """data class xxx(x: A<B,C,<caret>)""") fun testValInserterOnValWithInvalidComma() = testValInserter(',', """data class xxx(x:<caret> A<B>)""", """data class xxx(x:,<caret> A<B>)""") fun testValInserterOnValWithInvalidGenericType() = testValInserter(',', """data class xxx(x: A><caret>)""", """data class xxx(x: A>,<caret>)""") fun testValInserterOnInMultiline() = testValInserter( ',', """ |data class xxx( | val a: A, | b: B<caret> | val c: C |) """, """ |data class xxx( | val a: A, | val b: B,<caret> | val c: C |) """ ) fun testValInserterOnValInsertedInsideOtherParameters() = testValInserter( ',', """data class xxx(val a: A, b: A<caret>val c: A)""", """data class xxx(val a: A, val b: A,<caret>val c: A)""" ) fun testValInserterOnSimpleInlineClass() = testValInserter(')', """inline class xxx(a: A<caret>)""", """inline class xxx(val a: A)<caret>""") fun testValInserterOnValInsertedWithSquare() = testValInserter(')', """data class xxx(val a: A, b: A<caret>)""", """data class xxx(val a: A, val b: A)<caret>""") fun testValInserterOnTypingMissedSquare() = testValInserter(')', """data class xxx(val a: A, b: A<caret>""", """data class xxx(val a: A, val b: A)<caret>""") fun testValInserterWithDisabledSetting() = testValInserter(',', """data class xxx(x: Int<caret>)""", """data class xxx(x: Int,<caret>)""", inserterEnabled = false) fun testEnterInFunctionWithExpressionBody() { doTypeTest( '\n', """ |fun test() =<caret> """, """ |fun test() = | <caret> """ ) } fun testEnterInMultiDeclaration() { doTypeTest( '\n', """ |fun test() { | val (a, b) =<caret> |} """, """ |fun test() { | val (a, b) = | <caret> |} """ ) } fun testEnterInVariableDeclaration() { doTypeTest( '\n', """ |val test =<caret> """, """ |val test = | <caret> """ ) } fun testMoveThroughGT() { myFixture.configureByText("a.kt", "val a: List<Set<Int<caret>>>") EditorTestUtil.performTypingAction(editor, '>') EditorTestUtil.performTypingAction(editor, '>') myFixture.checkResult("val a: List<Set<Int>><caret>") } fun testCharClosingQuote() { doTypeTest('\'', "val c = <caret>", "val c = ''") } private val enableSmartEnter: (CodeStyleSettings) -> Unit get() = { val indentOptions = it.getLanguageIndentOptions(KotlinLanguage.INSTANCE) indentOptions.SMART_TABS = true } private val enableTabs: (CodeStyleSettings) -> Unit get() = { val indentOptions = it.getLanguageIndentOptions(KotlinLanguage.INSTANCE) indentOptions.USE_TAB_CHARACTER = true } private fun doTypeTest(ch: Char, beforeText: String, afterText: String, settingsModifier: ((CodeStyleSettings) -> Unit) = { }) { doTypeTest(ch.toString(), beforeText, afterText, settingsModifier) } private fun doTypeTest(text: String, beforeText: String, afterText: String, settingsModifier: ((CodeStyleSettings) -> Unit) = { }) { configureCodeStyleAndRun(project, configurator = { settingsModifier(it) }) { myFixture.configureByText("a.kt", beforeText.trimMargin()) for (ch in text) { myFixture.type(ch) } myFixture.checkResult(afterText.trimMargin()) } } private fun testValInserter(ch: Char, beforeText: String, afterText: String, inserterEnabled: Boolean = true) { val editorOptions = KotlinEditorOptions.getInstance() val wasEnabled = editorOptions.isAutoAddValKeywordToDataClassParameters try { editorOptions.isAutoAddValKeywordToDataClassParameters = inserterEnabled doTypeTest(ch, beforeText, afterText) } finally { editorOptions.isAutoAddValKeywordToDataClassParameters = wasEnabled } } private fun doLtGtTestNoAutoClose(initText: String) { doLtGtTest(initText, false) } private fun doLtGtTest(initText: String, shouldCloseBeInsert: Boolean) { myFixture.configureByText("a.kt", initText) EditorTestUtil.performTypingAction(editor, '<') myFixture.checkResult( if (shouldCloseBeInsert) initText.replace("<caret>", "<<caret>>") else initText.replace( "<caret>", "<<caret>" ) ) EditorTestUtil.performTypingAction(editor, EditorTestUtil.BACKSPACE_FAKE_CHAR) myFixture.checkResult(initText) } private fun doLtGtTest(initText: String) { doLtGtTest(initText, true) } private val enableKotlinObsoleteCodeStyle: (CodeStyleSettings) -> Unit = { KotlinObsoleteCodeStyle.apply(it) } }
apache-2.0
19e9cbf73b55477e84b0ca3651a78676
25.704309
158
0.389478
5.153857
false
true
false
false
Zhouzhouzhou/AndroidDemo
app/src/main/java/com/zhou/android/main/FocusDrawActivity.kt
1
1509
package com.zhou.android.main import android.graphics.Bitmap import android.graphics.BitmapFactory import android.view.ViewGroup import android.widget.Button import android.widget.RelativeLayout import com.zhou.android.R import com.zhou.android.common.BaseActivity import com.zhou.android.ui.FocusDrawView import kotlinx.android.synthetic.main.layout_app.view.* /** * Created by mxz on 2019/9/3. */ class FocusDrawActivity : BaseActivity() { private lateinit var focus: FocusDrawView private lateinit var b: Bitmap override fun setContentView() { b = BitmapFactory.decodeResource(resources, R.drawable.pic_head) val layout = RelativeLayout(this).apply { layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) } focus = FocusDrawView(this) layout.addView(focus) val btn = Button(this).apply { text = "加载位图" layoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT).apply { addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) addRule(RelativeLayout.CENTER_HORIZONTAL) bottomMargin = 20 } setOnClickListener { focus.setBitmap(b) } } layout.addView(btn) setContentView(layout) } override fun init() { } override fun addListener() { } }
mit
e467a338be60845151bcf8a4b543c256
27.884615
146
0.674883
4.676012
false
false
false
false
siosio/intellij-community
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/configuration/KotlinMPPDataNodes.kt
1
3678
// 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.configuration import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.AbstractExternalEntityData import com.intellij.openapi.externalSystem.model.project.AbstractNamedData import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.util.Key import com.intellij.serialization.PropertyMapping import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.config.ExternalSystemRunTask import org.jetbrains.kotlin.gradle.* import org.jetbrains.kotlin.idea.util.CopyableDataNodeUserDataProperty import org.jetbrains.plugins.gradle.util.GradleConstants import java.io.File import java.io.Serializable import com.intellij.openapi.externalSystem.model.Key as ExternalKey var DataNode<out ModuleData>.kotlinSourceSet: KotlinSourceSetInfo? by CopyableDataNodeUserDataProperty(Key.create("KOTLIN_SOURCE_SET")) val DataNode<out ModuleData>.kotlinAndroidSourceSets: List<KotlinSourceSetInfo>? get() = ExternalSystemApiUtil.getChildren(this, KotlinAndroidSourceSetData.KEY).firstOrNull()?.data?.sourceSetInfos class KotlinSourceSetInfo @PropertyMapping("kotlinModule") constructor(val kotlinModule: KotlinModule) : Serializable { var moduleId: String? = null var gradleModuleId: String = "" var actualPlatforms: KotlinPlatformContainer = KotlinPlatformContainerImpl() @Deprecated("Returns only single TargetPlatform", ReplaceWith("actualPlatforms.actualPlatforms"), DeprecationLevel.ERROR) val platform: KotlinPlatform get() = actualPlatforms.platforms.singleOrNull() ?: KotlinPlatform.COMMON @Transient var defaultCompilerArguments: CommonCompilerArguments? = null @Transient var compilerArguments: CommonCompilerArguments? = null var dependencyClasspath: List<String> = emptyList() var isTestModule: Boolean = false var sourceSetIdsByName: MutableMap<String, String> = LinkedHashMap() var dependsOn: List<String> = emptyList() var externalSystemRunTasks: Collection<ExternalSystemRunTask> = emptyList() } class KotlinAndroidSourceSetData @PropertyMapping("sourceSetInfos") constructor(val sourceSetInfos: List<KotlinSourceSetInfo> ) : AbstractExternalEntityData(GradleConstants.SYSTEM_ID) { companion object { val KEY = ExternalKey.create(KotlinAndroidSourceSetData::class.java, KotlinTargetData.KEY.processingWeight + 1) } } class KotlinTargetData @PropertyMapping("externalName") constructor(externalName: String) : AbstractNamedData(GradleConstants.SYSTEM_ID, externalName) { var moduleIds: Set<String> = emptySet() var archiveFile: File? = null var konanArtifacts: Collection<KonanArtifactModel>? = null companion object { val KEY = ExternalKey.create(KotlinTargetData::class.java, ProjectKeys.MODULE.processingWeight + 1) } } class KotlinOutputPathsData @PropertyMapping("paths") constructor(val paths: MultiMap<ExternalSystemSourceType, String>) : AbstractExternalEntityData(GradleConstants.SYSTEM_ID) { companion object { val KEY = ExternalKey.create(KotlinOutputPathsData::class.java, ProjectKeys.CONTENT_ROOT.processingWeight + 1) } }
apache-2.0
621d43adf6634fc90a29f8c5bb1a9f24
48.04
158
0.804785
4.904
false
false
false
false
mseroczynski/CityBikes
app/src/main/kotlin/pl/ches/citybikes/presentation/screen/main/stations/StationsFragment.kt
1
3259
package pl.ches.citybikes.presentation.screen.main.stations import android.content.Context import android.os.Bundle import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.LinearLayoutManager import android.view.View import com.hannesdorfmann.mosby.mvp.viewstate.lce.LceViewState import com.hannesdorfmann.mosby.mvp.viewstate.lce.data.RetainingLceViewState import com.jakewharton.rxbinding.support.design.widget.offsetChanges import com.jakewharton.rxbinding.support.v4.widget.refreshes import kotlinx.android.synthetic.main.app_bar_stations.* import kotlinx.android.synthetic.main.fragment_stations.* import pl.ches.citybikes.App import pl.ches.citybikes.R import pl.ches.citybikes.data.disk.entity.Station import pl.ches.citybikes.presentation.common.base.view.BaseLceViewStateFragmentSrl import pl.ches.citybikes.presentation.common.widget.DividerItemDecoration /** * @author Michał Seroczyński <[email protected]> */ class StationsFragment : BaseLceViewStateFragmentSrl<SwipeRefreshLayout, List<Pair<Station, Float>>, StationsView, StationsPresenter>(), StationsView, StationAdapter.Listener { private val component = App.component().plusStations() private lateinit var adapter: StationAdapter private lateinit var stationChooseListener: StationChooseListener //region Setup override val layoutRes by lazy { R.layout.fragment_stations } override fun injectDependencies() = component.inject(this) override fun createPresenter(): StationsPresenter = component.presenter() override fun onAttach(context: Context?) { super.onAttach(context) try { stationChooseListener = context as StationChooseListener } catch (e: ClassCastException) { throw ClassCastException(activity.toString() + " must implement ${StationChooseListener::class.java.simpleName}") } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) appBarLay.offsetChanges().subscribe { contentView.isEnabled = it == 0 } contentView.refreshes().subscribe { loadData(true) } adapter = StationAdapter(activity, this) recyclerView.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false) recyclerView.adapter = adapter recyclerView.isNestedScrollingEnabled = false val dividerItemDecoration = DividerItemDecoration(activity, R.drawable.bg_line_divider, false, false) recyclerView.addItemDecoration(dividerItemDecoration) } override fun loadData(pullToRefresh: Boolean) = presenter.loadData(pullToRefresh) override fun createViewState(): LceViewState<List<Pair<Station, Float>>, StationsView> = RetainingLceViewState() override fun getData(): List<Pair<Station, Float>> = adapter.getItems() override fun setData(data: List<Pair<Station, Float>>) { adapter.swapItems(data) // onStationClicked(data.first().first) } //endregion //region Events override fun onStationClicked(station: Station) = stationChooseListener.stationChosen(station) //endregion companion object { fun newInstance() = StationsFragment() } }
gpl-3.0
2e6b051051994c11be12201dee8b1fbb
38.253012
176
0.78907
4.62642
false
false
false
false
jwren/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/cli/common/arguments/CliArgumentStringBuilder.kt
3
3318
// 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.cli.common.arguments import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion object CliArgumentStringBuilder { private const val LANGUAGE_FEATURE_FLAG_PREFIX = "-XXLanguage:" private const val LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX = "-X" private val LanguageFeature.dedicatedFlagInfo get() = when (this) { LanguageFeature.InlineClasses -> Pair("inline-classes", KotlinVersion(1, 3, 50)) else -> null } private val LanguageFeature.State.sign: String get() = when (this) { LanguageFeature.State.ENABLED -> "+" LanguageFeature.State.DISABLED -> "-" LanguageFeature.State.ENABLED_WITH_WARNING -> "+" // not supported normally LanguageFeature.State.ENABLED_WITH_ERROR -> "-" // not supported normally } private fun LanguageFeature.getFeatureMentionInCompilerArgsRegex(): Regex { val basePattern = "$LANGUAGE_FEATURE_FLAG_PREFIX(?:-|\\+)$name" val fullPattern = if (dedicatedFlagInfo != null) "(?:$basePattern)|$LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX${dedicatedFlagInfo!!.first}" else basePattern return Regex(fullPattern) } fun LanguageFeature.buildArgumentString(state: LanguageFeature.State, kotlinVersion: IdeKotlinVersion?): String { val shouldBeFeatureEnabled = state == LanguageFeature.State.ENABLED || state == LanguageFeature.State.ENABLED_WITH_WARNING val dedicatedFlag = dedicatedFlagInfo?.run { val (xFlag, xFlagSinceVersion) = this if (kotlinVersion == null || kotlinVersion.kotlinVersion >= xFlagSinceVersion) xFlag else null } return if (shouldBeFeatureEnabled && dedicatedFlag != null) { LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX + dedicatedFlag } else { "$LANGUAGE_FEATURE_FLAG_PREFIX${state.sign}$name" } } fun String.replaceLanguageFeature( feature: LanguageFeature, state: LanguageFeature.State, kotlinVersion: IdeKotlinVersion?, prefix: String = "", postfix: String = "", separator: String = ", ", quoted: Boolean = true ): String { val quote = if (quoted) "\"" else "" val featureArgumentString = feature.buildArgumentString(state, kotlinVersion) val existingFeatureMatchResult = feature.getFeatureMentionInCompilerArgsRegex().find(this) return if (existingFeatureMatchResult != null) { replace(existingFeatureMatchResult.value, featureArgumentString) } else { val splitText = if (postfix.isNotEmpty()) split(postfix) else listOf(this, "") if (splitText.size != 2) { "$prefix$quote$featureArgumentString$quote$postfix" } else { val (mainPart, commentPart) = splitText // In Groovy / Kotlin DSL, we can have comment after [...] or listOf(...) mainPart + "$separator$quote$featureArgumentString$quote$postfix" + commentPart } } } }
apache-2.0
0972dda8e8e7db5bd86f336387efa2a0
43.851351
158
0.655515
4.944858
false
false
false
false
jwren/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/actions/ConfigureKotlinInProjectAction.kt
3
3074
// 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 import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.util.PlatformUtils import org.jetbrains.kotlin.idea.KotlinJvmBundle import org.jetbrains.kotlin.idea.configuration.* import org.jetbrains.kotlin.idea.util.ProgressIndicatorUtils.underModalProgress import org.jetbrains.kotlin.idea.util.projectStructure.allModules import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.platform.jvm.isJvm abstract class ConfigureKotlinInProjectAction : AnAction() { abstract fun getApplicableConfigurators(project: Project): Collection<KotlinProjectConfigurator> override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val (modules, configurators) = underModalProgress(project, KotlinJvmBundle.message("lookup.project.configurators.progress.text")) { val modules = getConfigurableModules(project) if (modules.all(::isModuleConfigured)) { return@underModalProgress modules to emptyList<KotlinProjectConfigurator>() } val configurators = getApplicableConfigurators(project) modules to configurators } if (modules.all(::isModuleConfigured)) { Messages.showInfoMessage(KotlinJvmBundle.message("all.modules.with.kotlin.files.are.configured"), e.presentation.text!!) return } when { configurators.size == 1 -> configurators.first().configure(project, emptyList()) configurators.isEmpty() -> Messages.showErrorDialog( KotlinJvmBundle.message("there.aren.t.configurators.available"), e.presentation.text!! ) else -> { val configuratorsPopup = KotlinSetupEnvironmentNotificationProvider.createConfiguratorsPopup(project, configurators.toList()) configuratorsPopup.showInBestPositionFor(e.dataContext) } } } } class ConfigureKotlinJsInProjectAction : ConfigureKotlinInProjectAction() { override fun getApplicableConfigurators(project: Project) = getAbleToRunConfigurators(project).filter { it.targetPlatform.isJs() } override fun update(e: AnActionEvent) { val project = e.project if (!PlatformUtils.isIntelliJ() && (project == null || project.allModules().all { it.getBuildSystemType() != BuildSystemType.JPS }) ) { e.presentation.isEnabledAndVisible = false } } } class ConfigureKotlinJavaInProjectAction : ConfigureKotlinInProjectAction() { override fun getApplicableConfigurators(project: Project) = getAbleToRunConfigurators(project).filter { it.targetPlatform.isJvm() } }
apache-2.0
18462eb8b2e07f799718a653c05bb70a
41.123288
158
0.710475
5.254701
false
true
false
false
jwren/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/IDELightClassGenerationSupport.kt
1
7605
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.caches.resolve import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.util.containers.ConcurrentFactoryMap import org.jetbrains.kotlin.asJava.LightClassBuilder import org.jetbrains.kotlin.asJava.LightClassGenerationSupport import org.jetbrains.kotlin.asJava.builder.InvalidLightClassDataHolder import org.jetbrains.kotlin.asJava.builder.LightClassDataHolder import org.jetbrains.kotlin.asJava.classes.* import org.jetbrains.kotlin.asJava.finder.JavaElementFinder import org.jetbrains.kotlin.codegen.ClassBuilderMode import org.jetbrains.kotlin.codegen.JvmCodegenUtil import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper import org.jetbrains.kotlin.config.JvmTarget import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.caches.lightClasses.IDELightClassContexts import org.jetbrains.kotlin.idea.caches.lightClasses.LazyLightClassDataHolder import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.project.platform import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.stubindex.KotlinTypeAliasShortNameIndex import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.platform.jvm.JdkPlatform import org.jetbrains.kotlin.platform.subplatformsOfType import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import java.util.concurrent.ConcurrentMap class IDELightClassGenerationSupport(project: Project) : LightClassGenerationSupport() { private class KtUltraLightSupportImpl(private val element: KtElement) : KtUltraLightSupport { private val module = ModuleUtilCore.findModuleForPsiElement(element) override val languageVersionSettings: LanguageVersionSettings get() = module?.languageVersionSettings ?: KotlinTypeMapper.LANGUAGE_VERSION_SETTINGS_DEFAULT private val resolutionFacade get() = element.getResolutionFacade() override val moduleDescriptor get() = resolutionFacade.moduleDescriptor override val moduleName: String by lazyPub { JvmCodegenUtil.getModuleName(moduleDescriptor) } override fun possiblyHasAlias(file: KtFile, shortName: Name): Boolean = allAliases(file)[shortName.asString()] == true private fun allAliases(file: KtFile): ConcurrentMap<String, Boolean> = CachedValuesManager.getCachedValue(file) { val importAliases = file.importDirectives.mapNotNull { it.aliasName }.toSet() val map = ConcurrentFactoryMap.createMap<String, Boolean> { s -> s in importAliases || KotlinTypeAliasShortNameIndex.get(s, file.project, file.resolveScope).isNotEmpty() } CachedValueProvider.Result.create<ConcurrentMap<String, Boolean>>(map, PsiModificationTracker.MODIFICATION_COUNT) } @OptIn(FrontendInternals::class) override val deprecationResolver: DeprecationResolver get() = resolutionFacade.getFrontendService(DeprecationResolver::class.java) override val typeMapper: KotlinTypeMapper by lazyPub { KotlinTypeMapper( BindingContext.EMPTY, ClassBuilderMode.LIGHT_CLASSES, moduleName, languageVersionSettings, useOldInlineClassesManglingScheme = false, jvmTarget = module?.platform?.subplatformsOfType<JdkPlatform>()?.firstOrNull()?.targetVersion ?: JvmTarget.DEFAULT, typePreprocessor = KotlinType::cleanFromAnonymousTypes, namePreprocessor = ::tryGetPredefinedName ) } } override fun getUltraLightClassSupport(element: KtElement): KtUltraLightSupport = KtUltraLightSupportImpl(element) override val useUltraLightClasses: Boolean get() = !KtUltraLightSupport.forceUsingOldLightClasses && Registry.`is`("kotlin.use.ultra.light.classes", true) private val scopeFileComparator = JavaElementFinder.byClasspathComparator(GlobalSearchScope.allScope(project)) override fun createDataHolderForClass(classOrObject: KtClassOrObject, builder: LightClassBuilder): LightClassDataHolder.ForClass { return when { classOrObject.shouldNotBeVisibleAsLightClass() -> InvalidLightClassDataHolder classOrObject.isLocal -> LazyLightClassDataHolder.ForClass( builder, exactContextProvider = { IDELightClassContexts.contextForLocalClassOrObject(classOrObject) }, dummyContextProvider = null, diagnosticsHolderProvider = { classOrObject.getDiagnosticsHolder() } ) else -> LazyLightClassDataHolder.ForClass( builder, exactContextProvider = { IDELightClassContexts.contextForNonLocalClassOrObject(classOrObject) }, dummyContextProvider = { IDELightClassContexts.lightContextForClassOrObject(classOrObject) }, diagnosticsHolderProvider = { classOrObject.getDiagnosticsHolder() } ) } } override fun createDataHolderForFacade(files: Collection<KtFile>, builder: LightClassBuilder): LightClassDataHolder.ForFacade { assert(!files.isEmpty()) { "No files in facade" } val sortedFiles = files.sortedWith(scopeFileComparator) return LazyLightClassDataHolder.ForFacade( builder, exactContextProvider = { IDELightClassContexts.contextForFacade(sortedFiles) }, dummyContextProvider = { IDELightClassContexts.lightContextForFacade(sortedFiles) }, diagnosticsHolderProvider = { files.first().getDiagnosticsHolder() } ) } override fun createDataHolderForScript(script: KtScript, builder: LightClassBuilder): LightClassDataHolder.ForScript { return LazyLightClassDataHolder.ForScript( builder, exactContextProvider = { IDELightClassContexts.contextForScript(script) }, dummyContextProvider = { null }, diagnosticsHolderProvider = { script.getDiagnosticsHolder() } ) } @OptIn(FrontendInternals::class) private fun KtElement.getDiagnosticsHolder() = getResolutionFacade().frontendService<LazyLightClassDataHolder.DiagnosticsHolder>() override fun resolveToDescriptor(declaration: KtDeclaration): DeclarationDescriptor? = declaration.resolveToDescriptorIfAny(BodyResolveMode.FULL) override fun analyze(element: KtElement) = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) override fun analyzeAnnotation(element: KtAnnotationEntry): AnnotationDescriptor? = element.resolveToDescriptorIfAny() override fun analyzeWithContent(element: KtClassOrObject) = element.safeAnalyzeWithContentNonSourceRootCode() }
apache-2.0
1107c83e773d840a20ac09d00bdbf345
50.734694
158
0.761867
5.56735
false
false
false
false
jwren/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/psi/UastKotlinPsiParameter.kt
4
2873
// 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.uast.kotlin.psi import com.intellij.lang.Language import com.intellij.openapi.components.ServiceManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiParameter import com.intellij.psi.PsiType import com.intellij.psi.impl.light.LightParameter import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.uast.UDeclaration import org.jetbrains.uast.UElement import org.jetbrains.uast.UastErrorType import org.jetbrains.uast.getParentOfType import org.jetbrains.uast.kotlin.BaseKotlinUastResolveProviderService @ApiStatus.Internal class UastKotlinPsiParameter( name: String, type: PsiType, parent: PsiElement, language: Language, isVarArgs: Boolean, ktDefaultValue: KtExpression?, ktParameter: KtParameter ) : UastKotlinPsiParameterBase<KtParameter>(name, type, parent, ktParameter, language, isVarArgs, ktDefaultValue) { companion object { fun create( parameter: KtParameter, parent: PsiElement, containingElement: UElement, index: Int ): PsiParameter { val service = ServiceManager.getService(BaseKotlinUastResolveProviderService::class.java) val psiParent = containingElement.getParentOfType<UDeclaration>()?.javaPsi ?: parent return UastKotlinPsiParameter( parameter.name ?: "p$index", service.getType(parameter, containingElement) ?: UastErrorType, psiParent, KotlinLanguage.INSTANCE, parameter.isVarArg, parameter.defaultValue, parameter ) } } val ktParameter: KtParameter get() = ktOrigin } @ApiStatus.Internal open class UastKotlinPsiParameterBase<T : KtElement>( name: String, type: PsiType, private val parent: PsiElement, val ktOrigin: T, language: Language = ktOrigin.language, isVarArgs: Boolean = false, val ktDefaultValue: KtExpression? = null, ) : LightParameter(name, type, parent, language, isVarArgs) { override fun getParent(): PsiElement = parent override fun getContainingFile(): PsiFile? = ktOrigin.containingFile override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other::class.java != this::class.java) return false return ktOrigin == (other as? UastKotlinPsiParameterBase<*>)?.ktOrigin } override fun hashCode(): Int = ktOrigin.hashCode() }
apache-2.0
bd048247d3f472b277991c70140ff636
35.367089
158
0.7118
4.987847
false
false
false
false
JetBrains/intellij-community
platform/lang-impl/testSources/com/intellij/toolWindow/ToolWindowManagerTestCase.kt
1
1973
// 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.toolWindow import com.intellij.openapi.application.EDT import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ex.ToolWindowManagerListener.ToolWindowManagerEventType import com.intellij.openapi.wm.impl.IdeFrameImpl import com.intellij.openapi.wm.impl.ProjectFrameHelper import com.intellij.openapi.wm.impl.ToolWindowManagerImpl import com.intellij.testFramework.LightPlatformTestCase import com.intellij.testFramework.SkipInHeadlessEnvironment import com.intellij.testFramework.replaceService import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext @SkipInHeadlessEnvironment abstract class ToolWindowManagerTestCase : LightPlatformTestCase() { @JvmField protected var manager: ToolWindowManagerImpl? = null final override fun runInDispatchThread() = false public override fun setUp() { super.setUp() runBlocking { val project = project manager = object : ToolWindowManagerImpl(project) { override fun fireStateChanged(changeType: ToolWindowManagerEventType) {} } project.replaceService(ToolWindowManager::class.java, manager!!, testRootDisposable) val frame = withContext(Dispatchers.EDT) { val frame = ProjectFrameHelper(IdeFrameImpl()) frame.init() frame } val reopeningEditorsJob = Job().also { it.complete() } manager!!.doInit(frame, project.messageBus.connect(testRootDisposable), reopeningEditorsJob, taskListDeferred = null) } } public override fun tearDown() { try { manager?.let { Disposer.dispose(it) } manager = null } catch (e: Throwable) { addSuppressedException(e) } finally { super.tearDown() } } }
apache-2.0
aadf3e5f70c35cacc879c5a841a6273a
32.457627
123
0.757729
4.90796
false
true
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/javac/JavacProcessingEnv.kt
3
11980
/* * Copyright (C) 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.room.compiler.processing.javac import androidx.room.compiler.processing.XElement import androidx.room.compiler.processing.XMessager import androidx.room.compiler.processing.XNullability import androidx.room.compiler.processing.XProcessingEnv import androidx.room.compiler.processing.XProcessingEnvConfig import androidx.room.compiler.processing.XType import androidx.room.compiler.processing.XTypeElement import androidx.room.compiler.processing.javac.kotlin.KmType import com.google.auto.common.GeneratedAnnotations import com.google.auto.common.MoreTypes import java.util.Locale import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.ExecutableElement import javax.lang.model.element.PackageElement import javax.lang.model.element.TypeElement import javax.lang.model.element.VariableElement import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror import javax.lang.model.util.Elements import javax.lang.model.util.Types internal class JavacProcessingEnv( val delegate: ProcessingEnvironment, override val config: XProcessingEnvConfig, ) : XProcessingEnv { override val backend: XProcessingEnv.Backend = XProcessingEnv.Backend.JAVAC val elementUtils: Elements = delegate.elementUtils val typeUtils: Types = delegate.typeUtils private val typeElementStore = XTypeElementStore( findElement = { qName -> delegate.elementUtils.getTypeElement(qName) }, wrap = { typeElement -> JavacTypeElement.create(this, typeElement) }, getQName = { it.qualifiedName.toString() } ) override val messager: XMessager by lazy { JavacProcessingEnvMessager(delegate.messager) } override val filer = JavacFiler(this, delegate.filer) override val options: Map<String, String> get() = delegate.options // SourceVersion enum constants are named 'RELEASE_x' and since they are public APIs, its safe // to assume they won't change and we can extract the version from them. override val jvmVersion = delegate.sourceVersion.name.substringAfter("RELEASE_").toIntOrNull() ?: error("Invalid source version: ${delegate.sourceVersion}") override fun findTypeElement(qName: String): JavacTypeElement? { return typeElementStore[qName] } override fun getTypeElementsFromPackage(packageName: String): List<XTypeElement> { // Note, to support Java Modules we would need to use "getAllPackageElements", // but that is only available in Java 9+. val packageElement = delegate.elementUtils.getPackageElement(packageName) ?: return emptyList() return packageElement.enclosedElements .filterIsInstance<TypeElement>() .map { wrapTypeElement(it) } } override fun findType(qName: String): XType? { // check for primitives first PRIMITIVE_TYPES[qName]?.let { return wrap( typeMirror = typeUtils.getPrimitiveType(it), kotlinType = null, elementNullability = XNullability.NONNULL ) } // check no types, such as 'void' NO_TYPES[qName]?.let { return wrap( typeMirror = typeUtils.getNoType(it), kotlinType = null, elementNullability = XNullability.NONNULL ) } return findTypeElement(qName)?.type } override fun findGeneratedAnnotation(): XTypeElement? { val element = GeneratedAnnotations.generatedAnnotation(elementUtils, delegate.sourceVersion) return if (element.isPresent) { wrapTypeElement(element.get()) } else { null } } override fun getArrayType(type: XType): JavacArrayType { check(type is JavacType) { "given type must be from java, $type is not" } return JavacArrayType( env = this, typeMirror = typeUtils.getArrayType(type.typeMirror), nullability = XNullability.UNKNOWN, knownComponentNullability = type.nullability ) } override fun getDeclaredType(type: XTypeElement, vararg types: XType): JavacType { check(type is JavacTypeElement) val args = types.map { check(it is JavacType) it.typeMirror }.toTypedArray() return wrap<JavacDeclaredType>( typeMirror = typeUtils.getDeclaredType(type.element, *args), // type elements cannot have nullability hence we don't synthesize anything here kotlinType = null, elementNullability = type.element.nullability ) } override fun getWildcardType(consumerSuper: XType?, producerExtends: XType?): XType { check(consumerSuper == null || producerExtends == null) { "Cannot supply both super and extends bounds." } return wrap( typeMirror = typeUtils.getWildcardType( (producerExtends as? JavacType)?.typeMirror, (consumerSuper as? JavacType)?.typeMirror, ), kotlinType = null, elementNullability = null ) } fun wrapTypeElement(element: TypeElement) = typeElementStore[element] /** * Wraps the given java processing type into an XType. * * @param typeMirror TypeMirror from java processor * @param kotlinType If the type is derived from a kotlin source code, the KmType information * parsed from kotlin metadata * @param elementNullability The nullability information parsed from the code. This value is * ignored if [kotlinType] is provided. */ inline fun <reified T : JavacType> wrap( typeMirror: TypeMirror, kotlinType: KmType?, elementNullability: XNullability? ): T { return when (typeMirror.kind) { TypeKind.ARRAY -> when { kotlinType != null -> { JavacArrayType( env = this, typeMirror = MoreTypes.asArray(typeMirror), kotlinType = kotlinType ) } elementNullability != null -> { JavacArrayType( env = this, typeMirror = MoreTypes.asArray(typeMirror), nullability = elementNullability, knownComponentNullability = null ) } else -> { JavacArrayType( env = this, typeMirror = MoreTypes.asArray(typeMirror), ) } } TypeKind.DECLARED -> when { kotlinType != null -> { JavacDeclaredType( env = this, typeMirror = MoreTypes.asDeclared(typeMirror), kotlinType = kotlinType ) } elementNullability != null -> { JavacDeclaredType( env = this, typeMirror = MoreTypes.asDeclared(typeMirror), nullability = elementNullability ) } else -> { JavacDeclaredType( env = this, typeMirror = MoreTypes.asDeclared(typeMirror) ) } } else -> when { kotlinType != null -> { DefaultJavacType( env = this, typeMirror = typeMirror, kotlinType = kotlinType ) } elementNullability != null -> { DefaultJavacType( env = this, typeMirror = typeMirror, nullability = elementNullability ) } else -> { DefaultJavacType( env = this, typeMirror = typeMirror ) } } } as T } internal fun wrapAnnotatedElement( element: Element, annotationName: String ): XElement { return when (element) { is VariableElement -> { wrapVariableElement(element) } is TypeElement -> { wrapTypeElement(element) } is ExecutableElement -> { wrapExecutableElement(element) } is PackageElement -> { error( "Cannot get elements with annotation $annotationName. Package " + "elements are not supported by XProcessing." ) } else -> error("Unsupported element $element with annotation $annotationName") } } fun wrapExecutableElement(element: ExecutableElement): JavacExecutableElement { return when (element.kind) { ElementKind.CONSTRUCTOR -> { JavacConstructorElement( env = this, element = element ) } ElementKind.METHOD -> { JavacMethodElement( env = this, element = element ) } else -> error("Unsupported kind ${element.kind} of executable element $element") } } fun wrapVariableElement(element: VariableElement): JavacVariableElement { return when (val enclosingElement = element.enclosingElement) { is ExecutableElement -> { val executableElement = wrapExecutableElement(enclosingElement) executableElement.parameters.find { param -> param.element.simpleName == element.simpleName } ?: error("Unable to create variable element for $element") } is TypeElement -> JavacFieldElement(this, element) else -> error("Unsupported enclosing type $enclosingElement for $element") } } internal fun clearCache() { typeElementStore.clear() } companion object { val PRIMITIVE_TYPES = TypeKind.values().filter { it.isPrimitive }.associateBy { it.name.lowercase(Locale.US) } val NO_TYPES = listOf( TypeKind.VOID, TypeKind.NONE ).associateBy { it.name.lowercase(Locale.US) } } }
apache-2.0
7df68071fc90aad803ddfcc73bc16812
35.748466
100
0.555342
5.939514
false
false
false
false
GunoH/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/PackageOperations.kt
7
1816
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageOperationType import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion import kotlinx.coroutines.Deferred internal data class PackageOperations( val targetModules: TargetModules, val primaryOperations: Deferred<List<PackageSearchOperation<*>>>, val removeOperations: Deferred<List<PackageSearchOperation<*>>>, val targetVersion: NormalizedPackageVersion<*>?, val primaryOperationType: PackageOperationType?, val repoToAddWhenInstalling: RepositoryModel? ) { val canInstallPackage = primaryOperationType == PackageOperationType.INSTALL val canUpgradePackage = primaryOperationType == PackageOperationType.UPGRADE val canSetPackage = primaryOperationType == PackageOperationType.SET }
apache-2.0
54f395b6e5ddfd98c3a42d83eb1f7d67
49.444444
105
0.730176
5.341176
false
false
false
false
GunoH/intellij-community
plugins/devkit/devkit-kotlin-tests/testData/inspections/useJBColor/UseJBColorConstant.kt
2
1161
import com.intellij.ui.JBColor import java.awt.Color import java.awt.Color.GREEN class UseJBColorConstant { companion object { private val COLOR_CONSTANT = <warning descr="'java.awt.Color' used instead of 'JBColor'">Color.BLUE</warning> private val COLOR_CONSTANT_STATIC_IMPORT = <warning descr="'java.awt.Color' used instead of 'JBColor'">GREEN</warning> private val JB_COLOR_CONSTANT: Color = JBColor(Color.DARK_GRAY, Color.LIGHT_GRAY) // correct usage private val JB_COLOR_CONSTANT_STATIC_IMPORT: Color = JBColor(GREEN, GREEN) // correct usage } fun any() { @Suppress("UNUSED_VARIABLE") val myColor = <warning descr="'java.awt.Color' used instead of 'JBColor'">Color.BLUE</warning> takeColor(<warning descr="'java.awt.Color' used instead of 'JBColor'">Color.green</warning>) takeColor(<warning descr="'java.awt.Color' used instead of 'JBColor'">GREEN</warning>) // correct cases: @Suppress("UNUSED_VARIABLE") val myGreen: Color = JBColor(Color.white, Color.YELLOW) takeColor(JBColor(Color.BLACK, Color.WHITE)) } fun takeColor(@Suppress("UNUSED_PARAMETER") color: Color) { // do nothing } }
apache-2.0
9ca94ac423f6b29e5d334cfd19c50d64
40.464286
122
0.711456
3.831683
false
false
false
false