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
abdodaoud/Merlin
app/src/main/java/com/abdodaoud/merlin/data/db/DbClasses.kt
1
745
package com.abdodaoud.merlin.data.db import java.util.* import kotlin.properties.getValue import kotlin.properties.setValue class MainFacts(val map: MutableMap<String, Any?>, val dailyFact: List<DayFact>) { var _id: Long by map constructor(id: Long, dailyFact: List<DayFact>) : this(HashMap(), dailyFact) { this._id = id } } class DayFact(var map: MutableMap<String, Any?>) { var _id: Long by map var factsId: Long by map var date: Long by map var title: String by map var url: String by map constructor(factsId: Long, date: Long, title: String, url: String) : this(HashMap()) { this.factsId = factsId this.date = date this.title = title this.url = url } }
mit
1fcabf124f9cc73c6c7faf7a0d8c6245
24.724138
82
0.648322
3.530806
false
false
false
false
http4k/http4k
http4k-core/src/main/kotlin/org/http4k/filter/cookie/clientCookies.kt
1
1602
package org.http4k.filter.cookie import org.http4k.core.cookie.Cookie import java.time.Duration import java.time.Instant import java.time.LocalDateTime import java.time.ZoneOffset import java.util.concurrent.ConcurrentHashMap data class LocalCookie(val cookie: Cookie, private val created: Instant) { @Deprecated("use main constructor", ReplaceWith("LocalCookie(cookie, created.toInstant(java.time.ZoneOffset.UTC))")) constructor(cookie: Cookie, created: LocalDateTime) : this(cookie, created.toInstant(ZoneOffset.UTC)) @Deprecated("use instant version", ReplaceWith("isExpired(now.toInstant(java.time.ZoneOffset.UTC))")) fun isExpired(now: LocalDateTime) = isExpired(now.toInstant(java.time.ZoneOffset.UTC)) fun isExpired(now: Instant) = (cookie.maxAge ?.let { maxAge -> Duration.between(created, now).seconds >= maxAge } ?: cookie.expires?.let { expires -> Duration.between(created, now).seconds > Duration.between( created, expires ).seconds }) == true } interface CookieStorage { fun store(cookies: List<LocalCookie>) fun remove(name: String) fun retrieve(): List<LocalCookie> } class BasicCookieStorage : CookieStorage { private val storage = ConcurrentHashMap<String, LocalCookie>() override fun store(cookies: List<LocalCookie>) = cookies.forEach { storage[it.cookie.name] = it } override fun retrieve(): List<LocalCookie> = storage.values.toList() override fun remove(name: String) { storage.remove(name) } }
apache-2.0
1bfa95c54394f07af703791432a60eab
35.409091
120
0.691635
4.353261
false
false
false
false
Bodo1981/swapi.co
app/src/main/java/com/christianbahl/swapico/AppModule.kt
1
2088
package com.christianbahl.swapico import android.app.Application import android.content.Context import com.christianbahl.swapico.api.SwapiApi import com.squareup.okhttp.Cache import com.squareup.okhttp.OkHttpClient import com.squareup.okhttp.logging.HttpLoggingInterceptor import dagger.Module import dagger.Provides import retrofit.GsonConverterFactory import retrofit.Retrofit import retrofit.RxJavaCallAdapterFactory import java.io.File import java.util.concurrent.TimeUnit import javax.inject.Singleton /** * @author Christian Bahl */ @Module class AppModule(private val application: Application) { companion object { val HTTP_RESPONSE_DISK_CACHE_MAX_SIZE: Long = 10 * 1024 * 1024 val DEFAULT_CONNECT_TIMEOUT_MILLIS: Long = 15 * 1000 val DEFAULT_READ_TIMEOUT_MILLIS: Long = 20 * 1000 val DEFAULT_WRITE_TIMEOUT_MILLIS: Long = 20 * 1000 } @Provides @Singleton fun provideApplicationContext() = application @Provides @Singleton fun provideContext(): Context = application @Provides @Singleton fun provideSwapiApi(okHttpClient: OkHttpClient) = Retrofit.Builder().baseUrl("http://swapi.co/api/").addConverterFactory( GsonConverterFactory.create()).addCallAdapterFactory( RxJavaCallAdapterFactory.create()).client(okHttpClient).build().create(SwapiApi::class.java) @Provides @Singleton fun provideOkHttpClient(context: Context): OkHttpClient { val logging = HttpLoggingInterceptor() logging.setLevel(HttpLoggingInterceptor.Level.BODY) val okHttpClient = OkHttpClient() okHttpClient.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); okHttpClient.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); okHttpClient.setWriteTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); okHttpClient.interceptors().add(logging) val baseDir = context.cacheDir; if (baseDir != null) { val cacheDir = File(baseDir, "HttpResponseCache") okHttpClient.setCache(Cache(cacheDir, HTTP_RESPONSE_DISK_CACHE_MAX_SIZE)) } return okHttpClient; } }
apache-2.0
42d10277b4b97a203d599deed3d76359
35.649123
102
0.772989
4.660714
false
false
false
false
mikegehard/kotlinExercisesForProgrammers
src/main/com/github/mikegehard/roomSize.kt
1
675
package com.github.mikegehard import java.math.BigDecimal import java.math.MathContext fun main(args: Array<String>) { val sqFeetToSqMeters = 0.09290304 // This will get you 5 digits, not always 3 decimal places. val precision = 5 val length = getNumber("What is the length of room in feet?") val width = getNumber("What is the width of room in feet?") val areaFeet = length * width val areaMeters = BigDecimal(areaFeet * sqFeetToSqMeters).round(MathContext(precision)) println("You entered dimensions of $length by $width feet.") println("The area is:") println("$areaFeet square feet") println("$areaMeters square meters") }
mit
919e489e5a58afe68d0abcb6aff81d96
32.75
90
0.711111
3.970588
false
false
false
false
alashow/music-android
modules/data/src/main/java/tm/alashow/datmusic/data/db/AppDatabase.kt
1
1664
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.data.db import androidx.room.AutoMigration import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import tm.alashow.data.db.BaseTypeConverters import tm.alashow.datmusic.data.db.daos.AlbumsDao import tm.alashow.datmusic.data.db.daos.ArtistsDao import tm.alashow.datmusic.data.db.daos.AudiosDao import tm.alashow.datmusic.data.db.daos.DownloadRequestsDao import tm.alashow.datmusic.data.db.daos.PlaylistsDao import tm.alashow.datmusic.data.db.daos.PlaylistsWithAudiosDao import tm.alashow.datmusic.domain.entities.Album import tm.alashow.datmusic.domain.entities.Artist import tm.alashow.datmusic.domain.entities.Audio import tm.alashow.datmusic.domain.entities.DownloadRequest import tm.alashow.datmusic.domain.entities.Playlist import tm.alashow.datmusic.domain.entities.PlaylistAudio @Database( version = 3, entities = [ Audio::class, Artist::class, Album::class, DownloadRequest::class, Playlist::class, PlaylistAudio::class, ], autoMigrations = [ AutoMigration(from = 1, to = 2), AutoMigration(from = 2, to = 3), ] ) @TypeConverters(BaseTypeConverters::class, AppTypeConverters::class) abstract class AppDatabase : RoomDatabase() { abstract fun audiosDao(): AudiosDao abstract fun artistsDao(): ArtistsDao abstract fun albumsDao(): AlbumsDao abstract fun playlistsDao(): PlaylistsDao abstract fun playlistsWithAudiosDao(): PlaylistsWithAudiosDao abstract fun downloadRequestsDao(): DownloadRequestsDao }
apache-2.0
3ad80bef8dd00d387a0982985c457b9a
31.627451
68
0.763822
4.088452
false
false
false
false
langara/USpek
ktjunit5sample/src/test/kotlin/ConcurrentTest.kt
1
4447
package pl.mareklangiewicz.ktjvmsample import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestFactory import pl.mareklangiewicz.uspek.* import java.util.Locale /** micro debugging ;-) */ private fun ud(s: String) = println("ud [${Thread.currentThread().name.padEnd(40).substring(0, 40)}] [${getCurrentTimeString()}] $s") private val ud get() = ud("") private fun getCurrentTimeString() = System.currentTimeMillis().let { String.format(Locale.US, "%tT:%tL", it, it) } private const val maxLoopShort = 9000 private const val maxLoopLong = 50_000_000 class ConcurrentTest { @Test fun tests_sequential_slowly() = runBlocking(Dispatchers.Default) { uspekLog = { } ud("start") val d1 = suspekAsync { checkAddSlowly(1, 1, 9000); ud("in1") }; ud("out1"); d1.await(); ud("after1") val d2 = suspekAsync { checkAddSlowly(2, 1, 9000); ud("in2") }; ud("out2"); d2.await(); ud("after2") ud("end") } @Test fun tests_concurrent_slowly() = runBlocking(Dispatchers.Default) { uspekLog = { } ud("start") val d1 = suspekAsync { checkAddSlowly(1, 1, maxLoopShort); ud("in1") }; ud("out1") val d2 = suspekAsync { checkAddSlowly(2, 1, maxLoopShort); ud("in2") }; ud("out2") d1.await(); ud("after1") d2.await(); ud("after2") ud("end") } @Test fun tests_simple_massively() { suspekBlocking { ud("start") checkAddFaster(100, 199, 1, maxLoopLong); ud("1") checkAddFaster(200, 299, 1, maxLoopLong); ud("2") checkAddFaster(300, 399, 1, maxLoopLong); ud("3") checkAddFaster(400, 499, 1, maxLoopLong); ud("4") ud("end") } } @Test fun tests_sequential_massively() = runBlocking(Dispatchers.Default) { ud("start") val d1 = suspekAsync { checkAddFaster(100, 199, 1, maxLoopLong); ud("in1") }; ud("out1"); d1.await(); ud("after1") val d2 = suspekAsync { checkAddFaster(200, 299, 1, maxLoopLong); ud("in2") }; ud("out2"); d2.await(); ud("after2") val d3 = suspekAsync { checkAddFaster(300, 399, 1, maxLoopLong); ud("in3") }; ud("out3"); d3.await(); ud("after3") val d4 = suspekAsync { checkAddFaster(400, 499, 1, maxLoopLong); ud("in4") }; ud("out4"); d4.await(); ud("after4") ud("end") } @Test fun tests_concurrent_massively() = runBlocking(Dispatchers.Default) { ud("start") val d1 = suspekAsync { checkAddFaster(100, 199, 1, maxLoopLong); ud("in1") }; ud("out1") val d2 = suspekAsync { checkAddFaster(200, 299, 1, maxLoopLong); ud("in2") }; ud("out2") val d3 = suspekAsync { checkAddFaster(300, 399, 1, maxLoopLong); ud("in3") }; ud("out3") val d4 = suspekAsync { checkAddFaster(400, 499, 1, maxLoopLong); ud("in4") }; ud("out4") d1.await(); ud("after1") d2.await(); ud("after2") d3.await(); ud("after3") d4.await(); ud("after4") ud("end") } @TestFactory fun exampleFactory() = suspekTestFactory { checkAddSlowly(666, 10, 20) checkAddSlowly(999, 50, 60) } suspend fun checkAddSlowly(addArg: Int, resultFrom: Int, resultTo: Int) { "create SUT for adding $addArg + $resultFrom..$resultTo" so { val sut = MicroCalc(666) "check add $addArg" so { for (i in resultFrom..resultTo) { // generating tests in a loop is slow because it starts the loop // again and again just to find and run first not-finished test "check add $addArg to $i" so { sut.result = i sut.add(addArg) sut.result eq i + addArg // require(i < resultTo - 3) // this should fail three times } } } } } suspend fun checkAddFaster(addArgFrom: Int, addArgTo: Int, resultFrom: Int, resultTo: Int) { "create SUT and check add $addArgFrom .. $addArgTo" so { val sut = MicroCalc(666) for (addArg in addArgFrom..addArgTo) for (i in resultFrom..resultTo) { sut.result = i sut.add(addArg) sut.result eq i + addArg } // require(false) // enable to test failing } } }
apache-2.0
04e07849cdb5184a1ebc20b7ffeddc58
39.427273
122
0.573645
3.830319
false
true
false
false
rock3r/detekt
detekt-api/src/test/kotlin/io/gitlab/arturbosch/detekt/api/internal/YamlConfigSpec.kt
1
5220
package io.gitlab.arturbosch.detekt.api.internal import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.test.resource import io.gitlab.arturbosch.detekt.test.yamlConfig import org.assertj.core.api.Assertions import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatIllegalStateException import org.assertj.core.api.Assertions.fail import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.nio.file.Paths @Suppress("DEPRECATION") class YamlConfigSpec : Spek({ describe("load yaml config") { val config by memoized { yamlConfig("detekt.yml") } it("should create a sub config") { try { val subConfig = config.subConfig("style") assertThat(subConfig.valueOrDefault("WildcardImport", mapOf<String, Any>())).isNotEmpty assertThat(subConfig.valueOrDefault("WildcardImport", mapOf<String, Any>())["active"].toString()).isEqualTo("true") assertThat(subConfig.valueOrDefault("WildcardImport", mapOf<String, Any>())["active"] as Boolean).isTrue() assertThat(subConfig.valueOrDefault("NotFound", mapOf<String, Any>())).isEmpty() assertThat(subConfig.valueOrDefault("NotFound", "")).isEmpty() } catch (ignored: Config.InvalidConfigurationError) { fail("Creating a sub config should work for test resources config!") } } it("should create a sub sub config") { try { val subConfig = config.subConfig("style") val subSubConfig = subConfig.subConfig("WildcardImport") assertThat(subSubConfig.valueOrDefault("active", false)).isTrue() assertThat(subSubConfig.valueOrDefault("NotFound", true)).isTrue() } catch (ignored: Config.InvalidConfigurationError) { fail("Creating a sub config should work for test resources config!") } } it("tests wrong sub config conversion") { assertThatIllegalStateException().isThrownBy { @Suppress("UNUSED_VARIABLE") val ignored = config.valueOrDefault("style", "") }.withMessage("Value \"{WildcardImport={active=true}, NoElseInWhenExpression={active=true}, MagicNumber={active=true, ignoreNumbers=[-1, 0, 1, 2]}}\" set for config parameter \"style\" is not of required type String.") } } describe("loading empty configurations") { it("empty yaml file is equivalent to empty config") { YamlConfig.loadResource(javaClass.getResource("/empty.yml")) } it("single item in yaml file is valid") { YamlConfig.loadResource(javaClass.getResource("/oneitem.yml")) } } describe("meaningful error messages") { val config by memoized { yamlConfig("wrong-property-type.yml") } it("only accepts true and false boolean values") { assertThatIllegalStateException() .isThrownBy { config.valueOrDefault("bool", false) } .withMessage("""Value "fasle" set for config parameter "bool" is not of required type Boolean.""") } it("prints whole config-key path for NumberFormatException") { assertThatIllegalStateException().isThrownBy { config.subConfig("RuleSet") .subConfig("Rule") .valueOrDefault("threshold", 6) }.withMessage("Value \"v5.7\" set for config parameter \"RuleSet > Rule > threshold\" is not of required type Int.") } it("prints whole config-key path for ClassCastException") { assertThatIllegalStateException().isThrownBy { @Suppress("UNUSED_VARIABLE") val bool: Int = config.subConfig("RuleSet") .subConfig("Rule") .valueOrDefault("active", 1) }.withMessage("Value \"[]\" set for config parameter \"RuleSet > Rule > active\" is not of required type Int.") } } describe("yaml config") { it("loads the config from a given yaml file") { val path = Paths.get(resource("detekt.yml")) val config = YamlConfig.load(path) assertThat(config).isNotNull } it("loads the config from a given text file") { val path = Paths.get(resource("detekt.txt")) val config = YamlConfig.load(path) assertThat(config).isNotNull } it("throws an exception on an non-existing file") { val path = Paths.get("doesNotExist.yml") Assertions.assertThatIllegalArgumentException() .isThrownBy { YamlConfig.load(path) } .withMessageStartingWith("Configuration does not exist") } it("throws an exception on a directory") { val path = Paths.get(resource("/config_validation")) Assertions.assertThatIllegalArgumentException() .isThrownBy { YamlConfig.load(path) } .withMessageStartingWith("Configuration must be a file") } } })
apache-2.0
e81d3922ea72239f7587a0c3612064e6
42.5
230
0.621073
5.158103
false
true
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/InitialActivity.kt
1
5084
/* * Copyright (c) 2021 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.Context import android.content.SharedPreferences import androidx.annotation.CheckResult import androidx.core.content.edit import com.ichi2.anki.servicelayer.PreferenceUpgradeService import com.ichi2.anki.servicelayer.PreferenceUpgradeService.setPreferencesUpToDate import com.ichi2.utils.VersionUtils.pkgVersionName import timber.log.Timber /** Utilities for launching the first activity (currently the DeckPicker) */ object InitialActivity { /** Returns null on success */ @CheckResult fun getStartupFailureType(context: Context): StartupFailure? { // A WebView failure means that we skip `AnkiDroidApp`, and therefore haven't loaded the collection if (AnkiDroidApp.webViewFailedToLoad()) { return StartupFailure.WEBVIEW_FAILED } // If we're OK, return null if (CollectionHelper.instance.getColSafe(context, reportException = false) != null) { return null } if (!AnkiDroidApp.isSdCardMounted) { return StartupFailure.SD_CARD_NOT_MOUNTED } else if (!CollectionHelper.isCurrentAnkiDroidDirAccessible(context)) { return StartupFailure.DIRECTORY_NOT_ACCESSIBLE } return when (CollectionHelper.lastOpenFailure) { CollectionHelper.CollectionOpenFailure.FILE_TOO_NEW -> StartupFailure.FUTURE_ANKIDROID_VERSION CollectionHelper.CollectionOpenFailure.CORRUPT -> StartupFailure.DB_ERROR CollectionHelper.CollectionOpenFailure.LOCKED -> StartupFailure.DATABASE_LOCKED null -> { // if getColSafe returned null, this should never happen null } } } /** @return Whether any preferences were upgraded */ fun upgradePreferences(context: Context?, previousVersionCode: Long): Boolean { return PreferenceUpgradeService.upgradePreferences(context, previousVersionCode) } /** * @return Whether a fresh install occurred and a "fresh install" setup for preferences was performed * This only refers to a fresh install from the preferences perspective, not from the Anki data perspective. * * NOTE: A user can wipe app data, which will mean this returns true WITHOUT deleting their collection. * The above note will need to be reevaluated after scoped storage migration takes place * * * On the other hand, restoring an app backup can cause this to return true before the Anki collection is created * in practice, this doesn't occur due to CollectionHelper.getCol creating a new collection, and it's called before * this in the startup script */ @CheckResult fun performSetupFromFreshInstallOrClearedPreferences(preferences: SharedPreferences): Boolean { if (!wasFreshInstall(preferences)) { Timber.d("Not a fresh install [preferences]") return false } Timber.i("Fresh install") setPreferencesUpToDate(preferences) setUpgradedToLatestVersion(preferences) return true } /** * true if the app was launched the first time * false if the app was launched for the second time after a successful initialisation * false if the app was launched after an update */ fun wasFreshInstall(preferences: SharedPreferences) = "" == preferences.getString("lastVersion", "") /** Sets the preference stating that the latest version has been applied */ fun setUpgradedToLatestVersion(preferences: SharedPreferences) { Timber.i("Marked prefs as upgraded to latest version: %s", pkgVersionName) preferences.edit { putString("lastVersion", pkgVersionName) } } /** @return false: The app has been upgraded since the last launch OR the app was launched for the first time. * Implementation detail: * This is not called in the case of performSetupFromFreshInstall returning true. * So this should not use the default value */ fun isLatestVersion(preferences: SharedPreferences): Boolean { return preferences.getString("lastVersion", "") == pkgVersionName } enum class StartupFailure { SD_CARD_NOT_MOUNTED, DIRECTORY_NOT_ACCESSIBLE, FUTURE_ANKIDROID_VERSION, DB_ERROR, DATABASE_LOCKED, WEBVIEW_FAILED } }
gpl-3.0
f051c3eb21a93c38d62bf9b19e6b3f07
42.452991
119
0.708497
4.907336
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/libanki/Media.kt
1
38157
/**************************************************************************************** * Copyright (c) 2011 Kostas Spyropoulos <[email protected]> * * Copyright (c) 2014 Houssam Salem <[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.libanki import android.database.SQLException import android.net.Uri import android.text.TextUtils import com.ichi2.anki.CrashReportService import com.ichi2.libanki.exception.EmptyMediaException import com.ichi2.libanki.template.TemplateFilters import com.ichi2.utils.* import com.ichi2.utils.HashUtil.HashMapInit import org.json.JSONArray import org.json.JSONObject import timber.log.Timber import java.io.* import java.util.* import java.util.regex.Matcher import java.util.regex.Pattern import java.util.zip.ZipEntry import java.util.zip.ZipFile import java.util.zip.ZipOutputStream import kotlin.math.min /** * Media manager - handles the addition and removal of media files from the media directory (collection.media) and * maintains the media database (collection.media.ad.db2) which is used to determine the state of files for syncing. * Note that the media database has an additional prefix for AnkiDroid (.ad) to avoid any potential issues caused by * users copying the file to the desktop client and vice versa. * * * Unlike the python version of this module, we do not (and cannot) modify the current working directory (CWD) before * performing operations on media files. In python, the CWD is changed to the media directory, allowing it to easily * refer to the files in the media directory by name only. In Java, we must be cautious about when to specify the full * path to the file and when we need to use the filename only. In general, when we refer to a file on disk (i.e., * creating a new File() object), we must include the full path. Use the dir() method to make this step easier. * * E.g: new File(dir(), "filename.jpg") */ @KotlinCleanup("IDE Lint") open class Media(private val col: Collection, server: Boolean) { private var mDir: String? /** * Used by unit tests only. */ @KotlinCleanup("non-null + exception if used after .close()") var db: DB? = null private set open fun connect() { if (col.server) { return } // NOTE: We use a custom prefix for AnkiDroid to avoid issues caused by copying // the db to the desktop or vice versa. val path = dir() + ".ad.db2" val dbFile = File(path) val create = !dbFile.exists() db = DB.withAndroidFramework(col.context, path) if (create) { _initDB() } maybeUpgrade() } fun _initDB() { val sql = """create table media ( fname text not null primary key, csum text, -- null indicates deleted file mtime int not null, -- zero if deleted dirty int not null ); create index idx_media_dirty on media (dirty); create table meta (dirMod int, lastUsn int); insert into meta values (0, 0);""" db!!.executeScript(sql) } private fun maybeUpgrade() { val oldPath = dir() + ".db" val oldDbFile = File(oldPath) if (oldDbFile.exists()) { db!!.execute(String.format(Locale.US, "attach \"%s\" as old", oldPath)) try { val sql = """insert into media select m.fname, csum, mod, ifnull((select 1 from log l2 where l2.fname=m.fname), 0) as dirty from old.media m left outer join old.log l using (fname) union select fname, null, 0, 1 from old.log where type=${Consts.CARD_TYPE_LRN};""" db!!.apply { execute(sql) execute("delete from meta") execute("insert into meta select dirMod, usn from old.meta") commit() } } catch (e: Exception) { // if we couldn't import the old db for some reason, just start anew val sw = StringWriter() e.printStackTrace(PrintWriter(sw)) col.log("failed to import old media db:$sw") } db!!.execute("detach old") val newDbFile = File("$oldPath.old") if (newDbFile.exists()) { newDbFile.delete() } oldDbFile.renameTo(newDbFile) } } open fun close() { if (col.server) { return } db!!.close() db = null } private fun _deleteDB() { val path = db!!.path close() File(path).delete() connect() } @KotlinCleanup("nullable if server == true, we don't do this in AnkiDroid so should be fine") fun dir(): String = mDir!! /* Adding media *********************************************************** */ /** * In AnkiDroid, adding a media file will not only copy it to the media directory, but will also insert an entry * into the media database marking it as a new addition. */ @Throws(IOException::class, EmptyMediaException::class) @KotlinCleanup("scope function: fname") fun addFile(oFile: File?): String { if (oFile == null || oFile.length() == 0L) { throw EmptyMediaException() } val fname = writeData(oFile) markFileAdd(fname) return fname } /** * Copy a file to the media directory and return the filename it was stored as. * * * Unlike the python version of this method, we don't read the file into memory as a string. All our operations are * done on streams opened on the file, so there is no second parameter for the string object here. */ @Throws(IOException::class) private fun writeData(oFile: File): String { // get the file name var fname = oFile.name // make sure we write it in NFC form and return an NFC-encoded reference fname = Utils.nfcNormalized(fname) // ensure it's a valid filename val base = cleanFilename(fname) val split = Utils.splitFilename(base) var root = split[0] val ext = split[1] // find the first available name val csum = Utils.fileChecksum(oFile) while (true) { fname = root + ext val path = File(dir(), fname) // if it doesn't exist, copy it directly if (!path.exists()) { Utils.copyFile(oFile, path) return fname } // if it's identical, reuse if (Utils.fileChecksum(path) == csum) { return fname } // otherwise, increment the checksum in the filename root = "$root-$csum" } } /** * Extract media filenames from an HTML string. * * @param string The string to scan for media filenames ([sound:...] or <img...>). * @param includeRemote If true will also include external http/https/ftp urls. * @return A list containing all the sound and image filenames found in the input string. */ /** * String manipulation * *********************************************************** */ fun filesInStr(mid: Long?, string: String, includeRemote: Boolean = false): List<String> { val l: MutableList<String> = ArrayList() val model = col.models.get(mid!!) var strings: MutableList<String?> = ArrayList() if (model!!.isCloze && string.contains("{{c")) { // if the field has clozes in it, we'll need to expand the // possibilities so we can render latex strings = _expandClozes(string) } else { strings.add(string) } for (s in strings) { @Suppress("NAME_SHADOWING") var s = s // handle latex @KotlinCleanup("change to .map { }") val svg = model.optBoolean("latexsvg", false) s = LaTeX.mungeQA(s!!, col, svg) // extract filenames var m: Matcher for (p in REGEXPS) { // NOTE: python uses the named group 'fname'. Java doesn't have named groups, so we have to determine // the index based on which pattern we are using val fnameIdx = if (p == fSoundRegexps) 2 else if (p == fImgAudioRegExpU) 2 else 3 m = p.matcher(s) while (m.find()) { val fname = m.group(fnameIdx)!! val isLocal = !fRemotePattern.matcher(fname.lowercase(Locale.getDefault())).find() if (isLocal || includeRemote) { l.add(fname) } } } } return l } private fun _expandClozes(string: String): MutableList<String?> { val ords: MutableSet<String> = TreeSet() var m = // In Android, } should be escaped Pattern.compile("\\{\\{c(\\d+)::.+?\\}\\}").matcher(string) while (m.find()) { ords.add(m.group(1)!!) } val strings = ArrayList<String?>(ords.size + 1) val clozeReg = TemplateFilters.CLOZE_REG for (ord in ords) { val buf = StringBuffer() m = Pattern.compile(String.format(Locale.US, clozeReg, ord)).matcher(string) while (m.find()) { if (!TextUtils.isEmpty(m.group(4))) { m.appendReplacement(buf, "[$4]") } else { m.appendReplacement(buf, TemplateFilters.CLOZE_DELETION_REPLACEMENT) } } m.appendTail(buf) val s = buf.toString().replace(String.format(Locale.US, clozeReg, ".+?").toRegex(), "$2") strings.add(s) } strings.add(string.replace(String.format(Locale.US, clozeReg, ".+?").toRegex(), "$2")) return strings } /** * Strips a string from media references. * * @param txt The string to be cleared of media references. * @return The media-free string. */ @KotlinCleanup("return early and remove var") fun strip(txt: String): String { @Suppress("NAME_SHADOWING") var txt = txt for (p in REGEXPS) { txt = p.matcher(txt).replaceAll("") } return txt } /* Rebuilding DB *********************************************************** */ /** * Finds missing, unused and invalid media files * * @return A list containing three lists of files (missingFiles, unusedFiles, invalidFiles) */ open fun check(): MediaCheckResult = check(null) private fun check(local: Array<File>?): MediaCheckResult { val mdir = File(dir()) // gather all media references in NFC form val allRefs: MutableSet<String> = HashSet() col.db.query("select id, mid, flds from notes").use { cur -> while (cur.moveToNext()) { val nid = cur.getLong(0) val mid = cur.getLong(1) val flds = cur.getString(2) var noteRefs = filesInStr(mid, flds) // check the refs are in NFC @KotlinCleanup("simplify with first {}") for (f in noteRefs) { // if they're not, we'll need to fix them first if (f != Utils.nfcNormalized(f)) { _normalizeNoteRefs(nid) noteRefs = filesInStr(mid, flds) break } } allRefs.addAll(noteRefs) } } // loop through media directory val unused: MutableList<String> = ArrayList() val invalid: List<String> = ArrayList() val files: Array<File> files = local ?: mdir.listFiles()!! var renamedFiles = false for (file in files) { @Suppress("NAME_SHADOWING") var file = file if (local == null) { if (file.isDirectory) { // ignore directories continue } } if (file.name.startsWith("_")) { // leading _ says to ignore file continue } val nfcFile = File(dir(), Utils.nfcNormalized(file.name)) // we enforce NFC fs encoding if (local == null) { if (file.name != nfcFile.name) { // delete if we already have the NFC form, otherwise rename renamedFiles = if (nfcFile.exists()) { file.delete() true } else { file.renameTo(nfcFile) true } file = nfcFile } } // compare if (!allRefs.contains(nfcFile.name)) { unused.add(file.name) } else { allRefs.remove(nfcFile.name) } } // if we renamed any files to nfc format, we must rerun the check // to make sure the renamed files are not marked as unused if (renamedFiles) { return check(local) } @KotlinCleanup(".filter { }") val noHave: MutableList<String> = ArrayList() for (x in allRefs) { if (!x.startsWith("_")) { noHave.add(x) } } // make sure the media DB is valid try { findChanges() } catch (ignored: SQLException) { Timber.w(ignored) _deleteDB() } return MediaCheckResult(noHave, unused, invalid) } private fun _normalizeNoteRefs(nid: Long) { val note = col.getNote(nid) val flds = note.fields @KotlinCleanup("improve") for (c in flds.indices) { val fld = flds[c] val nfc = Utils.nfcNormalized(fld) if (nfc != fld) { note.setField(c, nfc) } } note.flush() } /** * Copying on import * *********************************************************** */ open fun have(fname: String): Boolean = File(dir(), fname).exists() /** * Illegal characters and paths * *********************************************************** */ fun stripIllegal(str: String): String = fIllegalCharReg.matcher(str).replaceAll("") fun hasIllegal(str: String): Boolean = fIllegalCharReg.matcher(str).find() @KotlinCleanup("fix reassignment") fun cleanFilename(fname: String): String { @Suppress("NAME_SHADOWING") var fname = fname fname = stripIllegal(fname) fname = _cleanWin32Filename(fname) fname = _cleanLongFilename(fname) if ("" == fname) { fname = "renamed" } return fname } /** This method only change things on windows. So it's the * identity here. */ private fun _cleanWin32Filename(fname: String): String = fname @KotlinCleanup("Fix reassignment") private fun _cleanLongFilename(fname: String): String { /* a fairly safe limit that should work on typical windows paths and on eCryptfs partitions, even with a duplicate suffix appended */ @Suppress("NAME_SHADOWING") var fname = fname var nameMax = 136 val pathMax = 1024 // 240 for windows // cap nameMax based on absolute path val dirLen = fname.length // ideally, name should be normalized. Without access to nio.Paths library, it's hard to do it really correctly. This is still a better approximation than nothing. val remaining = pathMax - dirLen nameMax = min(remaining, nameMax) Assert.that( nameMax > 0, "The media directory is maximally long. There is no more length available for file name." ) if (fname.length > nameMax) { val lastSlash = fname.indexOf("/") val lastDot = fname.indexOf(".") if (lastDot == -1 || lastDot < lastSlash) { // no dot, or before last slash fname = fname.substring(0, nameMax) } else { val ext = fname.substring(lastDot + 1) var head = fname.substring(0, lastDot) val headMax = nameMax - ext.length head = head.substring(0, headMax) fname = head + ext Assert.that( fname.length <= nameMax, "The length of the file is greater than the maximal name value." ) } } return fname } /* Tracking changes *********************************************************** */ /** * Scan the media directory if it's changed, and note any changes. */ fun findChanges() { findChanges(false) } /** * @param force Unconditionally scan the media directory for changes (i.e., ignore differences in recorded and current * directory mod times). Use this when rebuilding the media database. */ open fun findChanges(force: Boolean) { if (force || _changed() != null) { _logChanges() } } fun haveDirty(): Boolean = db!!.queryScalar("select 1 from media where dirty=1 limit 1") > 0 /** * Returns the number of seconds from epoch since the last modification to the file in path. Important: this method * does not automatically append the root media directory to the path; the FULL path of the file must be specified. * * @param path The path to the file we are checking. path can be a file or a directory. * @return The number of seconds (rounded down). */ private fun _mtime(path: String): Long = File(path).lastModified() / 1000 private fun _checksum(path: String): String = Utils.fileChecksum(path) /** * Return dir mtime if it has changed since the last findChanges() * Doesn't track edits, but user can add or remove a file to update * * @return The modification time of the media directory if it has changed since the last call of findChanges(). If * it hasn't, it returns null. */ fun _changed(): Long? { val mod = db!!.queryLongScalar("select dirMod from meta") val mtime = _mtime(dir()) return if (mod != 0L && mod == mtime) { null } else mtime } @KotlinCleanup("destructure directly val (added, removed) = _changes()") private fun _logChanges() { val result = _changes() val added = result.first val removed = result.second val media = ArrayList<Array<Any?>>(added.size + removed.size) for (f in added) { val path = File(dir(), f).absolutePath val mt = _mtime(path) media.add(arrayOf(f, _checksum(path), mt, 1)) } for (f in removed) { media.add(arrayOf(f, null, 0, 1)) } // update media db db!!.apply { executeMany("insert or replace into media values (?,?,?,?)", media) execute("update meta set dirMod = ?", _mtime(dir())) commit() } } private fun _changes(): Pair<List<String>, List<String>> { val cache: MutableMap<String, Array<Any>> = HashMapInit( db!!.queryScalar("SELECT count() FROM media WHERE csum IS NOT NULL") ) try { db!!.query("select fname, csum, mtime from media where csum is not null").use { cur -> while (cur.moveToNext()) { val name = cur.getString(0) val csum = cur.getString(1) val mod = cur.getLong(2) cache[name] = arrayOf(csum, mod, false) } } } catch (e: SQLException) { throw RuntimeException(e) } val added: MutableList<String> = ArrayList() val removed: MutableList<String> = ArrayList() // loop through on-disk files for (f in File(dir()).listFiles()!!) { // ignore directories and thumbs.db if (f.isDirectory) { continue } val fname = f.name if ("thumbs.db".equals(fname, ignoreCase = true)) { continue } // and files with invalid chars if (hasIllegal(fname)) { continue } // empty files are invalid; clean them up and continue val sz = f.length() if (sz == 0L) { f.delete() continue } if (sz > 100 * 1024 * 1024) { col.log("ignoring file over 100MB", f) continue } // check encoding val normf = Utils.nfcNormalized(fname) if (fname != normf) { // wrong filename encoding which will cause sync errors val nf = File(dir(), normf) if (nf.exists()) { f.delete() } else { f.renameTo(nf) } } // newly added? if (!cache.containsKey(fname)) { added.add(fname) } else { // modified since last time? if (_mtime(f.absolutePath) != cache[fname]!![1] as Long) { // and has different checksum? if (_checksum(f.absolutePath) != cache[fname]!![0]) { added.add(fname) } } // mark as used cache[fname]!![2] = true } } // look for any entries in the cache that no longer exist on disk for ((key, value) in cache) { if (!(value[2] as Boolean)) { removed.add(key) } } return Pair(added, removed) } /** * Syncing related * *********************************************************** */ fun lastUsn(): Int = db!!.queryScalar("select lastUsn from meta") fun setLastUsn(usn: Int) { db!!.execute("update meta set lastUsn = ?", usn) db!!.commit() } fun syncInfo(fname: String?): Pair<String?, Int> { db!!.query("select csum, dirty from media where fname=?", fname!!).use { cur -> return if (cur.moveToNext()) { val csum = cur.getString(0) val dirty = cur.getInt(1) Pair(csum, dirty) } else { Pair(null, 0) } } } fun markClean(fnames: List<String?>) { for (fname in fnames) { db!!.execute("update media set dirty=0 where fname=?", fname!!) } } fun syncDelete(fname: String) { val f = File(dir(), fname) if (f.exists()) { f.delete() } db!!.execute("delete from media where fname=?", fname) } fun mediacount(): Int = db!!.queryScalar("select count() from media where csum is not null") fun dirtyCount(): Int = db!!.queryScalar("select count() from media where dirty=1") open fun forceResync() { db!!.apply { execute("delete from media") execute("update meta set lastUsn=0,dirMod=0") execute("vacuum") execute("analyze") commit() } } /* * Media syncing: zips * *********************************************************** */ /** * Unlike python, our temp zip file will be on disk instead of in memory. This avoids storing * potentially large files in memory which is not feasible with Android's limited heap space. * * * Notes: * * * - The maximum size of the changes zip is decided by the constant SYNC_ZIP_SIZE. If a media file exceeds this * limit, only that file (in full) will be zipped to be sent to the server. * * * - This method will be repeatedly called from MediaSyncer until there are no more files (marked "dirty" in the DB) * to send. * * * - Since AnkiDroid avoids scanning the media directory on every sync, it is possible for a file to be marked as a * new addition but actually have been deleted (e.g., with a file manager). In this case we skip over the file * and mark it as removed in the database. (This behaviour differs from the desktop client). * * */ fun mediaChangesZip(): Pair<File, List<String>> { val f = File(col.path.replaceFirst("collection\\.anki2$".toRegex(), "tmpSyncToServer.zip")) val fnames: MutableList<String> = ArrayList() try { ZipOutputStream(BufferedOutputStream(FileOutputStream(f))).use { z -> db!!.query( "select fname, csum from media where dirty=1 limit " + Consts.SYNC_MAX_FILES ).use { cur -> z.setMethod(ZipOutputStream.DEFLATED) // meta is a list of (fname, zipName), where zipName of null is a deleted file // NOTE: In python, meta is a list of tuples that then gets serialized into json and added // to the zip as a string. In our version, we use JSON objects from the start to avoid the // serialization step. Instead of a list of tuples, we use JSONArrays of JSONArrays. val meta = JSONArray() var sz = 0 val buffer = ByteArray(2048) var c = 0 while (cur.moveToNext()) { val fname = cur.getString(0) val csum = cur.getString(1) fnames.add(fname) val normName = Utils.nfcNormalized(fname) if (!TextUtils.isEmpty(csum)) { try { col.log("+media zip $fname") val file = File(dir(), fname) val bis = BufferedInputStream(FileInputStream(file), 2048) z.putNextEntry(ZipEntry(Integer.toString(c))) @KotlinCleanup("improve") var count: Int while (bis.read(buffer, 0, 2048).also { count = it } != -1) { z.write(buffer, 0, count) } z.closeEntry() bis.close() meta.put(JSONArray().put(normName).put(Integer.toString(c))) sz += file.length().toInt() } catch (e: FileNotFoundException) { Timber.w(e) // A file has been marked as added but no longer exists in the media directory. // Skip over it and mark it as removed in the db. removeFile(fname) } } else { col.log("-media zip $fname") meta.put(JSONArray().put(normName).put("")) } if (sz >= Consts.SYNC_MAX_BYTES) { break } c++ } z.putNextEntry(ZipEntry("_meta")) z.write(Utils.jsonToString(meta).toByteArray()) z.closeEntry() // Don't leave lingering temp files if the VM terminates. f.deleteOnExit() return Pair(f, fnames) } } } catch (e: IOException) { Timber.e(e, "Failed to create media changes zip: ") throw RuntimeException(e) } } /** * Extract zip data; return the number of files extracted. Unlike the python version, this method consumes a * ZipFile stored on disk instead of a String buffer. Holding the entire downloaded data in memory is not feasible * since some devices can have very limited heap space. * * This method closes the file before it returns. */ @Throws(IOException::class) fun addFilesFromZip(z: ZipFile): Int { return try { // get meta info first val meta = JSONObject(Utils.convertStreamToString(z.getInputStream(z.getEntry("_meta")))) // then loop through all files var cnt = 0 val zipEntries = Collections.list(z.entries()) val media: MutableList<Array<Any>> = ArrayList(zipEntries.size) for (i in zipEntries) { val fileName = i.name if ("_meta" == fileName) { // ignore previously-retrieved meta continue } var name = meta.getString(fileName) // normalize name for platform name = Utils.nfcNormalized(name) // save file val destPath = dir() + File.separator + name z.getInputStream(i) .use { zipInputStream -> Utils.writeToFile(zipInputStream, destPath) } val csum = Utils.fileChecksum(destPath) // update db media.add(arrayOf(name, csum, _mtime(destPath), 0)) cnt += 1 } if (!media.isEmpty()) { db!!.executeMany("insert or replace into media values (?,?,?,?)", media) } cnt } finally { z.close() } } /* * *********************************************************** * The methods below are not in LibAnki. * *********************************************************** */ /** * Add an entry into the media database for file named fname, or update it * if it already exists. */ open fun markFileAdd(fname: String) { Timber.d("Marking media file addition in media db: %s", fname) val path = File(dir(), fname).absolutePath db!!.execute( "insert or replace into media values (?,?,?,?)", fname, _checksum(path), _mtime(path), 1 ) } /** * Remove a file from the media directory if it exists and mark it as removed in the media database. */ open fun removeFile(fname: String) { val f = File(dir(), fname) if (f.exists()) { f.delete() } Timber.d("Marking media file removal in media db: %s", fname) db!!.execute( "insert or replace into media values (?,?,?,?)", fname, null, 0, 1 ) } /** * @return True if the media db has not been populated yet. */ fun needScan(): Boolean { val mod = db!!.queryLongScalar("select dirMod from meta") return mod == 0L } @Throws(IOException::class) open fun rebuildIfInvalid() { try { _changed() return } catch (e: Exception) { if (!ExceptionUtil.containsMessage(e, "no such table: meta")) { throw e } CrashReportService.sendExceptionReport(e, "media::rebuildIfInvalid") // TODO: We don't know the root cause of the missing meta table Timber.w(e, "Error accessing media database. Rebuilding") // continue below } // Delete and recreate the file db!!.database.close() val path = db!!.path Timber.i("Deleted %s", path) File(path).delete() db = DB.withAndroidFramework(col.context, path) _initDB() } companion object { // Upstream illegal chars defined on disallowed_char() // in https://github.com/ankitects/anki/blob/main/rslib/src/media/files.rs private val fIllegalCharReg = Pattern.compile("[\\[\\]><:\"/?*^\\\\|\\x00\\r\\n]") private val fRemotePattern = Pattern.compile("(https?|ftp)://") /* * A note about the regular expressions below: the python code uses named groups for the image and sound patterns. * Our version of Java doesn't support named groups, so we must use indexes instead. In the expressions below, the * group names (e.g., ?P<fname>) have been stripped and a comment placed above indicating the index of the group * name in the original. Refer to these indexes whenever the python code makes use of a named group. */ /** * Group 1 = Contents of [sound:] tag * Group 2 = "fname" */ // Regexes defined on https://github.com/ankitects/anki/blob/b403f20cae8fcdd7c3ff4c8d21766998e8efaba0/pylib/anki/media.py#L34-L45 private val fSoundRegexps = Pattern.compile("(?i)(\\[sound:([^]]+)])") // src element quoted case /** * Group 1 = Contents of `<img>|<audio>` tag * Group 2 = "str" * Group 3 = "fname" * Group 4 = Backreference to "str" (i.e., same type of quote character) */ private val fImgAudioRegExpQ = Pattern.compile("(?i)(<(?:img|audio)\\b[^>]* src=([\"'])([^>]+?)(\\2)[^>]*>)") private val fObjectRegExpQ = Pattern.compile("(?i)(<object\\b[^>]* data=([\"'])([^>]+?)(\\2)[^>]*>)") // unquoted case /** * Group 1 = Contents of `<img>|<audio>` tag * Group 2 = "fname" */ private val fImgAudioRegExpU = Pattern.compile("(?i)(<(?:img|audio)\\b[^>]* src=(?!['\"])([^ >]+)[^>]*?>)") private val fObjectRegExpU = Pattern.compile("(?i)(<object\\b[^>]* data=(?!['\"])([^ >]+)[^>]*?>)") val REGEXPS = listOf( fSoundRegexps, fImgAudioRegExpQ, fImgAudioRegExpU, fObjectRegExpQ, fObjectRegExpU ) fun getCollectionMediaPath(collectionPath: String): String { return collectionPath.replaceFirst("\\.anki2$".toRegex(), ".media") } /** * Percent-escape UTF-8 characters in local image filenames. * @param string The string to search for image references and escape the filenames. * @return The string with the filenames of any local images percent-escaped as UTF-8. */ @KotlinCleanup("fix 'string' as var") fun escapeImages(string: String, unescape: Boolean = false): String { @Suppress("NAME_SHADOWING") var string = string for (p in listOf(fImgAudioRegExpQ, fImgAudioRegExpU)) { val m = p.matcher(string) // NOTE: python uses the named group 'fname'. Java doesn't have named groups, so we have to determine // the index based on which pattern we are using val fnameIdx = if (p == fImgAudioRegExpU) 2 else 3 while (m.find()) { val tag = m.group(0)!! val fname = m.group(fnameIdx)!! if (fRemotePattern.matcher(fname).find()) { // don't do any escaping if remote image } else { string = if (unescape) { string.replace(tag, tag.replace(fname, Uri.decode(fname))) } else { string.replace(tag, tag.replace(fname, Uri.encode(fname, "/"))) } } } } return string } /** * Used by other classes to determine the index of a regular expression group named "fname" * (Anki2Importer needs this). This is needed because we didn't implement the "transformNames" * function and have delegated its job to the caller of this class. */ fun indexOfFname(p: Pattern): Int { return if (p == fSoundRegexps) 2 else if (p == fImgAudioRegExpU) 2 else 3 } } init { if (server) { mDir = null } else { // media directory mDir = getCollectionMediaPath(col.path) val fd = File(mDir!!) if (!fd.exists()) { if (!fd.mkdir()) { Timber.e("Cannot create media directory: %s", mDir) } } } } } data class MediaCheckResult(val noHave: List<String>, val unused: List<String>, val invalid: List<String>)
gpl-3.0
7d0eec93200b4749cd7d98edd3f78f96
38.015337
188
0.513877
4.731184
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/view/activity/AmountActivity.kt
1
7806
/* * Copyright (c) 2017. Toshi Inc * * 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.toshi.view.activity import android.app.Activity import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import com.toshi.R import com.toshi.crypto.util.TypeConverter import com.toshi.exception.CurrencyException import com.toshi.extensions.setActivityResultAndFinish import com.toshi.extensions.toast import com.toshi.util.CurrencyUtil import com.toshi.util.EthUtil import com.toshi.util.LocaleUtil import com.toshi.util.OnSingleClickListener import com.toshi.util.PaymentType import com.toshi.util.sharedPrefs.AppPrefs import com.toshi.view.adapter.AmountInputAdapter import com.toshi.viewModel.AmountViewModel import kotlinx.android.synthetic.main.activity_amount.amountInputView import kotlinx.android.synthetic.main.activity_amount.btnContinue import kotlinx.android.synthetic.main.activity_amount.closeButton import kotlinx.android.synthetic.main.activity_amount.ethValue import kotlinx.android.synthetic.main.activity_amount.localCurrencyCode import kotlinx.android.synthetic.main.activity_amount.localCurrencySymbol import kotlinx.android.synthetic.main.activity_amount.localValueView import kotlinx.android.synthetic.main.activity_amount.networkStatusView import kotlinx.android.synthetic.main.activity_amount.toolbarTitle import java.math.BigDecimal class AmountActivity : AppCompatActivity() { companion object { const val VIEW_TYPE = "type" const val INTENT_EXTRA__ETH_AMOUNT = "eth_amount" } private lateinit var viewModel: AmountViewModel private val separator by lazy { LocaleUtil.getDecimalFormatSymbols().monetaryDecimalSeparator } private val zero by lazy { LocaleUtil.getDecimalFormatSymbols().zeroDigit } private var encodedEthAmount: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_amount) init() } private fun init() { initViewModel() initToolbar() initClickListeners() initNetworkView() updateEthAmount() setCurrency() initObservers() } private fun initViewModel() { viewModel = ViewModelProviders.of(this).get(AmountViewModel::class.java) } private fun initToolbar() { val viewType = getViewTypeFromIntent() val title = if (viewType == PaymentType.TYPE_SEND) getString(R.string.send) else getString(R.string.request) toolbarTitle.text = title } private fun getViewTypeFromIntent() = intent.getIntExtra(AmountActivity.VIEW_TYPE, PaymentType.TYPE_SEND) private fun initClickListeners() { closeButton.setOnClickListener { finish() } btnContinue.setOnClickListener(continueClickListener) amountInputView.setOnAmountClickedListener(amountClickedListener) } private val continueClickListener = object : OnSingleClickListener() { override fun onSingleClick(v: View?) { setActivityResultAndFinish() } } private fun setActivityResultAndFinish() { encodedEthAmount?.let { setActivityResultAndFinish( Activity.RESULT_OK, { putExtra(INTENT_EXTRA__ETH_AMOUNT, encodedEthAmount) } ) } } private val amountClickedListener = object : AmountInputAdapter.OnKeyboardItemClicked { override fun onValueClicked(value: Char) { handleValueClicked(value) } override fun onBackSpaceClicked() { handleBackspaceClicked() } } private fun handleValueClicked(value: Char) { if (value == this.separator) handleSeparatorClicked() else updateValue(value) } private fun handleBackspaceClicked() { val currentLocalValue = localValueView.text.toString() val endIndex = Math.max(0, currentLocalValue.length - 1) val newLocalValue = currentLocalValue.substring(0, endIndex) val localValue = if (newLocalValue == zero.toString()) "" else newLocalValue localValueView.text = localValue updateEthAmount() } private fun initNetworkView() { networkStatusView.setNetworkVisibility(viewModel.getNetworks()) } private fun getLocalValueAsBigDecimal(): BigDecimal { val currentLocalValue = localValueView.text.toString() if (currentLocalValue.isEmpty() || currentLocalValue == this.separator.toString()) { return BigDecimal.ZERO } val parts = currentLocalValue.split(separator.toString()) val integerPart = if (parts.isEmpty()) currentLocalValue else parts[0] val fractionalPart = if (parts.size < 2) "0" else parts[1] val fullValue = integerPart + "." + fractionalPart val trimmedValue = if (fullValue.endsWith(".0")) fullValue.substring(0, fullValue.length - 2) else fullValue return BigDecimal(trimmedValue) } private fun handleSeparatorClicked() { val currentLocalValue = localValueView.text.toString() // Only allow a single decimal separator if (currentLocalValue.indexOf(separator) >= 0) return updateValue(separator) } private fun updateValue(value: Char) { appendValueInUi(value) updateEthAmount() } private fun appendValueInUi(value: Char) { val currentLocalValue = localValueView.text.toString() val isCurrentLocalValueEmpty = currentLocalValue.isEmpty() && value == zero if (currentLocalValue.length >= 10 || isCurrentLocalValueEmpty) return if (currentLocalValue.isEmpty() && value == separator) { val localValue = String.format("%s%s", zero.toString(), separator.toString()) localValueView.text = localValue return } val newLocalValue = currentLocalValue + value localValueView.text = newLocalValue } private fun updateEthAmount() { val localValue = getLocalValueAsBigDecimal() viewModel.getEthAmount(localValue) } private fun setCurrency() { try { val currency = AppPrefs.getCurrency() val currencyCode = CurrencyUtil.getCode(currency) val currencySymbol = CurrencyUtil.getSymbol(currency) localCurrencySymbol.text = currencySymbol localCurrencyCode.text = currencyCode } catch (e: CurrencyException) { toast(R.string.unsupported_currency_message) } } private fun initObservers() { viewModel.ethAmount.observe(this, Observer { ethAmount -> ethAmount ?.let { handleEth(it) } ?: toast(R.string.local_currency_to_eth_error) }) } private fun handleEth(ethAmount: BigDecimal) { ethValue.text = EthUtil.ethAmountToUserVisibleString(ethAmount) btnContinue.isEnabled = EthUtil.isLargeEnoughForSending(ethAmount) val weiAmount = EthUtil.ethToWei(ethAmount) encodedEthAmount = TypeConverter.toJsonHex(weiAmount) } }
gpl-3.0
bc4ab6aea9149db9f5eaac2d745c1f33
37.458128
116
0.705739
4.774312
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/provider/GamesIdPollsNameResultsProvider.kt
1
3054
package com.boardgamegeek.provider import android.content.ContentValues import android.content.Context import android.database.SQLException import android.database.sqlite.SQLiteDatabase import android.net.Uri import android.provider.BaseColumns import com.boardgamegeek.provider.BggContract.* import com.boardgamegeek.provider.BggContract.Companion.PATH_GAMES import com.boardgamegeek.provider.BggContract.Companion.PATH_POLLS import com.boardgamegeek.provider.BggContract.Companion.PATH_POLL_RESULTS import com.boardgamegeek.provider.BggContract.GamePollResults.Columns.POLL_ID import com.boardgamegeek.provider.BggContract.GamePolls import com.boardgamegeek.provider.BggDatabase.Tables import timber.log.Timber class GamesIdPollsNameResultsProvider : BaseProvider() { override fun getType(uri: Uri) = GamePollResults.CONTENT_TYPE override val path = "$PATH_GAMES/#/$PATH_POLLS/*/$PATH_POLL_RESULTS" override val defaultSortOrder = GamePollResults.DEFAULT_SORT override fun buildSimpleSelection(uri: Uri): SelectionBuilder { val gameId = Games.getGameId(uri) val pollName = Games.getPollName(uri) return SelectionBuilder() .table(Tables.GAME_POLL_RESULTS) .mapToTable(BaseColumns._ID, Tables.GAME_POLL_RESULTS) .where( "$POLL_ID = (SELECT ${Tables.GAME_POLLS}.${BaseColumns._ID} FROM ${Tables.GAME_POLLS} WHERE ${GamePolls.Columns.GAME_ID}=? AND ${GamePolls.Columns.POLL_NAME}=?)", gameId.toString(), pollName ) } override fun buildExpandedSelection(uri: Uri): SelectionBuilder { val gameId = Games.getGameId(uri) val pollName = Games.getPollName(uri) return SelectionBuilder().table(Tables.POLLS_JOIN_POLL_RESULTS) .mapToTable(BaseColumns._ID, Tables.GAME_POLL_RESULTS) .whereEquals(GamePolls.Columns.GAME_ID, gameId) .whereEquals(GamePolls.Columns.POLL_NAME, pollName) } override fun insert(context: Context, db: SQLiteDatabase, uri: Uri, values: ContentValues): Uri? { val gameId = Games.getGameId(uri) val pollName = Games.getPollName(uri) val builder = GamesIdPollsNameProvider().buildSimpleSelection(Games.buildPollsUri(gameId, pollName)) val pollId = queryInt(db, builder, BaseColumns._ID) values.put(POLL_ID, pollId) var key = values.getAsString(GamePollResults.Columns.POLL_RESULTS_PLAYERS) if (key.isNullOrEmpty()) key = "X" values.put(GamePollResults.Columns.POLL_RESULTS_KEY, key) try { val rowId = db.insertOrThrow(Tables.GAME_POLL_RESULTS, null, values) if (rowId != -1L) { return Games.buildPollResultsUri(gameId, pollName, values.getAsString(GamePollResults.Columns.POLL_RESULTS_PLAYERS)) } } catch (e: SQLException) { Timber.e(e, "Problem inserting poll %2\$s for game %1\$s", gameId, pollName) notifyException(context, e) } return null } }
gpl-3.0
eff3e83ddff2b18a546e32c54777c862
44.58209
178
0.700065
4.344239
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/ClientModifyBookDecoder.kt
1
2247
/* * 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.network.vanilla.packet.codec.play import io.netty.handler.codec.CodecException import io.netty.handler.codec.DecoderException import org.lanternpowered.server.data.io.store.item.WritableBookItemTypeObjectSerializer import org.lanternpowered.server.data.io.store.item.WrittenBookItemTypeObjectSerializer import org.lanternpowered.server.network.buffer.ByteBuffer import org.lanternpowered.server.network.packet.PacketDecoder import org.lanternpowered.server.network.packet.CodecContext import org.lanternpowered.server.network.vanilla.packet.type.play.ClientModifyBookPacket import org.spongepowered.api.data.type.HandTypes object ClientModifyBookDecoder : PacketDecoder<ClientModifyBookPacket> { override fun decode(ctx: CodecContext, buf: ByteBuffer): ClientModifyBookPacket { val rawItemStack = buf.readRawItemStack() val sign = buf.readBoolean() val handType = if (buf.readVarInt() == 0) HandTypes.MAIN_HAND.get() else HandTypes.OFF_HAND.get() if (rawItemStack == null) throw DecoderException("Modified book may not be null!") val dataView = rawItemStack.dataView ?: throw DecoderException("Modified book data view (nbt tag) may not be null!") val pages = dataView.getStringList(WritableBookItemTypeObjectSerializer.PAGES) .orElseThrow { DecoderException("Edited book pages missing!") } if (sign) { val author = dataView.getString(WrittenBookItemTypeObjectSerializer.AUTHOR) .orElseThrow { CodecException("Signed book author missing!") } val title = dataView.getString(WrittenBookItemTypeObjectSerializer.TITLE) .orElseThrow { CodecException("Signed book title missing!") } return ClientModifyBookPacket.Sign(handType, pages, author, title) } return ClientModifyBookPacket.Edit(handType, pages) } }
mit
6ce237edb7d5fd83e5ba8490526a801e
51.255814
124
0.742323
4.557809
false
false
false
false
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/utils/ClassLoaderx.kt
1
1760
/* * 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("ClassLoaderx") package debop4k.core.utils import java.security.AccessController import java.security.PrivilegedAction fun getClassLoader(clazz: Class<*>): ClassLoader { if (System.getSecurityManager() == null) { return clazz.classLoader } else { return AccessController.doPrivileged(PrivilegedAction { clazz.classLoader }) } } fun getDefaultClassLoader(): ClassLoader { var cl = getContextClassLoader() // TODO: Caller 를 참고해야 한다.. // if (cl == null) { // val callerClass = Thread.currentThread().javaClass // cl = callerClass.classLoader // } return cl } fun getContextClassLoader(): ClassLoader { if (System.getSecurityManager() != null) { return Thread.currentThread().contextClassLoader } else { return AccessController.doPrivileged(PrivilegedAction { Thread.currentThread().contextClassLoader }) } } fun getSystemClassLoader(): ClassLoader { if (System.getSecurityManager() != null) { return ClassLoader.getSystemClassLoader() } else { return AccessController.doPrivileged(PrivilegedAction { ClassLoader.getSystemClassLoader() }) } }
apache-2.0
66a387437691efab294c879fe9a7bdaa
29.649123
104
0.733677
4.279412
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/psi/LatexEnvironmentManipulator.kt
1
1358
package nl.hannahsten.texifyidea.psi import com.intellij.openapi.util.TextRange import com.intellij.psi.AbstractElementManipulator import com.intellij.psi.PsiFileFactory import com.intellij.psi.util.PsiTreeUtil import nl.hannahsten.texifyidea.LatexLanguage import nl.hannahsten.texifyidea.psi.impl.LatexEnvironmentImpl /** * Enable editing environment content in a separate window (when using language injection). */ class LatexEnvironmentManipulator : AbstractElementManipulator<LatexEnvironmentImpl>() { override fun handleContentChange( element: LatexEnvironmentImpl, range: TextRange, newContent: String ): LatexEnvironmentImpl? { val oldText = element.text // For some reason the endoffset of the given range is incorrect: sometimes it excludes the last line, so we calculate it ourselves val endOffset = oldText.indexOf("\\end{${element.environmentName}}") - 1 // -1 to exclude \n val newText = oldText.substring(0, range.startOffset) + newContent + oldText.substring(endOffset) val file = PsiFileFactory.getInstance(element.project) .createFileFromText("temp.tex", LatexLanguage, newText) val res = PsiTreeUtil.findChildOfType(file, LatexEnvironmentImpl::class.java) ?: return null element.replace(res) return element } }
mit
89cae92440e7469b64bc6bed876b93f0
42.806452
139
0.73785
4.992647
false
false
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/data/api/model/Note.kt
1
3364
package me.ykrank.s1next.data.api.model import com.fasterxml.jackson.annotation.* import com.google.common.base.Objects import com.github.ykrank.androidtools.ui.adapter.StableIdModel import com.github.ykrank.androidtools.ui.adapter.model.DiffSameItem import paperparcel.PaperParcel import paperparcel.PaperParcelable import java.util.regex.Pattern /** * Created by ykrank on 2017/1/5. */ @JsonIgnoreProperties(ignoreUnknown = true) @PaperParcel class Note : PaperParcelable, DiffSameItem, StableIdModel { @JsonProperty("author") var author: String? = null @JsonProperty("authorid") var authorId: String? = null @JsonProperty("dateline") var dateline: Long = 0 @JsonProperty("id") var id: String? = null @JsonIgnore private var isNew: Boolean = false @JsonIgnore var note: String? = null //eg forum.php?mod=redirect&goto=findpost&ptid=1220112&pid=1 @JsonIgnore var url: String? = null @JsonIgnore var content: String? = null @JsonCreator constructor(@JsonProperty("note") note: String) { this.note = note //eg <a href="home.php?mod=space&uid=1">someone</a> 回复了您的帖子 <a href="forum.php?mod=redirect&goto=findpost&ptid=1220112&pid=1" target="_blank">【Android】 s1Next-鹅版-v0.7.2(群522433035)</a> &nbsp; <a href="forum.php?mod=redirect&goto=findpost&pid=34692327&ptid=1220112" target="_blank" class="lit">查看</a> var pattern = Pattern.compile("<a href=\"(forum\\.php\\?mod=redirect&goto=findpost.+?)\"") var matcher = pattern.matcher(note) if (matcher.find()) { url = matcher.group(1) } pattern = Pattern.compile("target=\"_blank\">(.+)</a> &nbsp;") matcher = pattern.matcher(note) if (matcher.find()) { content = matcher.group(1) } } fun isNew(): Boolean { return isNew } fun setNew(aNew: Boolean) { isNew = aNew } @JsonSetter("new") fun setNew(aNew: Int) { isNew = aNew > 0 } override fun isSameItem(o: Any): Boolean { if (this === o) return true return if (o !is Note) false else Objects.equal(id, o.id) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Note if (author != other.author) return false if (authorId != other.authorId) return false if (dateline != other.dateline) return false if (id != other.id) return false if (isNew != other.isNew) return false if (note != other.note) return false if (url != other.url) return false if (content != other.content) return false return true } override fun hashCode(): Int { var result = author?.hashCode() ?: 0 result = 31 * result + (authorId?.hashCode() ?: 0) result = 31 * result + dateline.hashCode() result = 31 * result + (id?.hashCode() ?: 0) result = 31 * result + isNew.hashCode() result = 31 * result + (note?.hashCode() ?: 0) result = 31 * result + (url?.hashCode() ?: 0) result = 31 * result + (content?.hashCode() ?: 0) return result } companion object { @JvmField val CREATOR = PaperParcelNote.CREATOR } }
apache-2.0
2a8ce900ed4ac361b0a636e3ed1959a9
30.733333
307
0.616146
3.731243
false
false
false
false
cout970/Statistics
src/main/kotlin/com/cout970/statistics/gui/InventoryDetector.kt
1
10023
package com.cout970.statistics.gui import com.cout970.statistics.Statistics import com.cout970.statistics.data.ItemIdentifier import com.cout970.statistics.network.ClientEventPacket import com.cout970.statistics.network.GuiPacket import com.cout970.statistics.tileentity.TileInventoryDetector import net.minecraft.client.gui.Gui import net.minecraft.client.gui.GuiTextField import net.minecraft.client.renderer.GlStateManager import net.minecraft.entity.player.EntityPlayer import net.minecraft.init.Blocks import net.minecraft.item.EnumDyeColor import net.minecraft.item.Item import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound import net.minecraft.nbt.NBTTagList import net.minecraft.util.math.BlockPos import net.minecraft.world.World import net.minecraftforge.common.util.Constants import org.lwjgl.input.Keyboard import org.lwjgl.input.Mouse import java.awt.Color /** * Created by cout970 on 06/08/2016. */ class GuiInventoryDetector(val cont: ContainerInventoryDetector) : GuiBase(cont) { lateinit var text: GuiTextField var offset = 0 var count = 0 var newLimit = -1 override fun initGui() { super.initGui() text = object : GuiTextField(0, fontRendererObj, guiLeft + 80 - 2, guiTop + 67 + 8, 90, 18) { override fun setFocused(isFocusedIn: Boolean) { super.setFocused(isFocusedIn) if (!isFocusedIn) { var amount = cont.tile!!.limit try { val i = Integer.parseInt(text) if (i >= 0) { amount = i } } catch (e: Exception) { } text = amount.toString() cont.tile!!.limit = amount newLimit = amount Statistics.NETWORK.sendToServer(ClientEventPacket(cont.tile!!.world.provider.dimension, cont.tile!!.pos, 0, amount)) } } } text.text = cont.tile!!.limit.toString() } override fun updateScreen() { super.updateScreen() text.updateCursorCounter() } override fun drawGuiContainerBackgroundLayer(partialTicks: Float, mouseX: Int, mouseY: Int) { if (cont.tile!!.limit != newLimit) { newLimit = cont.tile!!.limit text.text = cont.tile!!.limit.toString() } val tile = cont.tile!! val start = guiTop + 67 //background Gui.drawRect(guiLeft, guiTop + 67, guiLeft + xSize, guiTop + 100, 0x7F4C4C4C.toInt()) //active/disable val item = ItemStack(Blocks.STAINED_GLASS_PANE, 1, if (tile.active) 5 else 14) drawStack(item, guiLeft + 9, start + 9) //item Gui.drawRect(guiLeft + 35, start + 8, guiLeft + 53, start + 26, 0x7FFFFFFF.toInt()) Gui.drawRect(guiLeft + 35 - 1, start + 8 - 1, guiLeft + 53 + 1, start + 26 + 1, 0x7F000000.toInt()) synchronized(tile) { val selected = tile.itemCache if (selected != null) { drawStack(selected.stack.copy().apply { stackSize = 1 }, guiLeft + 9 + 18 + 9, start + 9) } } //comparator drawBox(guiLeft + 59, start + 11, 6 + 8, 8 + 4, 0x3FFFFFFF.toInt()) drawCenteredString(fontRendererObj, tile.operation.toString(), guiLeft + 65, start + 13, Color.WHITE.rgb) //text text.drawTextBox() //items val move = -20 Gui.drawRect(guiLeft, guiTop + 123 + move, guiLeft + xSize, guiTop + 125 + 54 + move, 0x4F4C4C4C.toInt()) synchronized(tile) { var index = 0 val allItems = tile.items.keys.sortedBy { it.stack.item.registryName.toString() } val dye = EnumDyeColor.byMetadata(0) for (i in allItems) { if (index / 9 < 3 + offset && index / 9 - offset >= 0) { val x = index % 9 * 18 + 7 val y = (index / 9 - offset) * 18 + 125 + move val stack = i.stack.copy().apply { stackSize = 1 } if (tile.getItem(index) == tile.itemCache) { if (stack.item != Item.getItemFromBlock(Blocks.STAINED_GLASS_PANE)) { GlStateManager.pushMatrix() GlStateManager.translate(0.0, 0.0, -20.0) drawStack(ItemStack(Blocks.STAINED_GLASS_PANE, 1, dye.metadata), guiLeft + x, guiTop + y) GlStateManager.popMatrix() } else { Gui.drawRect(guiLeft + x - 1, guiTop + y - 1, guiLeft + x + 17, guiTop + y + 17, dye.mapColor.colorValue or 0x5F000000.toInt()) } } drawStack(stack, guiLeft + x, guiTop + y) } index++ } count = index } } override fun drawGuiContainerForegroundLayer(mouseX: Int, mouseY: Int) { if (inside(guiLeft + 9 + 18 + 9 - 1, guiTop + 67 + 9 - 1, 18, 18, mouseX, mouseY)) { if (cont.tile!!.amount != -1) { drawHoveringText(listOf("Amount: " + cont.tile!!.amount.toString()), mouseX - guiLeft, mouseY - guiTop) } } if (inside(guiLeft + 8, guiTop + 67 + 8, 18, 18, mouseX, mouseY)) { drawHoveringText(listOf(cont.tile!!.active.toString()), mouseX - guiLeft, mouseY - guiTop) } super.drawGuiContainerForegroundLayer(mouseX, mouseY) } fun drawBox(x: Int, y: Int, sizeX: Int, sizeY: Int, color: Int = 0x7F4C4C4C.toInt()) { Gui.drawRect(x, y, x + sizeX, y + sizeY, color) } override fun handleMouseInput() { super.handleMouseInput() val dwheel = Mouse.getDWheel() if (dwheel < 0) { if (count / 9 > 3 + offset) { offset++ } } else if (dwheel > 0) { if (offset > 0) { offset-- } } } override fun mouseClicked(mouseX: Int, mouseY: Int, mouseButton: Int) { text.mouseClicked(mouseX, mouseY, mouseButton) if (mouseButton == 0) { if (inside(guiLeft + 59, guiTop + 67 + 11, 6 + 8, 8 + 4, mouseX, mouseY)) { Statistics.NETWORK.sendToServer(ClientEventPacket(cont.tile!!.world.provider.dimension, cont.tile!!.pos, 1, cont.tile!!.operation.ordinal + 1)) } } val move = -20 val tile = cont.tile!! start@for (x in 0 until 9) { for (y in 0 until 3) { if (inside(guiLeft + x * 18 + 6, guiTop + y * 18 + 125 + move, 18, 18, mouseX, mouseY)) { val index = x + (y + offset) * 9 if (mouseButton == 0) { if (index < count && tile.getItem(index) != tile.itemCache) { Statistics.NETWORK.sendToServer(ClientEventPacket(cont.tile!!.world.provider.dimension, cont.tile!!.pos, 2, index)) } } else { if (tile.getItem(index) == tile.itemCache) { Statistics.NETWORK.sendToServer(ClientEventPacket(cont.tile!!.world.provider.dimension, cont.tile!!.pos, 2, -1)) } } break@start } } } super.mouseClicked(mouseX, mouseY, mouseButton) } override fun keyTyped(typedChar: Char, keyCode: Int) { text.textboxKeyTyped(typedChar, keyCode) if (keyCode == Keyboard.KEY_DOWN) { if (count / 9 > 3 + offset) { offset++ } } else if (keyCode == Keyboard.KEY_UP) { if (offset > 0) { offset-- } } super.keyTyped(typedChar, keyCode) } } class ContainerInventoryDetector(world: World, pos: BlockPos, player: EntityPlayer) : ContainerBase(world, pos, player) { val tile by lazy { val t = world.getTileEntity(pos) if (t is TileInventoryDetector) { t } else { null } } override fun readPacket(pkt: GuiPacket) { if (tile != null) { val nbt = pkt.nbt!! val map = mutableMapOf<ItemIdentifier, Int>() nbt.getTagList("Items", Constants.NBT.TAG_COMPOUND).forEach { val item = ItemIdentifier.deserializeNBT(it) val size = it.getInteger("Extra") map.put(item, size) } synchronized(tile!!) { tile!!.operation = TileInventoryDetector.Operation.values()[nbt.getInteger("Operation")] tile!!.active = nbt.getBoolean("Active") if (!nbt.getCompoundTag("Cache").hasNoTags()) { tile!!.itemCache = ItemIdentifier.deserializeNBT(nbt.getCompoundTag("Cache")) } else { tile!!.itemCache = null } tile!!.limit = nbt.getInteger("Limit") tile!!.amount = nbt.getInteger("Amount") tile!!.items.clear() tile!!.items.putAll(map) } } } override fun writePacket(): GuiPacket? = GuiPacket(NBTTagCompound().apply { setTag("Items", encodeItems(tile!!.items)) setTag("Cache", tile!!.itemCache?.serializeNBT() ?: NBTTagCompound()) setInteger("Limit", tile!!.limit) setInteger("Amount", tile!!.amount) setInteger("Operation", tile!!.operation.ordinal) setBoolean("Active", tile!!.getRedstoneLevel() > 0) }) private fun encodeItems(map: Map<ItemIdentifier, Int>): NBTTagList { //items val itemList = NBTTagList() for ((key, value) in map) { itemList.appendTag(key.serializeNBT().apply { setInteger("Extra", value) }) } return itemList } }
gpl-3.0
c2d4f883d1da39c767b548ded2b8ec87
37.852713
159
0.542153
4.314679
false
false
false
false
Mithrandir21/Duopoints
app/src/main/java/com/duopoints/android/fragments/registration/RegPresenter.kt
1
2145
package com.duopoints.android.fragments.registration import android.text.TextUtils import com.duopoints.android.Calls import com.duopoints.android.fragments.base.BasePresenter import com.duopoints.android.rest.models.geo.City import com.duopoints.android.rest.models.geo.Country import com.duopoints.android.rest.models.geo.wrappers.CityWrapper import com.duopoints.android.rest.models.geo.wrappers.CountryWrapper import com.duopoints.android.rest.models.post.UserReg import com.duopoints.android.utils.ReactiveUtils import io.reactivex.functions.Consumer import java.util.regex.Pattern class RegPresenter internal constructor(regFrag: RegFrag) : BasePresenter<RegFrag>(regFrag) { private val chars = Pattern.compile("\\w+", Pattern.UNICODE_CASE) fun loadCountries() { Calls.geoService.allCountries .map<ArrayList<Country>>(CountryWrapper::geonames) .compose(ReactiveUtils.workMaybeInBackgroundDeliverToMain()) .subscribe(view::countriesLoaded, Throwable::printStackTrace) } fun loadCities(countryID: Int) { Calls.geoService.getCities(countryID) .map<ArrayList<City>>(CityWrapper::geonames) .compose(ReactiveUtils.workMaybeInBackgroundDeliverToMain()) .subscribe(view::citiesLoaded, Throwable::printStackTrace) } fun regUser(userReg: UserReg) { Calls.userService.registerUser(userReg) .compose(ReactiveUtils.workMaybeInBackgroundDeliverToMain()) .subscribe(Consumer(view::userRegistered), Consumer { view.failedUserReg() it.printStackTrace() }) } fun inputValidation(input: String): String? { return if (TextUtils.isEmpty(input) || !chars.matcher(input).matches()) null else input } fun countryValidation(country: Any?): String? { return if (country == null) null else (country as Country).countryName } fun cityValidation(city: Any?): String? { return if (city == null) null else (city as City).name } }
gpl-3.0
612f03335ec6fd0e1f381d1acb57107f
38.740741
95
0.683916
4.515789
false
false
false
false
googlesamples/mlkit
android/material-showcase/app/src/main/java/com/google/mlkit/md/objectdetection/StaticObjectDotView.kt
1
3019
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mlkit.md.objectdetection import android.animation.ValueAnimator import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.view.View import androidx.interpolator.view.animation.FastOutSlowInInterpolator import com.google.mlkit.md.R /** Represents a detected object by drawing a circle dot at the center of object's bounding box. */ class StaticObjectDotView @JvmOverloads constructor(context: Context, selected: Boolean = false) : View(context) { private val paint: Paint = Paint().apply { style = Paint.Style.FILL } private val unselectedDotRadius: Int = context.resources.getDimensionPixelOffset(R.dimen.static_image_dot_radius_unselected) private val radiusOffsetRange: Int private var currentRadiusOffset: Float = 0.toFloat() init { val selectedDotRadius = context.resources.getDimensionPixelOffset(R.dimen.static_image_dot_radius_selected) radiusOffsetRange = selectedDotRadius - unselectedDotRadius currentRadiusOffset = (if (selected) radiusOffsetRange else 0).toFloat() } fun playAnimationWithSelectedState(selected: Boolean) { val radiusOffsetAnimator: ValueAnimator = if (selected) { ValueAnimator.ofFloat(0f, radiusOffsetRange.toFloat()) .setDuration(DOT_SELECTION_ANIMATOR_DURATION_MS).apply { startDelay = DOT_DESELECTION_ANIMATOR_DURATION_MS } } else { ValueAnimator.ofFloat(radiusOffsetRange.toFloat(), 0f) .setDuration(DOT_DESELECTION_ANIMATOR_DURATION_MS) } radiusOffsetAnimator.interpolator = FastOutSlowInInterpolator() radiusOffsetAnimator.addUpdateListener { animation -> currentRadiusOffset = animation.animatedValue as Float invalidate() } radiusOffsetAnimator.start() } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val cx = width / 2f val cy = height / 2f paint.color = Color.WHITE canvas.drawCircle(cx, cy, unselectedDotRadius + currentRadiusOffset, paint) } companion object { private const val DOT_SELECTION_ANIMATOR_DURATION_MS: Long = 116 private const val DOT_DESELECTION_ANIMATOR_DURATION_MS: Long = 67 } }
apache-2.0
bd6296bf3ffb94dce33e56c8d772a7ad
37.705128
115
0.698907
4.72457
false
false
false
false
didi/DoraemonKit
Android/dokit/src/main/java/com/didichuxing/doraemonkit/DoKitFragmentLifecycleCallbacks.kt
1
1223
package com.didichuxing.doraemonkit import android.content.Context import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import com.didichuxing.doraemonkit.util.LifecycleListenerUtil /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2019-12-31-10:56 * 描 述:全局的fragment 生命周期回调 * 修订历史: * ================================================ */ class DoKitFragmentLifecycleCallbacks : FragmentManager.FragmentLifecycleCallbacks() { override fun onFragmentAttached(fm: FragmentManager, fragment: Fragment, context: Context) { super.onFragmentAttached(fm, fragment, context) for (listener in LifecycleListenerUtil.LIFECYCLE_LISTENERS) { listener.onFragmentAttached(fragment) } } override fun onFragmentDetached(fm: FragmentManager, fragment: Fragment) { super.onFragmentDetached(fm, fragment) for (listener in LifecycleListenerUtil.LIFECYCLE_LISTENERS) { listener.onFragmentDetached(fragment) } } companion object { private const val TAG = "DokitFragmentLifecycleCallbacks" } }
apache-2.0
b994b492dbf0dc553c8cf69e1f65a2eb
32.114286
96
0.658326
4.869748
false
false
false
false
zyallday/kotlin-koans
src/i_introduction/_2_Named_Arguments/n02NamedArguments.kt
1
959
package i_introduction._2_Named_Arguments import i_introduction._1_Java_To_Kotlin_Converter.task1 import util.TODO import util.doc2 // default values for arguments fun bar(i: Int, s: String = "", b: Boolean = true) {} fun usage() { // named arguments bar(1, b = false) } fun todoTask2(): Nothing = TODO( """ Task 2. Print out the collection contents surrounded by curly braces using the library function 'joinToString'. Specify only 'prefix' and 'postfix' arguments. Don't forget to remove the 'todoTask2()' invocation which throws an exception. """, documentation = doc2(), references = { collection: Collection<Int> -> task1(collection); collection.joinToString() }) fun task2(collection: Collection<Int>): String { return task2Impl(collection) } private fun task2Impl(collection: Collection<Int>) = collection.joinToString(separator = ", ", prefix = "{", postfix = "}")
mit
301f595ae2e9fd9826a4f6c773a79ebc
29.967742
111
0.67049
4.11588
false
false
false
false
rcgroot/open-gpstracker-ng
studio/base/src/main/java/nl/sogeti/android/gpstracker/ng/base/dagger/SystemModule.kt
1
1689
package nl.sogeti.android.gpstracker.ng.base.dagger import android.content.ContentResolver import android.content.Context import android.content.pm.PackageManager import android.net.Uri import android.os.AsyncTask import dagger.Module import dagger.Provides import nl.sogeti.android.gpstracker.ng.base.location.GpsLocationFactory import nl.sogeti.android.gpstracker.ng.base.location.LocationFactory import nl.sogeti.android.gpstracker.ng.common.controllers.gpsstatus.GpsStatusControllerFactory import java.util.concurrent.Executor import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module class SystemModule { @Provides fun gpsStatusControllerFactory(application: Context): GpsStatusControllerFactory { return GpsStatusControllerFactory(application) } @Provides fun uriBuilder() = Uri.Builder() @Provides @Singleton @Computation fun computationExecutor(): Executor = AsyncTask.THREAD_POOL_EXECUTOR @Provides @Singleton @DiskIO fun diskExecutor(): Executor = ThreadPoolExecutor(1, 2, 10L, TimeUnit.SECONDS, LinkedBlockingQueue()) @Provides @Singleton @NetworkIO fun networkExecutor(): Executor = ThreadPoolExecutor(1, 16, 30L, TimeUnit.SECONDS, LinkedBlockingQueue()) @Provides fun packageManager(application: Context): PackageManager = application.packageManager @Provides fun locationFactory(application: Context): LocationFactory = GpsLocationFactory(application) @Provides fun contentResolver(application: Context): ContentResolver = application.contentResolver }
gpl-3.0
7edc371ff71a5aa53c2aaf1986ca3f47
30.867925
109
0.791593
4.771186
false
false
false
false
pedroSG94/rtmp-streamer-java
rtmp/src/main/java/com/pedro/rtmp/rtmp/message/command/CommandAmf0.kt
1
1202
/* * Copyright (C) 2021 pedroSG94. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pedro.rtmp.rtmp.message.command import com.pedro.rtmp.rtmp.chunk.ChunkStreamId import com.pedro.rtmp.rtmp.chunk.ChunkType import com.pedro.rtmp.rtmp.message.BasicHeader import com.pedro.rtmp.rtmp.message.MessageType /** * Created by pedro on 21/04/21. */ class CommandAmf0(name: String = "", commandId: Int = 0, timestamp: Int = 0, streamId: Int = 0, basicHeader: BasicHeader = BasicHeader(ChunkType.TYPE_0, ChunkStreamId.OVER_CONNECTION.mark)): Command(name, commandId, timestamp, streamId, basicHeader = basicHeader) { override fun getType(): MessageType = MessageType.COMMAND_AMF0 }
apache-2.0
a7325de1122ecf8c02475f33e1991a8e
39.1
146
0.753744
3.877419
false
false
false
false
nemerosa/ontrack
ontrack-extension-auto-versioning/src/main/java/net/nemerosa/ontrack/extension/av/properties/yaml/Yaml.kt
1
1226
package net.nemerosa.ontrack.extension.av.properties.yaml import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator import com.fasterxml.jackson.module.kotlin.KotlinModule import com.fasterxml.jackson.module.kotlin.readValues import java.io.StringWriter class Yaml { private val yamlFactory = YAMLFactory().apply { enable(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE) } private val mapper = ObjectMapper(yamlFactory).apply { registerModule(KotlinModule.Builder().build()) } /** * Reads some Yaml as a list of documents */ fun read(content: String): List<ObjectNode> { val parser = yamlFactory.createParser(content) return mapper .readValues<ObjectNode>(parser) .readAll() } fun write(json: List<ObjectNode>): String { val writer = StringWriter() json.forEach { val generator = yamlFactory.createGenerator(writer) generator.writeObject(it) writer.append('\n') } return writer.toString() } }
mit
b78aa068cf4f5a3547070636a53ed2e4
28.926829
63
0.690865
4.540741
false
false
false
false
goodwinnk/intellij-community
platform/configuration-store-impl/src/ComponentStoreImpl.kt
1
24516
// 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.configurationStore import com.intellij.configurationStore.statistic.eventLog.FeatureUsageSettingsEvents import com.intellij.notification.NotificationsManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ex.DecodeDefaultsUtil import com.intellij.openapi.application.runUndoTransparentWriteAction import com.intellij.openapi.components.* import com.intellij.openapi.components.StateStorage.SaveSession import com.intellij.openapi.components.StateStorageChooserEx.Resolution import com.intellij.openapi.components.impl.ComponentManagerImpl import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.components.impl.stores.SaveSessionAndFile import com.intellij.openapi.components.impl.stores.StoreUtil import com.intellij.openapi.components.impl.stores.UnknownMacroNotification import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.Project import com.intellij.openapi.util.InvalidDataException import com.intellij.openapi.util.JDOMExternalizable import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess import com.intellij.ui.AppUIUtil import com.intellij.util.ArrayUtilRt import com.intellij.util.SmartList import com.intellij.util.SystemProperties import com.intellij.util.containers.SmartHashSet import com.intellij.util.containers.isNullOrEmpty import com.intellij.util.lang.CompoundRuntimeException import com.intellij.util.messages.MessageBus import com.intellij.util.xmlb.XmlSerializerUtil import gnu.trove.THashMap import org.jdom.Element import org.jetbrains.annotations.TestOnly import java.io.IOException import java.nio.file.Paths import java.util.* import java.util.concurrent.TimeUnit import com.intellij.openapi.util.Pair as JBPair internal val LOG = Logger.getInstance(ComponentStoreImpl::class.java) internal val deprecatedComparator = Comparator<Storage> { o1, o2 -> val w1 = if (o1.deprecated) 1 else 0 val w2 = if (o2.deprecated) 1 else 0 w1 - w2 } private class PersistenceStateAdapter(val component: Any) : PersistentStateComponent<Any> { override fun getState() = component override fun loadState(state: Any) { XmlSerializerUtil.copyBean(state, component) } } private val NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD_DEFAULT = TimeUnit.MINUTES.toSeconds(4).toInt() private var NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD = NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD_DEFAULT @TestOnly internal fun restoreDefaultNotRoamableComponentSaveThreshold() { NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD = NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD_DEFAULT } @TestOnly internal fun setRoamableComponentSaveThreshold(thresholdInSeconds: Int) { NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD = thresholdInSeconds } abstract class ComponentStoreImpl : IComponentStore { private val components = Collections.synchronizedMap(THashMap<String, ComponentInfo>()) internal open val project: Project? get() = null open val loadPolicy: StateLoadPolicy get() = StateLoadPolicy.LOAD override abstract val storageManager: StateStorageManager internal fun getComponents(): Map<String, ComponentInfo> { return components } override fun initComponent(component: Any, isService: Boolean) { var componentName = "" try { @Suppress("DEPRECATION") if (component is PersistentStateComponent<*>) { componentName = initPersistenceStateComponent(component, StoreUtil.getStateSpec(component), isService) } else if (component is JDOMExternalizable) { componentName = ComponentManagerImpl.getComponentName(component) @Suppress("DEPRECATION") initJdomExternalizable(component, componentName) } } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { LOG.error("Cannot init $componentName component state", e) return } } override fun initPersistencePlainComponent(component: Any, key: String) { initPersistenceStateComponent(PersistenceStateAdapter(component), StateAnnotation(key, FileStorageAnnotation(StoragePathMacros.WORKSPACE_FILE, false)), isService = false) } private fun initPersistenceStateComponent(component: PersistentStateComponent<*>, stateSpec: State, isService: Boolean): String { val componentName = stateSpec.name val info = doAddComponent(componentName, component, stateSpec) if (initComponent(info, null, false) && isService) { // if not service, so, component manager will check it later for all components project?.let { val app = ApplicationManager.getApplication() if (!app.isHeadlessEnvironment && !app.isUnitTestMode && it.isInitialized) { notifyUnknownMacros(this, it, componentName) } } } return componentName } override final fun save(readonlyFiles: MutableList<SaveSessionAndFile>, isForce: Boolean) { val errors: MutableList<Throwable> = SmartList<Throwable>() beforeSaveComponents(errors) val externalizationSession = if (components.isEmpty()) null else SaveSessionProducerManager() if (externalizationSession != null) { saveComponents(isForce, externalizationSession, errors) } afterSaveComponents(errors) try { saveAdditionalComponents(isForce) } catch (e: Throwable) { errors.add(e) } if (externalizationSession != null) { doSave(externalizationSession, readonlyFiles, errors) } CompoundRuntimeException.throwIfNotEmpty(errors) } protected open fun saveAdditionalComponents(isForce: Boolean) { } protected open fun beforeSaveComponents(errors: MutableList<Throwable>) { } protected open fun afterSaveComponents(errors: MutableList<Throwable>) { } private fun saveComponents(isForce: Boolean, session: SaveSessionProducerManager, errors: MutableList<Throwable>): MutableList<Throwable>? { val isUseModificationCount = Registry.`is`("store.save.use.modificationCount", true) val names = ArrayUtilRt.toStringArray(components.keys) Arrays.sort(names) val timeLogPrefix = "Saving" val timeLog = if (LOG.isDebugEnabled) StringBuilder(timeLogPrefix) else null // well, strictly speaking each component saving takes some time, but +/- several seconds doesn't matter val nowInSeconds: Int = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()).toInt() for (name in names) { val start = if (timeLog == null) 0 else System.currentTimeMillis() try { val info = components.get(name)!! var currentModificationCount = -1L if (info.isModificationTrackingSupported) { currentModificationCount = info.currentModificationCount if (currentModificationCount == info.lastModificationCount) { LOG.debug { "${if (isUseModificationCount) "Skip " else ""}$name: modificationCount ${currentModificationCount} equals to last saved" } if (isUseModificationCount) { continue } } } if (info.lastSaved != -1) { if (isForce || (nowInSeconds - info.lastSaved) > NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD) { info.lastSaved = nowInSeconds } else { LOG.debug { "Skip $name: was already saved in last ${TimeUnit.SECONDS.toMinutes(NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD_DEFAULT.toLong())} minutes (lastSaved ${info.lastSaved}, now: $nowInSeconds)" } continue } } commitComponent(session, info, name) info.updateModificationCount(currentModificationCount) } catch (e: Throwable) { errors.add(Exception("Cannot get $name component state", e)) } timeLog?.let { val duration = System.currentTimeMillis() - start if (duration > 10) { it.append("\n").append(name).append(" took ").append(duration).append(" ms: ").append((duration / 60000)).append(" min ").append( ((duration % 60000) / 1000)).append("sec") } } } if (timeLog != null && timeLog.length > timeLogPrefix.length) { LOG.debug(timeLog.toString()) } return errors } @TestOnly override fun saveApplicationComponent(component: PersistentStateComponent<*>) { val stateSpec = StoreUtil.getStateSpec(component) LOG.info("saveApplicationComponent is called for ${stateSpec.name}") val externalizationSession = SaveSessionProducerManager() commitComponent(externalizationSession, ComponentInfoImpl(component, stateSpec), null) val absolutePath = Paths.get(storageManager.expandMacros(findNonDeprecated(stateSpec.storages).path)).toAbsolutePath().toString() runUndoTransparentWriteAction { val errors: MutableList<Throwable> = SmartList<Throwable>() try { VfsRootAccess.allowRootAccess(absolutePath) val isSomethingChanged = externalizationSession.save(errors = errors) if (!isSomethingChanged) { LOG.info("saveApplicationComponent is called for ${stateSpec.name} but nothing to save") } } finally { VfsRootAccess.disallowRootAccess(absolutePath) } CompoundRuntimeException.throwIfNotEmpty(errors) } } private fun commitComponent(session: SaveSessionProducerManager, info: ComponentInfo, componentName: String?) { val component = info.component @Suppress("DEPRECATION") if (component is JDOMExternalizable) { val effectiveComponentName = componentName ?: ComponentManagerImpl.getComponentName(component) storageManager.getOldStorage(component, effectiveComponentName, StateStorageOperation.WRITE)?.let { session.getProducer(it)?.setState(component, effectiveComponentName, component) } return } val state = (component as PersistentStateComponent<*>).state ?: return val stateSpec = info.stateSpec!! val effectiveComponentName = componentName ?: stateSpec.name val stateStorageChooser = component as? StateStorageChooserEx val storageSpecs = getStorageSpecs(component, stateSpec, StateStorageOperation.WRITE) for (storageSpec in storageSpecs) { @Suppress("IfThenToElvis") var resolution = if (stateStorageChooser == null) Resolution.DO else stateStorageChooser.getResolution(storageSpec, StateStorageOperation.WRITE) if (resolution == Resolution.SKIP) { continue } val storage = storageManager.getStateStorage(storageSpec) if (resolution == Resolution.DO) { resolution = storage.getResolution(component, StateStorageOperation.WRITE) if (resolution == Resolution.SKIP) { continue } } session.getProducer(storage)?.setState(component, effectiveComponentName, if (storageSpec.deprecated || resolution == Resolution.CLEAR) null else state) } } protected open fun doSave(saveSession: SaveExecutor, readonlyFiles: MutableList<SaveSessionAndFile> = arrayListOf(), errors: MutableList<Throwable>) { saveSession.save(readonlyFiles, errors) return } private fun initJdomExternalizable(@Suppress("DEPRECATION") component: JDOMExternalizable, componentName: String): String? { doAddComponent(componentName, component, null) if (loadPolicy != StateLoadPolicy.LOAD) { return null } try { getDefaultState(component, componentName, Element::class.java)?.let { component.readExternal(it) } } catch (e: Throwable) { LOG.error(e) } val element = storageManager.getOldStorage(component, componentName, StateStorageOperation.READ)?.getState(component, componentName, Element::class.java, null, false) ?: return null try { component.readExternal(element) } catch (e: InvalidDataException) { LOG.error(e) return null } return componentName } private fun doAddComponent(name: String, component: Any, stateSpec: State?): ComponentInfo { val newInfo = createComponentInfo(component, stateSpec) val existing = components.put(name, newInfo) if (existing != null && existing.component !== component) { components.put(name, existing) LOG.error("Conflicting component name '$name': ${existing.component.javaClass} and ${component.javaClass}") return existing } return newInfo } private fun initComponent(info: ComponentInfo, changedStorages: Set<StateStorage>?, reloadData: Boolean): Boolean { if (loadPolicy == StateLoadPolicy.NOT_LOAD) { return false } @Suppress("UNCHECKED_CAST") if (doInitComponent(info.stateSpec!!, info.component as PersistentStateComponent<Any>, changedStorages, reloadData)) { // if component was initialized, update lastModificationCount info.updateModificationCount() return true } return false } private fun doInitComponent(stateSpec: State, component: PersistentStateComponent<Any>, changedStorages: Set<StateStorage>?, reloadData: Boolean): Boolean { val name = stateSpec.name @Suppress("UNCHECKED_CAST") val stateClass: Class<Any> = if (component is PersistenceStateAdapter) component.component::class.java as Class<Any> else ComponentSerializationUtil.getStateClass<Any>(component.javaClass) if (!stateSpec.defaultStateAsResource && LOG.isDebugEnabled && getDefaultState(component, name, stateClass) != null) { LOG.error("$name has default state, but not marked to load it") } val defaultState = if (stateSpec.defaultStateAsResource) getDefaultState(component, name, stateClass) else null if (loadPolicy == StateLoadPolicy.LOAD) { val storageChooser = component as? StateStorageChooserEx for (storageSpec in getStorageSpecs(component, stateSpec, StateStorageOperation.READ)) { if (storageChooser?.getResolution(storageSpec, StateStorageOperation.READ) == Resolution.SKIP) { continue } val storage = storageManager.getStateStorage(storageSpec) val stateGetter = createStateGetter(isUseLoadedStateAsExistingForComponent(storage, name), storage, component, name, stateClass, reloadData = reloadData) var state = stateGetter.getState(defaultState) if (state == null) { if (changedStorages != null && changedStorages.contains(storage)) { // state will be null if file deleted // we must create empty (initial) state to reinit component state = deserializeState(Element("state"), stateClass, null)!! } else { FeatureUsageSettingsEvents.logDefaultConfigurationState(name, stateSpec, stateClass, project) continue } } try { component.loadState(state) } finally { val stateAfterLoad = stateGetter.close() (stateAfterLoad ?: state).let { FeatureUsageSettingsEvents.logConfigurationState(name, stateSpec, it, project) } } return true } } // we load default state even if isLoadComponentState false - required for app components (for example, at least one color scheme must exists) if (defaultState == null) { component.noStateLoaded() } else { component.loadState(defaultState) } return true } // todo fix FacetManager // use.loaded.state.as.existing used in upsource private fun isUseLoadedStateAsExistingForComponent(storage: StateStorage, name: String): Boolean { return isUseLoadedStateAsExisting(storage) && name != "AntConfiguration" && name != "ProjectModuleManager" /* why after loadState we get empty state on getState, test CMakeWorkspaceContentRootsTest */ && name != "FacetManager" && name != "ProjectRunConfigurationManager" && /* ProjectRunConfigurationManager is used only for IPR, avoid relatively cost call getState */ name != "NewModuleRootManager" /* will be changed only on actual user change, so, to speed up module loading, skip it */ && name != "DeprecatedModuleOptionManager" /* doesn't make sense to check it */ && SystemProperties.getBooleanProperty("use.loaded.state.as.existing", true) } protected open fun isUseLoadedStateAsExisting(storage: StateStorage): Boolean = (storage as? XmlElementStorage)?.roamingType != RoamingType.DISABLED protected open fun getPathMacroManagerForDefaults(): PathMacroManager? = null private fun <T : Any> getDefaultState(component: Any, componentName: String, stateClass: Class<T>): T? { val url = DecodeDefaultsUtil.getDefaults(component, componentName) ?: return null try { val element = JDOMUtil.load(url) getPathMacroManagerForDefaults()?.expandPaths(element) return deserializeState(element, stateClass, null) } catch (e: Throwable) { throw IOException("Error loading default state from $url", e) } } protected open fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> { val storages = stateSpec.storages if (storages.size == 1 || component is StateStorageChooserEx) { return storages.toList() } if (storages.isEmpty()) { if (stateSpec.defaultStateAsResource) { return emptyList() } throw AssertionError("No storage specified") } return storages.sortByDeprecated() } final override fun isReloadPossible(componentNames: Set<String>): Boolean = !componentNames.any { isNotReloadable(it) } private fun isNotReloadable(name: String): Boolean { val component = components.get(name)?.component ?: return false return component !is PersistentStateComponent<*> || !StoreUtil.getStateSpec(component).reloadable } fun getNotReloadableComponents(componentNames: Collection<String>): Collection<String> { var notReloadableComponents: MutableSet<String>? = null for (componentName in componentNames) { if (isNotReloadable(componentName)) { if (notReloadableComponents == null) { notReloadableComponents = LinkedHashSet() } notReloadableComponents.add(componentName) } } return notReloadableComponents ?: emptySet() } override final fun reloadStates(componentNames: Set<String>, messageBus: MessageBus) { runBatchUpdate(messageBus) { reinitComponents(componentNames) } } override final fun reloadState(componentClass: Class<out PersistentStateComponent<*>>) { val stateSpec = StoreUtil.getStateSpecOrError(componentClass) val info = components.get(stateSpec.name) ?: return (info.component as? PersistentStateComponent<*>)?.let { initComponent(info, emptySet(), true) } } private fun reloadState(componentName: String, changedStorages: Set<StateStorage>): Boolean { val info = components.get(componentName) ?: return false if (info.component !is PersistentStateComponent<*>) { return false } val changedStoragesEmpty = changedStorages.isEmpty() initComponent(info, if (changedStoragesEmpty) null else changedStorages, changedStoragesEmpty) return true } /** * null if reloaded * empty list if nothing to reload * list of not reloadable components (reload is not performed) */ fun reload(changedStorages: Set<StateStorage>): Collection<String>? { if (changedStorages.isEmpty()) { return emptySet() } val componentNames = SmartHashSet<String>() for (storage in changedStorages) { try { // we must update (reload in-memory storage data) even if non-reloadable component will be detected later // not saved -> user does own modification -> new (on disk) state will be overwritten and not applied storage.analyzeExternalChangesAndUpdateIfNeed(componentNames) } catch (e: Throwable) { LOG.error(e) } } if (componentNames.isEmpty) { return emptySet() } val notReloadableComponents = getNotReloadableComponents(componentNames) reinitComponents(componentNames, changedStorages, notReloadableComponents) return if (notReloadableComponents.isEmpty()) null else notReloadableComponents } // used in settings repository plugin /** * You must call it in batch mode (use runBatchUpdate) */ fun reinitComponents(componentNames: Set<String>, changedStorages: Set<StateStorage> = emptySet(), notReloadableComponents: Collection<String> = emptySet()) { for (componentName in componentNames) { if (!notReloadableComponents.contains(componentName)) { reloadState(componentName, changedStorages) } } } @TestOnly fun removeComponent(name: String) { components.remove(name) } } internal fun executeSave(session: SaveSession, readonlyFiles: MutableList<SaveSessionAndFile>, errors: MutableList<Throwable>) { try { session.save() } catch (e: ReadOnlyModificationException) { LOG.warn(e) readonlyFiles.add(SaveSessionAndFile(e.session ?: session, e.file)) } catch (e: Exception) { errors.add(e) } } private fun findNonDeprecated(storages: Array<Storage>) = storages.firstOrNull { !it.deprecated } ?: throw AssertionError( "All storages are deprecated") enum class StateLoadPolicy { LOAD, LOAD_ONLY_DEFAULT, NOT_LOAD } internal fun Array<out Storage>.sortByDeprecated(): List<Storage> { if (size < 2) { return toList() } if (!first().deprecated) { val othersAreDeprecated = (1 until size).any { get(it).deprecated } if (othersAreDeprecated) { return toList() } } return sortedWith(deprecatedComparator) } private fun notifyUnknownMacros(store: IComponentStore, project: Project, componentName: String) { val substitutor = store.storageManager.macroSubstitutor ?: return val immutableMacros = substitutor.getUnknownMacros(componentName) if (immutableMacros.isEmpty()) { return } val macros = LinkedHashSet(immutableMacros) AppUIUtil.invokeOnEdt(Runnable { var notified: MutableList<String>? = null val manager = NotificationsManager.getNotificationsManager() for (notification in manager.getNotificationsOfType(UnknownMacroNotification::class.java, project)) { if (notified == null) { notified = SmartList<String>() } notified.addAll(notification.macros) } if (!notified.isNullOrEmpty()) { macros.removeAll(notified!!) } if (macros.isEmpty()) { return@Runnable } LOG.debug("Reporting unknown path macros $macros in component $componentName") doNotify(macros, project, Collections.singletonMap(substitutor, store)) }, project.disposed) } interface SaveExecutor { /** * @return was something really saved */ fun save(readonlyFiles: MutableList<SaveSessionAndFile> = SmartList(), errors: MutableList<Throwable>): Boolean } private class SaveSessionProducerManager : SaveExecutor { private val sessions = LinkedHashMap<StateStorage, StateStorage.SaveSessionProducer>() fun getProducer(storage: StateStorage): StateStorage.SaveSessionProducer? { var session = sessions.get(storage) if (session == null) { session = storage.createSaveSessionProducer() ?: return null sessions.put(storage, session) } return session } override fun save(readonlyFiles: MutableList<SaveSessionAndFile>, errors: MutableList<Throwable>): Boolean { if (sessions.isEmpty()) { return false } var changed = false for (session in sessions.values) { val saveSession = session.createSaveSession() ?: continue executeSave(saveSession, readonlyFiles, errors) changed = true } return changed } }
apache-2.0
e1d5f84610ac962bc4a1f4bd9853c5aa
37.24805
209
0.703867
5.159091
false
true
false
false
openHPI/android-app
app/src/main/java/de/xikolo/controllers/dialogs/OpenExternalContentDialog.kt
1
2057
package de.xikolo.controllers.dialogs import android.app.Dialog import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import com.yatatsu.autobundle.AutoBundleField import de.xikolo.R import de.xikolo.controllers.dialogs.base.BaseDialogFragment import de.xikolo.models.Item class OpenExternalContentDialog : BaseDialogFragment() { companion object { val TAG: String = OpenExternalContentDialog::class.java.simpleName } @AutoBundleField(required = false) var type: String = Item.TYPE_LTI var listener: ExternalContentDialogListener? = null override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val message = if (type == Item.TYPE_LTI) { getString( R.string.dialog_external_content_message_lti, getString(R.string.app_name) ) } else { getString(R.string.dialog_external_content_message_peer) } val yes = if (type == Item.TYPE_LTI) R.string.dialog_external_content_yes_lti else R.string.dialog_external_content_yes_peer val yesAlways = if (type == Item.TYPE_LTI) R.string.dialog_external_content_yes_always_lti else R.string.dialog_external_content_yes_always_peer val builder = AlertDialog.Builder(requireActivity()) builder.setMessage(message) .setTitle(R.string.dialog_external_content_title) .setPositiveButton(yes) { _, _ -> listener?.onOpen(this) } .setNegativeButton(R.string.dialog_negative) { _, _ -> dialog?.cancel() } .setNeutralButton(yesAlways) { _, _ -> listener?.onOpenAlways(this) } .setCancelable(true) val dialog = builder.create() dialog.setCanceledOnTouchOutside(true) return dialog } interface ExternalContentDialogListener { fun onOpen(dialog: DialogFragment) fun onOpenAlways(dialog: DialogFragment) } }
bsd-3-clause
acedf7928d1a1a00502cd905c3d6638f
32.721311
152
0.655323
4.43319
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/notifications/AnonymousNotificationHelper.kt
1
2172
package org.wikipedia.notifications import io.reactivex.rxjava3.core.Observable import org.wikipedia.auth.AccountUtil import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.mwapi.MwQueryResponse import org.wikipedia.page.PageTitle import org.wikipedia.settings.Prefs import org.wikipedia.util.DateUtil import java.util.* import java.util.concurrent.TimeUnit object AnonymousNotificationHelper { private const val NOTIFICATION_DURATION_DAYS = 7L fun onEditSubmitted() { if (!AccountUtil.isLoggedIn) { Prefs.lastAnonEditTime = Date().time } } fun observableForAnonUserInfo(wikiSite: WikiSite): Observable<MwQueryResponse> { return if (Date().time - Prefs.lastAnonEditTime < TimeUnit.DAYS.toMillis(NOTIFICATION_DURATION_DAYS)) { ServiceFactory.get(wikiSite).userInfo } else { Observable.just(MwQueryResponse()) } } fun shouldCheckAnonNotifications(response: MwQueryResponse): Boolean { if (isWithinAnonNotificationTime()) { return false } val hasMessages = response.query?.userInfo?.messages == true if (hasMessages) { if (!response.query?.userInfo?.name.isNullOrEmpty()) { Prefs.lastAnonUserWithMessages = response.query?.userInfo?.name } } return hasMessages } fun anonTalkPageHasRecentMessage(response: MwQueryResponse, title: PageTitle): Boolean { response.query?.firstPage()?.revisions?.firstOrNull()?.timeStamp?.let { if (Date().time - DateUtil.iso8601DateParse(it).time < TimeUnit.DAYS.toMillis(NOTIFICATION_DURATION_DAYS)) { Prefs.hasAnonymousNotification = true Prefs.lastAnonNotificationTime = Date().time Prefs.lastAnonNotificationLang = title.wikiSite.languageCode return true } } return false } fun isWithinAnonNotificationTime(): Boolean { return Date().time - Prefs.lastAnonNotificationTime < TimeUnit.DAYS.toMillis(NOTIFICATION_DURATION_DAYS) } }
apache-2.0
b882c9111ebb77a94daf2f2d7d4180f5
35.813559
120
0.682781
4.970252
false
false
false
false
cjkent/osiris
aws/src/main/kotlin/ws/osiris/aws/KeepAlive.kt
1
3054
package ws.osiris.aws import com.amazonaws.services.lambda.AWSLambda import com.amazonaws.services.lambda.AWSLambdaClientBuilder import com.amazonaws.services.lambda.model.InvocationType import com.amazonaws.services.lambda.model.InvokeRequest import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent import com.google.gson.Gson import org.slf4j.LoggerFactory import java.nio.ByteBuffer import kotlin.math.pow /** * The number of retries if the keep-alive call fails with access denied. * * Retrying is necessary because policy updates aren't visible immediately after the stack is updated. */ private const val RETRIES = 7 /** * Lambda that invokes other lambdas with keep-alive messages. * * It is triggered by a CloudWatch event containing the ARN of the lambda to keep alive and * the number of instances that should be kept alive. */ class KeepAliveLambda { private val lambdaClient: AWSLambda = AWSLambdaClientBuilder.defaultClient() private val gson: Gson = Gson() fun handle(trigger: KeepAliveTrigger) { log.debug("Triggering keep-alive, count: {}, function: {}", trigger.instanceCount, trigger.functionArn) // The lambda expects a request from API Gateway of this type - this fakes it val requestEvent = APIGatewayProxyRequestEvent().apply { resource = KEEP_ALIVE_RESOURCE headers = mapOf(KEEP_ALIVE_SLEEP to trigger.sleepTimeMs.toString()) } val json = gson.toJson(requestEvent) val payloadBuffer = ByteBuffer.wrap(json.toByteArray()) val invokeRequest = InvokeRequest().apply { functionName = trigger.functionArn invocationType = InvocationType.Event.name payload = payloadBuffer } /** * Invokes multiple copies of the function, retrying if access is denied. * * The retry is necessary because policy updates aren't visible immediately after the stack is updated. */ tailrec fun invokeFunctions(attemptCount: Int = 1) { try { repeat(trigger.instanceCount) { lambdaClient.invoke(invokeRequest) } log.debug("Keep-alive complete") return } catch (e: Exception) { if (attemptCount == RETRIES) throw e // Back off retrying - sleep for 2, 4, 8, 16, ... val sleep = 1000L * (2.0.pow(attemptCount)).toLong() log.debug("Exception triggering keep-alive: {} {}, sleeping for {}ms", e.javaClass.name, e.message, sleep) Thread.sleep(sleep) } invokeFunctions(attemptCount + 1) } invokeFunctions() } companion object { private val log = LoggerFactory.getLogger(KeepAliveLambda::class.java) } } /** * Message sent from the CloudWatch event to trigger keep-alive calls. */ class KeepAliveTrigger(var functionArn: String = "", var instanceCount: Int = 0, var sleepTimeMs: Int = 200)
apache-2.0
c70651c39857730d96239f36fd521dbf
38.153846
122
0.664375
4.606335
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/rule/attribute/TensorflowListAttributeValueLookupToIndex.kt
1
5095
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.tensorflow.rule.attribute import org.nd4j.ir.OpNamespace import org.nd4j.samediff.frameworkimport.argDescriptorType import org.nd4j.samediff.frameworkimport.findOp import org.nd4j.samediff.frameworkimport.ir.IRAttribute import org.nd4j.samediff.frameworkimport.isNd4jTensorName import org.nd4j.samediff.frameworkimport.isOutputFrameworkAttributeName import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder import org.nd4j.samediff.frameworkimport.process.MappingProcess import org.nd4j.samediff.frameworkimport.rule.MappingRule import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeValueType import org.nd4j.samediff.frameworkimport.rule.attribute.ListAttributeValueLookupToIndex import org.nd4j.samediff.frameworkimport.tensorflow.ir.TensorflowIRAttr import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowAttributeName import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowTensorName import org.nd4j.samediff.frameworkimport.tensorflow.ir.tensorflowAttributeValueTypeFor import org.tensorflow.framework.* @MappingRule("tensorflow","listattributevaluelookuptoindex","attribute") class TensorflowListAttributeValueLookupToIndex(mappingNamesToPerform: Map<String, String>, transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>) : ListAttributeValueLookupToIndex<GraphDef, OpDef, NodeDef, OpDef.AttrDef, AttrValue, TensorProto, DataType>(mappingNamesToPerform, transformerArgs) { override fun createIRAttribute(name: String, attrDef: OpDef.AttrDef, attributeValueType: AttrValue): IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType> { return TensorflowIRAttr(inputAttributeValue = attributeValueType, inputAttributeDef = attrDef) } override fun convertAttributesReverse(allInputArguments: List<OpNamespace.ArgDescriptor>, inputArgumentsToProcess: List<OpNamespace.ArgDescriptor>): List<IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType>> { TODO("Not yet implemented") } override fun isInputFrameworkTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return isTensorflowTensorName(name, opDef) } override fun isNd4jTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return isNd4jTensorName(name,nd4jOpDescriptor) } override fun isInputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return isTensorflowAttributeName(name, opDef) } override fun isOutputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return isOutputFrameworkAttributeName(name,nd4jOpDescriptor) } override fun argDescriptorType(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): OpNamespace.ArgDescriptor.ArgType { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return argDescriptorType(name,nd4jOpDescriptor) } override fun attributeValueTypeFor(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): AttributeValueType { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return tensorflowAttributeValueTypeFor(attributeName = name, opDef = opDef) } }
apache-2.0
79d7a06122e8556f363d3e11e05c20fd
64.333333
305
0.774289
5.009833
false
false
false
false
Egibide-PROGRAMACION/kotlin
03_ejemplos/EjemploSQLite/src/app.kt
1
1351
import java.sql.Connection import java.sql.DriverManager import java.sql.SQLException /** * Created by widemos on 26/5/17. */ fun main(args: Array<String>) { // Conectar var conexion: Connection? = null try { val controlador = "org.sqlite.JDBC" val cadenaconex = "jdbc:sqlite:corredores.sqlite" Class.forName(controlador) conexion = DriverManager.getConnection(cadenaconex) } catch (ex: ClassNotFoundException) { println("No se ha podido cargar el driver JDBC") } catch (ex: SQLException) { println("Error de conexión") } // Leer datos val lista = ArrayList<Corredor>() try { val st = conexion?.createStatement() val sql = "SELECT * FROM corredores" val rs = st?.executeQuery(sql) while (rs!!.next()) { val c = Corredor( rs.getLong("id"), rs.getString("nombre"), rs.getInt("dorsal"), rs.getInt("categoria") ) lista.add(c) } } catch (ex: SQLException) { println("Error al recuperar los datos") } // Mostrar los datos println("Recuperados: ${lista.size} registros") for (corredor in lista) { println(corredor) } // Desconectar conexion?.close() }
apache-2.0
74b0df5f2cae6dd42b178b26e92b3c16
21.5
59
0.562222
3.792135
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/newProject/ui/RsNewProjectPanel.kt
2
7534
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.newProject.ui import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionToolbarPosition import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.ui.MessageType import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.ui.ColoredListCellRenderer import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.ToolbarDecorator import com.intellij.ui.components.JBList import com.intellij.ui.components.Link import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.gridLayout.VerticalAlign import com.intellij.util.ui.JBUI import org.rust.cargo.project.settings.ui.RustProjectSettingsPanel import org.rust.cargo.toolchain.tools.Cargo import org.rust.cargo.toolchain.tools.cargo import org.rust.ide.newProject.ConfigurationData import org.rust.ide.newProject.RsCustomTemplate import org.rust.ide.newProject.RsGenericTemplate import org.rust.ide.newProject.RsProjectTemplate import org.rust.ide.newProject.state.RsUserTemplatesState import org.rust.ide.notifications.showBalloon import org.rust.openapiext.UiDebouncer import org.rust.openapiext.fullWidthCell import org.rust.stdext.unwrapOrThrow import javax.swing.DefaultListModel import javax.swing.JList import javax.swing.ListSelectionModel import kotlin.math.min class RsNewProjectPanel( private val showProjectTypeSelection: Boolean, private val updateListener: (() -> Unit)? = null ) : Disposable { private val rustProjectSettings = RustProjectSettingsPanel(updateListener = updateListener) private val cargo: Cargo? get() = rustProjectSettings.data.toolchain?.cargo() private val defaultTemplates: List<RsProjectTemplate> = listOf( RsGenericTemplate.CargoBinaryTemplate, RsGenericTemplate.CargoLibraryTemplate, RsCustomTemplate.ProcMacroTemplate, RsCustomTemplate.WasmPackTemplate ) private val userTemplates: List<RsCustomTemplate> get() = RsUserTemplatesState.getInstance().templates.map { RsCustomTemplate(it.name, it.url) } private val templateListModel: DefaultListModel<RsProjectTemplate> = JBList.createDefaultListModel(defaultTemplates + userTemplates) private val templateList: JBList<RsProjectTemplate> = JBList(templateListModel).apply { selectionMode = ListSelectionModel.SINGLE_SELECTION selectedIndex = 0 addListSelectionListener { update() } cellRenderer = object : ColoredListCellRenderer<RsProjectTemplate>() { override fun customizeCellRenderer( list: JList<out RsProjectTemplate>, value: RsProjectTemplate, index: Int, selected: Boolean, hasFocus: Boolean ) { icon = value.icon append(value.name) if (value is RsCustomTemplate) { append(" ") append(value.shortLink, SimpleTextAttributes.GRAYED_ATTRIBUTES) } } } } private val selectedTemplate: RsProjectTemplate get() = templateList.selectedValue private val templateToolbar: ToolbarDecorator = ToolbarDecorator.createDecorator(templateList) .setToolbarPosition(ActionToolbarPosition.BOTTOM) .setPreferredSize(JBUI.size(0, 125)) .disableUpDownActions() .setAddAction { AddUserTemplateDialog().show() updateTemplatesList() } .setRemoveAction { val customTemplate = selectedTemplate as? RsCustomTemplate ?: return@setRemoveAction RsUserTemplatesState.getInstance().templates .removeIf { it.name == customTemplate.name } updateTemplatesList() } .setRemoveActionUpdater { selectedTemplate !in defaultTemplates } private var needInstallCargoGenerate = false @Suppress("DialogTitleCapitalization") private val downloadCargoGenerateLink = Link("Install cargo-generate using Cargo") { val cargo = cargo ?: return@Link object : Task.Modal(null, "Installing cargo-generate", true) { var exitCode: Int = Int.MIN_VALUE override fun onFinished() { if (exitCode != 0) { templateList.showBalloon("Failed to install cargo-generate", MessageType.ERROR, this@RsNewProjectPanel) } update() } override fun run(indicator: ProgressIndicator) { indicator.isIndeterminate = true cargo.installCargoGenerate(this@RsNewProjectPanel, listener = object : ProcessAdapter() { override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) { indicator.text = "Installing using Cargo..." indicator.text2 = event.text.trim() } override fun processTerminated(event: ProcessEvent) { exitCode = event.exitCode } }).unwrapOrThrow() } }.queue() }.apply { isVisible = false } private val updateDebouncer = UiDebouncer(this) val data: ConfigurationData get() = ConfigurationData(rustProjectSettings.data, selectedTemplate) fun attachTo(panel: Panel) = with(panel) { rustProjectSettings.attachTo(this) if (showProjectTypeSelection) { groupRowsRange(title = "Project Template", indent = false) { row { resizableRow() fullWidthCell(templateToolbar.createPanel()) .verticalAlign(VerticalAlign.FILL) } row { cell(downloadCargoGenerateLink) } } } update() } fun update() { updateDebouncer.run( onPooledThread = { when (selectedTemplate) { is RsGenericTemplate -> false is RsCustomTemplate -> cargo?.checkNeedInstallCargoGenerate() ?: false } }, onUiThread = { needInstall -> downloadCargoGenerateLink.isVisible = needInstall needInstallCargoGenerate = needInstall updateListener?.invoke() } ) } private fun updateTemplatesList() { val index: Int = templateList.selectedIndex with(templateListModel) { removeAllElements() defaultTemplates.forEach(::addElement) userTemplates.forEach(::addElement) } templateList.selectedIndex = min(index, templateList.itemsCount - 1) } @Throws(ConfigurationException::class) fun validateSettings() { rustProjectSettings.validateSettings() if (needInstallCargoGenerate) { @Suppress("DialogTitleCapitalization") throw ConfigurationException("cargo-generate is needed to create a project from a custom template") } } override fun dispose() { Disposer.dispose(rustProjectSettings) } }
mit
2b9171cf7217a18b8b03d7f18aa48f7b
35.396135
123
0.657154
5.392985
false
false
false
false
Undin/intellij-rust
toml/src/main/kotlin/org/rust/toml/inspections/CargoDependencyCrateVisitor.kt
3
4284
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.toml.inspections import org.rust.stdext.intersects import org.rust.toml.isDependencyKey import org.rust.toml.stringValue import org.toml.lang.psi.* import org.toml.lang.psi.ext.TomlLiteralKind import org.toml.lang.psi.ext.kind import org.toml.lang.psi.ext.name abstract class CargoDependencyCrateVisitor: TomlVisitor() { abstract fun visitDependency(dependency: DependencyCrate) override fun visitKeyValue(element: TomlKeyValue) { val table = element.parent as? TomlTable ?: return val depTable = DependencyTable.fromTomlTable(table) ?: return if (depTable !is DependencyTable.General) return val segment = element.key.segments.firstOrNull() ?: return val name = segment.name ?: return val value = element.value ?: return if (value is TomlLiteral && value.kind is TomlLiteralKind.String) { visitDependency(DependencyCrate(name, segment, mapOf("version" to value))) } else if (value is TomlInlineTable) { val pkg = value.getPackageKeyValue() val (originalNameElement, originalName) = when { pkg != null -> pkg.value to pkg.value?.stringValue else -> segment to name } if (originalName != null && originalNameElement != null) { visitDependency(DependencyCrate(originalName, originalNameElement, collectProperties(value))) } } } override fun visitTable(element: TomlTable) { val depTable = DependencyTable.fromTomlTable(element) ?: return if (depTable !is DependencyTable.Specific) return visitDependency(DependencyCrate(depTable.crateName, depTable.crateNameElement, collectProperties(element))) } } private fun collectProperties(owner: TomlKeyValueOwner): Map<String, TomlValue> { return owner.entries.mapNotNull { val name = it.key.name ?: return@mapNotNull null val value = it.value ?: return@mapNotNull null name to value }.toMap() } data class DependencyCrate( val crateName: String, val crateNameElement: TomlElement, val properties: Map<String, TomlValue> ) { /** * Is this crate from another source than crates.io? */ fun isForeign(): Boolean = properties.keys.intersects(FOREIGN_PROPERTIES) companion object { private val FOREIGN_PROPERTIES = listOf("git", "path", "registry") } } private sealed class DependencyTable { object General : DependencyTable() data class Specific(val crateName: String, val crateNameElement: TomlElement) : DependencyTable() companion object { fun fromTomlTable(table: TomlTable): DependencyTable? { val key = table.header.key ?: return null val segments = key.segments val dependencyNameIndex = segments.indexOfFirst { it.isDependencyKey } return when { // [dependencies], [x86.dev-dependencies], etc. dependencyNameIndex == segments.lastIndex -> General // [dependencies.crate] dependencyNameIndex != -1 -> { val pkg = table.getPackageKeyValue() val (nameElement, name) = when { pkg != null -> pkg.value to pkg.value?.stringValue else -> { val segment = segments.getOrNull(dependencyNameIndex + 1) segment to segment?.name } } if (nameElement != null && name != null) { Specific(name, nameElement) } else { null } } else -> null } } } } /** * Return the `package` key from a table, if present. * Example: * * ``` * [dependencies.foo] * <selection>package = "bar"</selection> * * [dependencies] * foo = { <selection>package = "bar"</selection> } * ``` */ private fun TomlKeyValueOwner.getPackageKeyValue(): TomlKeyValue? = entries.firstOrNull { it.key.segments.firstOrNull()?.name == "package" }
mit
b5004cc25855686b9d477de1b8850426
34.114754
115
0.613212
4.712871
false
false
false
false
mvarnagiris/expensius
models/src/test/kotlin/com/mvcoding/expensius/model/extensions/RemoteFilterExtensions.kt
1
1158
/* * Copyright (C) 2017 Mantas Varnagiris. * * 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. */ package com.mvcoding.expensius.model.extensions import com.mvcoding.expensius.model.RemoteFilter import com.mvcoding.expensius.model.ReportPeriod import com.mvcoding.expensius.model.ReportPeriod.MONTH import org.joda.time.DateTimeConstants fun anInterval(reportPeriod: ReportPeriod = MONTH) = reportPeriod.interval(System.currentTimeMillis() - DateTimeConstants.MILLIS_PER_DAY.toLong() * 30 * anInt(1000)) fun aRemoteFilter(reportPeriod: ReportPeriod = MONTH) = RemoteFilter(aUserId(), anInterval(reportPeriod)) fun RemoteFilter.withInterval(interval: org.joda.time.Interval) = copy(interval = interval)
gpl-3.0
8dbe8410e3e3cd99f88ddb0d2a667c39
47.291667
165
0.789292
4.226277
false
false
false
false
RSDT/Japp16
app/src/main/java/nl/rsdt/japp/jotial/maps/movement/MovementManager.kt
1
20187
package nl.rsdt.japp.jotial.maps.movement import android.content.SharedPreferences import android.graphics.BitmapFactory import android.graphics.Color import android.location.Location import android.os.Bundle import android.util.Pair import android.view.View import com.google.android.gms.location.LocationListener import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.LocationSource import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.google.android.gms.maps.model.PolylineOptions import com.google.android.material.snackbar.Snackbar import com.google.gson.Gson import com.google.gson.reflect.TypeToken import nl.rsdt.japp.R import nl.rsdt.japp.application.Japp import nl.rsdt.japp.application.JappPreferences import nl.rsdt.japp.jotial.data.bodies.AutoUpdateTaakPostBody import nl.rsdt.japp.jotial.data.structures.area348.AutoInzittendeInfo import nl.rsdt.japp.jotial.io.AppData import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied import nl.rsdt.japp.jotial.maps.locations.LocationProviderService import nl.rsdt.japp.jotial.maps.management.MarkerIdentifier import nl.rsdt.japp.jotial.maps.misc.AnimateMarkerTool import nl.rsdt.japp.jotial.maps.misc.LatLngInterpolator import nl.rsdt.japp.jotial.maps.wrapper.ICameraPosition import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap import nl.rsdt.japp.jotial.maps.wrapper.IMarker import nl.rsdt.japp.jotial.maps.wrapper.IPolyline import nl.rsdt.japp.jotial.net.apis.AutoApi import nl.rsdt.japp.service.LocationService import nl.rsdt.japp.service.ServiceManager import org.acra.ktx.sendWithAcra import retrofit2.Call import retrofit2.Callback import retrofit2.Response import kotlin.collections.ArrayList /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 2-8-2016 * Description... */ class MovementManager : ServiceManager.OnBindCallback<LocationService.LocationBinder>, LocationListener, SharedPreferences.OnSharedPreferenceChangeListener { private val MAX_SIZE_LONG_TAIL = 60 override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { if (key == JappPreferences.TAIL_LENGTH){ smallTailPoints.maxSize = JappPreferences.tailLength smallTail?.points = smallTailPoints hourTailPoints.maxSize = JappPreferences.tailLength hourTail?.points = hourTailPoints hourTailPoints.onremoveCallback = ::addToLongTail } if (key == JappPreferences.GPS_ACCURACY || key == JappPreferences.GPS_INTERVAL || key == JappPreferences.GPS_FASTEST_INTERVAL){ gpsAccuracy = JappPreferences.gpsAccuracy fastestInterval = JappPreferences.gpsFastestInterval locationInterval = JappPreferences.gpsInterval request?.let {service?.removeRequest(it)} request = LocationProviderService.LocationRequest(accuracy = gpsAccuracy, fastestInterval = fastestInterval, interval = locationInterval) request?.let {service?.addRequest(it)} } } private var gpsAccuracy = JappPreferences.gpsAccuracy private var fastestInterval: Long = JappPreferences.gpsInterval private var locationInterval: Long = JappPreferences.gpsFastestInterval private var service: LocationService? = null private var jotiMap: IJotiMap? = null private var marker: IMarker? = null private var smallTail: IPolyline? = null private val smallTailPoints: TailPoints<LatLng> = TailPoints(JappPreferences.tailLength) private var hourTail: IPolyline? = null private val hourTailPoints: TailPoints<LatLng> = TailPoints(MAX_SIZE_LONG_TAIL) private var bearing: Float = 0f private var lastLocation: Location? = null private var lastHourLocationTime: Long = System.currentTimeMillis() private var activeSession: FollowSession? = null private var deelgebied: Deelgebied? = null private var snackBarView: View? = null private var request: LocationProviderService.LocationRequest? = null private var listener: LocationService.OnResolutionRequiredListener? = null fun addToLongTail(location: LatLng, addedOn: Long){ if (lastHourLocationTime - addedOn > 60 * 60 * 1000){ lastHourLocationTime = addedOn hourTailPoints.add(location) hourTail?.points = hourTailPoints } } fun setListener(listener: LocationService.OnResolutionRequiredListener) { this.listener = listener } fun setSnackBarView(snackBarView: View) { this.snackBarView = snackBarView } fun newSession(jotiMap: IJotiMap,before: ICameraPosition, zoom: Float, aoa: Float): FollowSession? { if (activeSession != null) { activeSession!!.end() activeSession = null } activeSession = FollowSession(jotiMap,before, zoom, aoa) return activeSession } fun onCreate(savedInstanceState: Bundle?) { val list:ArrayList<Pair<LatLng,Long>>? = AppData.getObject<ArrayList<Pair<LatLng,Long>>>( STORAGE_KEY, object : TypeToken<ArrayList<Pair<LatLng,Long>>>() {}.type) if (list != null) { smallTailPoints.setPoints(list) smallTail?.points = smallTailPoints } JappPreferences.visiblePreferences.registerOnSharedPreferenceChangeListener(this) } fun onSaveInstanceState(saveInstanceState: Bundle?) { save() } override fun onLocationChanged(l: Location) { Japp.lastLocation = l var location = Japp.lastLocation?:l var nextLocation = Japp.lastLocation?:l do { onNewLocation(location) location = nextLocation nextLocation = Japp.lastLocation?:l } while(location != nextLocation) } fun onNewLocation(location: Location){ val ldeelgebied = deelgebied if (marker != null) { if (lastLocation != null) { bearing = lastLocation!!.bearingTo(location) /** * Animate the marker to the new position */ AnimateMarkerTool.animateMarkerToICS(marker, LatLng(location.latitude, location.longitude), LatLngInterpolator.Linear(), 1000) marker?.setRotation(bearing) } else { marker?.position = LatLng(location.latitude, location.longitude) } smallTailPoints.add(LatLng(location.latitude, location.longitude)) smallTail?.points = smallTailPoints } val refresh = if (ldeelgebied != null) { if (!ldeelgebied.containsLocation(location)) { true } else { false } } else { true } if (refresh) { deelgebied = Deelgebied.resolveOnLocation(location) if (deelgebied != null && snackBarView != null) { Snackbar.make(snackBarView!!, """Welkom in deelgebied ${deelgebied?.name}""", Snackbar.LENGTH_LONG).show() val coordinatesSmall: List<LatLng> = smallTailPoints smallTail?.remove() hourTail?.remove() smallTail = jotiMap!!.addPolyline( PolylineOptions() .width(3f) .color(getTailColor()?:Color.BLUE) .addAll(coordinatesSmall)) val coordinatesHour: List<LatLng> = smallTailPoints hourTail = jotiMap!!.addPolyline( PolylineOptions() .width(3f) .color(getTailColor()?:Color.BLUE) .addAll(coordinatesHour)) } } /** * Make the marker visible */ if (marker?.isVisible == false) { marker?.isVisible = true } updateAutoTaak(location) if (activeSession != null) { activeSession!!.onLocationChanged(location) } lastLocation = location } private fun getTailColor(): Int? { val color = deelgebied?.color return if (color != null) Color.rgb(255 - Color.red(color), 255 - Color.green(color), 255 - Color.blue(color)) else null } private fun updateAutoTaak(location: Location) { if (JappPreferences.autoTaak) { val autoApi = Japp.getApi(AutoApi::class.java) autoApi.getInfoById(JappPreferences.accountKey, JappPreferences.accountId).enqueue(object : Callback<AutoInzittendeInfo> { override fun onFailure(call: Call<AutoInzittendeInfo>, t: Throwable) { t.sendWithAcra() } override fun onResponse(call: Call<AutoInzittendeInfo>, response: Response<AutoInzittendeInfo>) { val newTaak = """${deelgebied?.name}${Japp.getString(R.string.automatisch)}""" if (deelgebied != null && newTaak.toLowerCase() != response.body()?.taak?.toLowerCase()) { val body: AutoUpdateTaakPostBody = AutoUpdateTaakPostBody.default body.setTaak(newTaak) autoApi.updateTaak(body).enqueue(object : Callback<Void> { override fun onFailure(call: Call<Void>, t: Throwable) { t.sendWithAcra() } override fun onResponse(call: Call<Void>, response: Response<Void>) { if (response.isSuccessful) { Snackbar.make(snackBarView!!, """taak upgedate: ${deelgebied?.name}""", Snackbar.LENGTH_LONG).show() } } }) } } }) } } override fun onBind(binder: LocationService.LocationBinder) { val service = binder.instance service.setListener(listener) service.add(this) request?.let { service.removeRequest(it) } request = LocationProviderService.LocationRequest(accuracy = gpsAccuracy, fastestInterval = fastestInterval, interval = locationInterval) request?.let {service.addRequest(it)} this.service = service } fun postResolutionResultToService(code: Int) { service?.handleResolutionResult(code) } fun requestLocationSettingRequest() { service?.restartLocationUpdates() } fun onMapReady(jotiMap: IJotiMap) { this.jotiMap = jotiMap val identifier = MarkerIdentifier.Builder() .setType(MarkerIdentifier.TYPE_ME) .add("icon", R.drawable.me.toString()) .create() marker = jotiMap.addMarker(Pair( MarkerOptions() .position(LatLng(52.021818, 6.059603)) .visible(false) .flat(true) .title(Gson().toJson(identifier)), BitmapFactory.decodeResource(Japp.instance!!.resources, R.drawable.me))) smallTail = jotiMap.addPolyline( PolylineOptions() .width(3f) .color(getTailColor()?:Color.BLUE)) hourTail = jotiMap.addPolyline( PolylineOptions() .width(3f) .color(getTailColor()?:Color.BLUE)) if (smallTailPoints.isNotEmpty()) { smallTail!!.points = smallTailPoints val last = smallTailPoints.size - 1 marker?.position = smallTailPoints[last] marker?.isVisible = true } } inner class FollowSession(private val jotiMap: IJotiMap, private val before: ICameraPosition, zoom: Float, aoa: Float) : LocationSource.OnLocationChangedListener { private var zoom = 19f private var aoa = 45f init { this.zoom = zoom this.aoa = aoa /** * Enable controls. */ jotiMap.uiSettings.setAllGesturesEnabled(true) jotiMap.uiSettings.setCompassEnabled(true) jotiMap.setOnCameraMoveStartedListener(GoogleMap.OnCameraMoveStartedListener { i -> if (i == GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE) { val position = jotiMap.previousCameraPosition setZoom(position.zoom) setAngleOfAttack(position.tilt) } }) } private fun setZoom(zoom: Float) { this.zoom = zoom } private fun setAngleOfAttack(aoa: Float) { this.aoa = aoa } override fun onLocationChanged(location: Location) { /** * Animate the camera to the new position */ if (JappPreferences.followNorth()) { jotiMap.cameraToLocation(true, location, zoom, aoa, 0f) } else { jotiMap.cameraToLocation(true, location, zoom, aoa, bearing) } } fun end() { /** * Save the settings of the session to the release_preferences */ JappPreferences.followZoom = zoom JappPreferences.setFollowAoa(aoa) /** * Disable controls */ jotiMap.uiSettings.setCompassEnabled(false) /** * Remove callback */ jotiMap.setOnCameraMoveStartedListener(null) /** * Move the camera to the before position */ //googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(before)); activeSession = null } } fun onResume() { request?.let { service?.addRequest(it) } } fun onPause() { request?.let { service?.removeRequest(it) } } private fun save() { val list1 = smallTailPoints.toArrayList() val list2 = hourTailPoints.toArrayList() val list3 = ArrayList<Pair<LatLng, Long>>() list3.addAll(list2) list3.addAll(list1) list3.sortBy { it.second } AppData.saveObjectAsJsonInBackground(list3, STORAGE_KEY) } fun onDestroy() { marker?.remove() smallTail?.remove() smallTail = null smallTailPoints.clear() hourTail?.remove() hourTailPoints.clear() hourTail = null if (jotiMap != null) { jotiMap = null } if (marker != null) { marker?.remove() marker = null } if (lastLocation != null) { lastLocation = null } if (activeSession != null) { activeSession = null } if (service != null) { service?.setListener(null) service?.remove(this) service = null } snackBarView = null } companion object { private val STORAGE_KEY = "TAIL" private val BUNDLE_KEY = "MovementManager" } } class TailPoints<T>(maxSize:Int) : List<T>{ private var list: ArrayList<T> = ArrayList() private var addedOn: MutableMap<T,Long> = HashMap() private var currentFirst = 0 var onremoveCallback: (T, Long) -> Unit= {element, timeAdded -> } internal var maxSize:Int = maxSize set(value) { rearrangeList() if (value < list.size){ val toRemove = list.subList(value, list.size) for (el in toRemove){ addedOn.remove(el) } list.removeAll(toRemove) } field = value } private fun toListIndex(tailIndex: Int):Int{ return (currentFirst + tailIndex) % maxSize } private fun toTailIndex(listIndex:Int ): Int{ return when { listIndex > currentFirst -> listIndex - currentFirst listIndex < currentFirst -> listIndex + currentFirst else -> 0 } } private fun incrementCurrentFirst() { currentFirst++ if (currentFirst >= maxSize){ currentFirst = 0 } } private fun rearrangeList(){ val first = list.subList(currentFirst, list.size) val second = list.subList(0, currentFirst) val result = ArrayList<T>() result.addAll(first) result.addAll(second) currentFirst = 0 list = result } override fun iterator(): kotlin.collections.Iterator<T> { return Iterator(0) } override val size: Int get() = list.size override fun contains(element: T): Boolean { return list.contains(element) } override fun containsAll(elements: Collection<T>): Boolean { return list.containsAll(elements) } override fun get(index: Int): T { return list[toListIndex(index)] } override fun indexOf(element: T): Int { return toTailIndex(list.indexOf(element)) } override fun isEmpty(): Boolean { return list.isEmpty() } override fun lastIndexOf(element: T): Int { return toTailIndex(list.lastIndexOf(element)) } override fun subList(fromIndex: Int, toIndex: Int): List<T> { val fromIndexList = toListIndex(fromIndex) val toIndexList = toListIndex(toIndex) return when { fromIndexList == toIndexList -> listOf() fromIndexList < toIndexList -> list.subList(fromIndexList, toIndexList) else -> { val result = list.subList(0, toIndexList) result.addAll(list.subList(fromIndexList, maxSize)) result } } } override fun listIterator(): ListIterator<T> { return Iterator(0) } override fun listIterator(index: Int): ListIterator<T> { return Iterator(index) } fun toArrayList():ArrayList<Pair<T, Long>>{ rearrangeList() return ArrayList(list.map {Pair(it, addedOn[it]!!)}) } fun add(element: T): Boolean { if (list.contains(element)){ return false } addedOn[element] = System.currentTimeMillis() return if (list.size < maxSize){ assert(currentFirst == 0) {currentFirst} list.add(element) } else { onremoveCallback(list[currentFirst], addedOn[list[currentFirst]]!!) addedOn.remove(list[currentFirst]) list[currentFirst] = element incrementCurrentFirst() true } } fun clear() { list.clear() addedOn.clear() currentFirst = 0 } fun setPoints(list: List<Pair<T,Long>>) { clear() if (list.size <= maxSize) { this.list.addAll(list.map { it.first }) list.forEach{ addedOn[it.first] = it.second } }else{ val overflow = list.size - maxSize val sublist = list.subList(overflow, list.size) this.list.addAll(sublist.map { it.first }) sublist.forEach { addedOn[it.first] = it.second } } assert(this.list.size <= maxSize) } inner class Iterator(private var currentIndex: Int): ListIterator<T> { override fun hasNext(): Boolean { return currentIndex + 1 < size } override fun next(): T { val nextE = get(currentIndex) currentIndex++ return nextE } override fun hasPrevious(): Boolean { return currentIndex - 1 > maxSize } override fun nextIndex(): Int { return currentIndex + 1 } override fun previous(): T { val prevE = get(currentIndex) currentIndex-- return prevE } override fun previousIndex(): Int { return currentIndex - 1 } } }
apache-2.0
6778df29a1be74e9a585c952189da270
31.402889
167
0.590974
5.041708
false
false
false
false
androidx/androidx
datastore/datastore-rxjava2/src/main/java/androidx/datastore/rxjava2/RxSharedPreferencesMigration.kt
3
4938
/* * 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.datastore.rxjava2 import android.annotation.SuppressLint import android.content.Context import androidx.datastore.core.DataMigration import androidx.datastore.migrations.SharedPreferencesMigration import androidx.datastore.migrations.SharedPreferencesView import io.reactivex.Single import kotlinx.coroutines.rx2.await @JvmDefaultWithCompatibility /** * Client implemented migration interface. **/ public interface RxSharedPreferencesMigration<T> { /** * Whether or not the migration should be run. This can be used to skip a read from the * SharedPreferences. * * @param currentData the most recently persisted data * @return a Single indicating whether or not the migration should be run. */ public fun shouldMigrate(currentData: T): Single<Boolean> { return Single.just(true) } /** * Maps SharedPreferences into T. Implementations should be idempotent * since this may be called multiple times. See [DataMigration.migrate] for more * information. The method accepts a SharedPreferencesView which is the view of the * SharedPreferences to migrate from (limited to [keysToMigrate] and a T which represent * the current data. The function must return the migrated data. * * If SharedPreferences is empty or does not contain any keys which you specified, this * callback will not run. * * @param sharedPreferencesView the current state of the SharedPreferences * @param currentData the most recently persisted data * @return a Single of the updated data */ public fun migrate(sharedPreferencesView: SharedPreferencesView, currentData: T): Single<T> } /** * RxSharedPreferencesMigrationBuilder for the RxSharedPreferencesMigration. */ @SuppressLint("TopLevelBuilder") public class RxSharedPreferencesMigrationBuilder<T> /** * Construct a RxSharedPreferencesMigrationBuilder. * * @param context the Context used for getting the SharedPreferences. * @param sharedPreferencesName the name of the SharedPreference from which to migrate. * @param rxSharedPreferencesMigration the user implemented migration for this SharedPreference. */ constructor( private val context: Context, private val sharedPreferencesName: String, private val rxSharedPreferencesMigration: RxSharedPreferencesMigration<T> ) { private var keysToMigrate: Set<String>? = null /** * Set the list of keys to migrate. The keys will be mapped to datastore.Preferences with * their same values. If the key is already present in the new Preferences, the key * will not be migrated again. If the key is not present in the SharedPreferences it * will not be migrated. * * This method is optional and if keysToMigrate is not set, all keys will be migrated from the * existing SharedPreferences. * * @param keys the keys to migrate * @return this */ @Suppress("MissingGetterMatchingBuilder") public fun setKeysToMigrate(vararg keys: String): RxSharedPreferencesMigrationBuilder<T> = apply { keysToMigrate = setOf(*keys) } /** * Build and return the DataMigration instance. * * @return the DataMigration. */ public fun build(): DataMigration<T> { return if (keysToMigrate == null) { SharedPreferencesMigration( context = context, sharedPreferencesName = sharedPreferencesName, migrate = { spView, curData -> rxSharedPreferencesMigration.migrate(spView, curData).await() }, shouldRunMigration = { curData -> rxSharedPreferencesMigration.shouldMigrate(curData).await() } ) } else { SharedPreferencesMigration( context = context, sharedPreferencesName = sharedPreferencesName, migrate = { spView, curData -> rxSharedPreferencesMigration.migrate(spView, curData).await() }, keysToMigrate = keysToMigrate!!, shouldRunMigration = { curData -> rxSharedPreferencesMigration.shouldMigrate(curData).await() } ) } } }
apache-2.0
c1d00eb894694d8c11581cad81352d94
37.27907
98
0.688538
5.338378
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/badges/self/none/BecomeASustainerViewModel.kt
1
1512
package org.thoughtcrime.securesms.badges.self.none import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.kotlin.subscribeBy import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.components.settings.app.subscription.MonthlyDonationRepository import org.thoughtcrime.securesms.util.livedata.Store class BecomeASustainerViewModel(subscriptionsRepository: MonthlyDonationRepository) : ViewModel() { private val store = Store(BecomeASustainerState()) val state: LiveData<BecomeASustainerState> = store.stateLiveData private val disposables = CompositeDisposable() init { disposables += subscriptionsRepository.getSubscriptions().subscribeBy( onError = { Log.w(TAG, "Could not load subscriptions.") }, onSuccess = { subscriptions -> store.update { it.copy(badge = subscriptions.firstOrNull()?.badge) } } ) } override fun onCleared() { disposables.clear() } companion object { private val TAG = Log.tag(BecomeASustainerViewModel::class.java) } class Factory(private val subscriptionsRepository: MonthlyDonationRepository) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return modelClass.cast(BecomeASustainerViewModel(subscriptionsRepository))!! } } }
gpl-3.0
9f2095fd6b360aa91a580c3bd1fb5dcd
32.6
109
0.767857
4.754717
false
false
false
false
androidx/androidx
compose/material/material-ripple/src/androidMain/kotlin/androidx/compose/material/ripple/RippleHostView.android.kt
3
16728
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material.ripple import android.content.Context import android.content.res.ColorStateList import android.graphics.Rect import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.graphics.drawable.RippleDrawable import android.os.Build import android.view.View import android.view.animation.AnimationUtils import androidx.annotation.DoNotInline import androidx.annotation.RequiresApi import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.ui.geometry.Size import androidx.compose.ui.geometry.toRect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toAndroidRect import androidx.compose.ui.graphics.toArgb import java.lang.reflect.Method /** * Empty [View] that hosts a [RippleDrawable] as its background. This is needed as * [RippleDrawable]s cannot currently be drawn directly to a [android.graphics.RenderNode] * (b/184760109), so instead we rely on [View]'s internal implementation to draw to the * background [android.graphics.RenderNode]. * * A [RippleContainer] is used to manage and assign RippleHostViews when needed - see * [RippleContainer.getRippleHostView]. */ internal class RippleHostView( context: Context ) : View(context) { /** * View related configuration */ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { setMeasuredDimension(0, 0) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { // noop } override fun refreshDrawableState() { // We don't want the View to manage the drawable state, so avoid updating the ripple's // state (via View.mBackground) when we lose window focus, or other events. } /** * A [RippleDrawable] cannot be dynamically changed between bounded / unbounded states - as a * result we need to create a new instance when we need to draw a different type. * Alternatively we could maintain both a bounded and unbounded instance, but we would still * need to reset state for both, and change what the view's background is - so it doesn't * help us out that much. */ private var ripple: UnprojectedRipple? = null private var bounded: Boolean? = null /** * The last time in millis that we called [setRippleState], needed to ensure that we don't * instantly fade out if [setRippleState] is called on the exact same millisecond twice. */ private var lastRippleStateChangeTimeMillis: Long? = null private var resetRippleRunnable: Runnable? = null /** * Creates a new [UnprojectedRipple] and assigns it to [ripple]. * * @param bounded whether the [UnprojectedRipple] is bounded (fills the bounds of the * containing canvas, or unbounded (starts from the center of the canvas and fills outwards * in a circle that may go outside the bounds of the canvas). */ private fun createRipple(bounded: Boolean) { ripple = UnprojectedRipple(bounded).apply { // Set the ripple to be the view's background - this will internally set the ripple's // Drawable.Callback callback to equal this view so there is no need to manage this // separately. background = this } } /** * Callback invoked when the underlying [RippleDrawable] requests to be * invalidated - this callback should end up triggering a re-draw in the owning ripple instance. */ private var onInvalidateRipple: (() -> Unit)? = null /** * Pass through any drawable invalidations to the owning ripple instance - the normal * [View.invalidate] circuitry won't trigger a re-draw / re-composition inside of Compose out * of the box. */ override fun invalidateDrawable(who: Drawable) { onInvalidateRipple?.invoke() } /** * Adds and starts drawing a ripple with the provided properties. * * @param onInvalidateRipple callback invoked when the ripple requests an invalidation */ fun addRipple( interaction: PressInteraction.Press, bounded: Boolean, size: Size, radius: Int, color: Color, alpha: Float, onInvalidateRipple: () -> Unit ) { // Create a new ripple if there is no existing ripple, or bounded has changed. // (Since this.bounded is initialized to `null`, technically the first check isn't // needed, but it might not survive refactoring). if (ripple == null || bounded != this.bounded) { createRipple(bounded) this.bounded = bounded } val ripple = ripple!! this.onInvalidateRipple = onInvalidateRipple updateRippleProperties(size, radius, color, alpha) if (bounded) { // Bounded ripples should animate from the press position ripple.setHotspot(interaction.pressPosition.x, interaction.pressPosition.y) } else { // Unbounded ripples should animate from the center of the ripple - in the framework // this change in spec was never made, so they currently animate from the press // position into a circle that starts at the center of the ripple, instead of // starting directly at the center. ripple.setHotspot( ripple.bounds.centerX().toFloat(), ripple.bounds.centerY().toFloat() ) } setRippleState(pressed = true) } /** * Removes the most recent ripple, causing it to start the 'end' animation. Note that this is * separate from immediately cancelling existing ripples - see [disposeRipple]. */ fun removeRipple() { setRippleState(pressed = false) } /** * Update the underlying [RippleDrawable] with the new properties. Note that changes to * [size] or [radius] while a ripple is animating will cause the animation to move to the UI * thread, so it is important to also provide the correct values in [addRipple]. */ fun updateRippleProperties( size: Size, radius: Int, color: Color, alpha: Float ) { val ripple = ripple ?: return // NOTE: if adding new properties here, make sure they are guarded with an equality check // (either here or internally in RippleDrawable). Many properties invalidate the ripple when // changed, which will lead to a call to updateRippleProperties again, which will cause // another invalidation, etc. ripple.trySetRadius(radius) ripple.setColor(color, alpha) val newBounds = size.toRect().toAndroidRect() // Drawing the background causes the view to update the bounds of the drawable // based on the view's bounds, so we need to adjust the view itself to match the // canvas' bounds. // These setters will no-op if there is no change, so no need for us to check for equality left = newBounds.left top = newBounds.top right = newBounds.right bottom = newBounds.bottom ripple.bounds = newBounds } /** * Remove existing callbacks and clear any currently drawing ripples. */ fun disposeRipple() { onInvalidateRipple = null if (resetRippleRunnable != null) { removeCallbacks(resetRippleRunnable) resetRippleRunnable!!.run() } else { ripple?.state = RestingState } val ripple = ripple ?: return ripple.setVisible(false, false) unscheduleDrawable(ripple) } /** * Calls [RippleDrawable.setState] depending on [pressed]. Also makes sure that the fade out * will not happen instantly if the enter and exit events happen to occur on the same * millisecond. */ private fun setRippleState(pressed: Boolean) { val currentTime = AnimationUtils.currentAnimationTimeMillis() resetRippleRunnable?.let { runnable -> removeCallbacks(runnable) runnable.run() } val timeSinceLastStateChange = currentTime - (lastRippleStateChangeTimeMillis ?: 0) // When fading out, if the exit happens on the same millisecond (as returned by // currentAnimationTimeMillis), RippleForeground will instantly fade out without showing // the minimum duration ripple. Handle this specific case by posting the exit event to // make sure it is shown for its minimum time, if the last state change was recent. // Since it is possible for currentAnimationTimeMillis to be different between here, and // when it is called inside RippleForeground, we post for any small difference just to be // safe. if (!pressed && timeSinceLastStateChange < MinimumRippleStateChangeTime) { resetRippleRunnable = Runnable { ripple?.state = RestingState resetRippleRunnable = null } postDelayed(resetRippleRunnable, ResetRippleDelayDuration) } else { val state = if (pressed) PressedState else RestingState ripple?.state = state } lastRippleStateChangeTimeMillis = currentTime } companion object { /** * Minimum time between moving to [PressedState] and [RestingState] - for values smaller * than this it is possible that the value of [AnimationUtils.currentAnimationTimeMillis] * might be different between where we check in [setRippleState], and where it is checked * inside [RippleDrawable] - so even if it appears different here, it might be the same * value inside [RippleDrawable]. As a result if the time is smaller than this, we post * the resting state change to be safe. */ private const val MinimumRippleStateChangeTime = 5L /** * Delay between moving to [PressedState] and [RestingState], to ensure that the move to * [RestingState] happens on a new value for [AnimationUtils.currentAnimationTimeMillis], * so the ripple will cleanly animate out instead of instantly cancelling. * * The actual value of this number doesn't matter, provided it is long enough that it is * guaranteed to happen on another frame / value for * [AnimationUtils.currentAnimationTimeMillis], and that it is short enough that it will * happen before the minimum ripple duration (225ms). */ private const val ResetRippleDelayDuration = 50L private val PressedState = intArrayOf( android.R.attr.state_pressed, android.R.attr.state_enabled ) private val RestingState = intArrayOf() } } /** * [RippleDrawable] that always returns `false` for [isProjected], so that it will always be drawn * in the owning [View]'s RenderNode, and not an ancestor node. This is only meaningful if the * owning [View]'s drawing is not clipped, which it won't be in Compose, so we can always return * `false` and just draw outside of the bounds if we need to. */ private class UnprojectedRipple(private val bounded: Boolean) : RippleDrawable( // Temporary default color that we will override later /* color */ ColorStateList.valueOf(android.graphics.Color.BLACK), /* content */null, // The color of the mask here doesn't matter - we just need a mask to draw the bounded ripple // against /* mask */ if (bounded) ColorDrawable(android.graphics.Color.WHITE) else null ) { /** * Store the ripple color so we can compare it later, as there is no way to get the currently * set color on the RippleDrawable itself. */ private var rippleColor: Color? = null /** * Store the ripple radius so we can compare it later - [getRadius] is only available on M+, * and we don't want to use reflection to read this below that. */ private var rippleRadius: Int? = null /** * Set a new [color] with [alpha] for this [RippleDrawable]. */ fun setColor(color: Color, alpha: Float) { val newColor = calculateRippleColor(color, alpha) if (rippleColor != newColor) { rippleColor = newColor setColor(ColorStateList.valueOf(newColor.toArgb())) } } private var projected = false /** * Return false (other than when calculating dirty bounds, see [getDirtyBounds]) to ensure * that this [RippleDrawable] will be drawn inside the owning [View]'s RenderNode, and not an * ancestor that supports projection. */ override fun isProjected(): Boolean { return projected } /** * On older API levels [isProjected] is used to control whether the dirty bounds (and hence * how the ripple is clipped) are bounded / unbounded. Since we turn off projection for this * ripple, if the ripple is unbounded we temporarily set isProjected to return true, so the * super implementation will return us the correct bounds for an unbounded ripple. */ override fun getDirtyBounds(): Rect { if (!bounded) { projected = true } val bounds = super.getDirtyBounds() projected = false return bounds } /** * Compat wrapper for [setRadius] which is only available on [Build.VERSION_CODES.M] and * above. This will try to call setMaxRadius below that if possible. */ fun trySetRadius(radius: Int) { if (rippleRadius != radius) { rippleRadius = radius if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { try { if (!setMaxRadiusFetched) { setMaxRadiusFetched = true setMaxRadiusMethod = RippleDrawable::class.java.getDeclaredMethod( "setMaxRadius", Int::class.javaPrimitiveType ) } setMaxRadiusMethod?.invoke(this, radius) } catch (e: Exception) { // Fail silently } } else { MRadiusHelper.setRadius(this, radius) } } } /** * Calculates the resulting [Color] from [color] with [alpha] applied, accounting for * differences in [RippleDrawable]'s behavior on different API levels. */ private fun calculateRippleColor(color: Color, alpha: Float): Color { // On API 21-27 the ripple animation is split into two sections - an overlay and an // animation on top - and 50% of the original alpha is used for both. Since these sections // don't always overlap, the actual alpha of the animation in parts can be 50% of the // original amount, so to ensure that the contrast is correct, and make the ripple alpha // match more closely with the provided value, we double it first. // Note that this is also consistent with MDC behavior. val transformedAlpha = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { alpha * 2 } else { // Note: above 28 the ripple alpha is clamped to 50%, so this might not be the // _actual_ alpha that is used in the ripple. alpha }.coerceAtMost(1f) return color.copy(alpha = transformedAlpha) } /** * Separate class to avoid verification errors for methods introduced in M. */ @RequiresApi(Build.VERSION_CODES.M) private object MRadiusHelper { /** * Sets the [radius] for the given [ripple]. */ @DoNotInline fun setRadius(ripple: RippleDrawable, radius: Int) { ripple.radius = radius } } companion object { /** * Cache RippleDrawable#setMaxRadius to avoid retrieving it more times than necessary */ private var setMaxRadiusMethod: Method? = null private var setMaxRadiusFetched = false } }
apache-2.0
b2236dd1ce6ee8d476569c7e30f16a3b
40.405941
100
0.65483
4.898389
false
false
false
false
androidx/androidx
wear/compose/compose-foundation/src/commonMain/kotlin/androidx/wear/compose/foundation/BasicCurvedText.kt
3
7748
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.foundation import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.layout.Measurable import androidx.compose.ui.layout.Placeable import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontSynthesis import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Constraints import kotlin.math.roundToInt import kotlin.math.sqrt /** * [basicCurvedText] is a component allowing developers to easily write curved text following * the curvature a circle (usually at the edge of a circular screen). * [basicCurvedText] can be only created within the [CurvedLayout] since it's not a not a * composable. * * @sample androidx.wear.compose.foundation.samples.CurvedAndNormalText * * @param text The text to display * @param modifier The [CurvedModifier] to apply to this curved text. * @param angularDirection Specify if the text is laid out clockwise or anti-clockwise, and if * those needs to be reversed in a Rtl layout. * If not specified, it will be inherited from the enclosing [curvedRow] or [CurvedLayout] * See [CurvedDirection.Angular]. * @param overflow How visual overflow should be handled. * @param style A @Composable factory to provide the style to use. This composable SHOULDN'T * generate any compose nodes. */ public fun CurvedScope.basicCurvedText( text: String, modifier: CurvedModifier = CurvedModifier, angularDirection: CurvedDirection.Angular? = null, overflow: TextOverflow = TextOverflow.Clip, style: @Composable () -> CurvedTextStyle = { CurvedTextStyle() } ) = add(CurvedTextChild( text, curvedLayoutDirection.copy(overrideAngular = angularDirection).absoluteClockwise(), style, overflow ), modifier) /** * [basicCurvedText] is a component allowing developers to easily write curved text following * the curvature a circle (usually at the edge of a circular screen). * [basicCurvedText] can be only created within the [CurvedLayout] since it's not a not a * composable. * * @sample androidx.wear.compose.foundation.samples.CurvedAndNormalText * * @param text The text to display * @param style A style to use. * @param modifier The [CurvedModifier] to apply to this curved text. * @param angularDirection Specify if the text is laid out clockwise or anti-clockwise, and if * those needs to be reversed in a Rtl layout. * If not specified, it will be inherited from the enclosing [curvedRow] or [CurvedLayout] * See [CurvedDirection.Angular]. * @param overflow How visual overflow should be handled. */ public fun CurvedScope.basicCurvedText( text: String, style: CurvedTextStyle, modifier: CurvedModifier = CurvedModifier, angularDirection: CurvedDirection.Angular? = null, overflow: TextOverflow = TextOverflow.Clip, ) = basicCurvedText(text, modifier, angularDirection, overflow) { style } internal class CurvedTextChild( val text: String, val clockwise: Boolean = true, val style: @Composable () -> CurvedTextStyle = { CurvedTextStyle() }, val overflow: TextOverflow ) : CurvedChild() { private lateinit var delegate: CurvedTextDelegate private lateinit var actualStyle: CurvedTextStyle // We create a compose-ui node so that we can attach a11y info. private lateinit var placeable: Placeable @Composable override fun SubComposition() { actualStyle = DefaultCurvedTextStyles + style() // Avoid recreating the delegate if possible, as it's expensive delegate = remember { CurvedTextDelegate() } delegate.UpdateFontIfNeeded( actualStyle.fontFamily, actualStyle.fontWeight, actualStyle.fontStyle, actualStyle.fontSynthesis ) // Empty compose-ui node to attach a11y info. Box(Modifier.semantics { contentDescription = text }) } override fun CurvedMeasureScope.initializeMeasure( measurables: Iterator<Measurable> ) { delegate.updateIfNeeded( text, clockwise, actualStyle.fontSize.toPx() ) // Size the compose-ui node reasonably. // We make the bounding rectangle sizes as the text, but cut the width (if needed) to the // point at which the circle crosses the middle of the side val height = delegate.textHeight.roundToInt() val maxWidth = sqrt(height * (radius - height / 4)) val width = delegate.textWidth.coerceAtMost(maxWidth).roundToInt() // Measure the corresponding measurable. placeable = measurables.next().measure(Constraints( minWidth = width, maxWidth = width, minHeight = height, maxHeight = height )) } override fun doEstimateThickness(maxRadius: Float): Float = delegate.textHeight override fun doRadialPosition( parentOuterRadius: Float, parentThickness: Float ): PartialLayoutInfo { val measureRadius = parentOuterRadius - delegate.baseLinePosition return PartialLayoutInfo( delegate.textWidth / measureRadius, parentOuterRadius, delegate.textHeight, measureRadius ) } private var parentSweepRadians: Float = 0f override fun doAngularPosition( parentStartAngleRadians: Float, parentSweepRadians: Float, centerOffset: Offset ): Float { this.parentSweepRadians = parentSweepRadians return super.doAngularPosition(parentStartAngleRadians, parentSweepRadians, centerOffset) } override fun DrawScope.draw() { with(delegate) { doDraw( layoutInfo!!, parentSweepRadians, overflow, actualStyle.color, actualStyle.background ) } } override fun (Placeable.PlacementScope).placeIfNeeded() = // clockwise doesn't matter, we have no content in placeable. place(placeable, layoutInfo!!, parentSweepRadians, clockwise = false) } internal expect class CurvedTextDelegate() { var textWidth: Float var textHeight: Float var baseLinePosition: Float fun updateIfNeeded( text: String, clockwise: Boolean, fontSizePx: Float ) @Composable fun UpdateFontIfNeeded( fontFamily: FontFamily?, fontWeight: FontWeight?, fontStyle: FontStyle?, fontSynthesis: FontSynthesis? ) fun DrawScope.doDraw( layoutInfo: CurvedLayoutInfo, parentSweepRadians: Float, overflow: TextOverflow, color: Color, background: Color ) }
apache-2.0
0cd2e35c0629987a046ebc2e74f8d0b5
35.205607
97
0.708957
4.806452
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/glfw/templates/GLFWNativeNSGL.kt
1
829
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.glfw.templates import org.lwjgl.generator.* import org.lwjgl.glfw.* import org.lwjgl.system.macosx.* val GLFWNativeNSGL = "GLFWNativeNSGL".nativeClass(packageName = GLFW_PACKAGE, nativeSubPath = "macosx", prefix = "GLFW", binding = GLFW_BINDING_DELEGATE) { documentation = "Native bindings to the GLFW library's NSGL native access functions." id( "GetNSGLContext", """ Returns the ${code("NSOpenGLContext")} of the specified GLFW window. Note: This function may be called from any thread. Access is not synchronized. """, GLFWwindow.IN("window", "the GLFW window"), returnDoc = "The ${code("NSOpenGLContext")} of the specified window, or nil if an error occurred.", since = "version 3.0" ) }
bsd-3-clause
4b38783bd510bc294ddfaf0a8efb242c
30.923077
155
0.722557
3.684444
false
false
false
false
edx/edx-app-android
OpenEdXMobile/src/main/java/org/edx/mobile/view/CourseDatesPageFragment.kt
1
22169
package org.edx.mobile.view import android.app.Activity import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import org.edx.mobile.BuildConfig.VERSION_NAME import org.edx.mobile.R import org.edx.mobile.base.BaseFragment import org.edx.mobile.databinding.FragmentCourseDatesPageBinding import org.edx.mobile.exception.ErrorMessage import org.edx.mobile.http.HttpStatus import org.edx.mobile.http.HttpStatusException import org.edx.mobile.http.notifications.FullScreenErrorNotification import org.edx.mobile.http.notifications.SnackbarErrorNotification import org.edx.mobile.interfaces.OnDateBlockListener import org.edx.mobile.model.CourseDatesCalendarSync import org.edx.mobile.model.api.EnrolledCoursesResponse import org.edx.mobile.model.course.CourseBannerInfoModel import org.edx.mobile.model.course.CourseComponent import org.edx.mobile.module.analytics.Analytics import org.edx.mobile.util.* import org.edx.mobile.view.adapters.CourseDatesAdapter import org.edx.mobile.view.dialog.AlertDialogFragment import org.edx.mobile.viewModel.CourseDateViewModel import org.edx.mobile.viewModel.ViewModelFactory class CourseDatesPageFragment : OfflineSupportBaseFragment(), BaseFragment.PermissionListener { private lateinit var errorNotification: FullScreenErrorNotification private lateinit var binding: FragmentCourseDatesPageBinding private lateinit var viewModel: CourseDateViewModel private var onDateItemClick: OnDateBlockListener = object : OnDateBlockListener { override fun onClick(link: String, blockId: String) { val component = courseManager.getComponentByIdFromAppLevelCache(courseData.courseId, blockId) if (blockId.isNotEmpty() && component != null) { environment.router.showCourseUnitDetail(this@CourseDatesPageFragment, REQUEST_SHOW_COURSE_UNIT_DETAIL, courseData, null, blockId, false) environment.analyticsRegistry.trackDatesCourseComponentTapped(courseData.courseId, component.id, component.type.toString().toLowerCase(), link) } else { showOpenInBrowserDialog(link) if (blockId.isNotEmpty()) { environment.analyticsRegistry.trackUnsupportedComponentTapped(courseData.courseId, blockId, link) } } } } private var courseData: EnrolledCoursesResponse = EnrolledCoursesResponse() private var isSelfPaced: Boolean = true private var isDeepLinkEnabled: Boolean = false private lateinit var calendarTitle: String private lateinit var accountName: String private lateinit var keyValMap: Map<String, CharSequence> private var isCalendarExist: Boolean = false private lateinit var loaderDialog: AlertDialogFragment companion object { @JvmStatic fun makeArguments(courseData: EnrolledCoursesResponse): Bundle { val courseBundle = Bundle() courseBundle.putSerializable(Router.EXTRA_COURSE_DATA, courseData) return courseBundle } } override fun isShowingFullScreenError(): Boolean { return errorNotification.isShowing } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_course_dates_page, container, false) return binding.root } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_SHOW_COURSE_UNIT_DETAIL && resultCode == Activity.RESULT_OK && data != null) { val outlineComp: CourseComponent? = courseManager.getCourseDataFromAppLevelCache(courseData.courseId) outlineComp?.let { navigateToCourseUnit(data, courseData, outlineComp) } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) permissionListener = this viewModel = ViewModelProvider(this, ViewModelFactory()).get(CourseDateViewModel::class.java) courseData = arguments?.getSerializable(Router.EXTRA_COURSE_DATA) as EnrolledCoursesResponse isSelfPaced = courseData.course.isSelfPaced calendarTitle = CalendarUtils.getCourseCalendarTitle(environment, courseData.course.name) accountName = CalendarUtils.getUserAccountForSync(environment) keyValMap = mapOf( AppConstants.PLATFORM_NAME to environment.config.platformName, AppConstants.COURSE_NAME to calendarTitle ) errorNotification = FullScreenErrorNotification(binding.swipeContainer) loaderDialog = AlertDialogFragment.newInstance(R.string.title_syncing_calendar, R.layout.alert_dialog_progress) binding.swipeContainer.setOnRefreshListener { // Hide the progress bar as swipe layout has its own progress indicator binding.loadingIndicator.loadingIndicator.visibility = View.GONE errorNotification.hideError() viewModel.fetchCourseDates(courseID = courseData.courseId, forceRefresh = true, showLoader = false, isSwipeRefresh = true) } UiUtils.setSwipeRefreshLayoutColors(binding.swipeContainer) initObserver() } override fun onResume() { super.onResume() viewModel.fetchCourseDates(courseID = courseData.courseId, forceRefresh = false, showLoader = true, isSwipeRefresh = false) } private fun initObserver() { viewModel.showLoader.observe(viewLifecycleOwner, Observer { showLoader -> binding.loadingIndicator.loadingIndicator.visibility = if (showLoader) View.VISIBLE else View.GONE }) viewModel.bannerInfo.observe(viewLifecycleOwner, Observer { initDatesBanner(it) }) viewModel.syncLoader.observe(viewLifecycleOwner, Observer { syncLoader -> if (syncLoader) { loaderDialog.isCancelable = false loaderDialog.showNow(childFragmentManager, null) } else { checkIfCalendarExists() dismissLoader() } }) viewModel.courseDates.observe(viewLifecycleOwner, Observer { dates -> if (dates.courseDateBlocks.isNullOrEmpty()) { viewModel.setError(ErrorMessage.COURSE_DATES_CODE, HttpStatus.NO_CONTENT, getString(R.string.course_dates_unavailable_message)) } else { dates.organiseCourseDates() binding.rvDates.apply { layoutManager = LinearLayoutManager(context) adapter = CourseDatesAdapter(dates.courseDatesMap, onDateItemClick) } val outdatedCalenderId = CalendarUtils.isCalendarOutOfDate( requireContext(), accountName, calendarTitle, dates.courseDateBlocks ) if (outdatedCalenderId != -1L) { showCalendarOutOfDateDialog(outdatedCalenderId) } } }) viewModel.resetCourseDates.observe(viewLifecycleOwner, Observer { resetCourseDates -> if (resetCourseDates != null) { if (!CalendarUtils.isCalendarExists(contextOrThrow, accountName, calendarTitle)) { showShiftDateSnackBar(true) } } }) viewModel.errorMessage.observe(viewLifecycleOwner, Observer { errorMsg -> if (errorMsg != null) { if (errorMsg.throwable is HttpStatusException) { when (errorMsg.throwable.statusCode) { HttpStatus.UNAUTHORIZED -> { environment.router?.forceLogout(contextOrThrow, environment.analyticsRegistry, environment.notificationDelegate) return@Observer } else -> errorNotification.showError(contextOrThrow, errorMsg.throwable, -1, null) } } else { when (errorMsg.errorCode) { ErrorMessage.COURSE_DATES_CODE -> errorNotification.showError(contextOrThrow, errorMsg.throwable, -1, null) ErrorMessage.BANNER_INFO_CODE -> initDatesBanner(null) ErrorMessage.COURSE_RESET_DATES_CODE -> showShiftDateSnackBar(false) } } } }) viewModel.swipeRefresh.observe(viewLifecycleOwner, Observer { enableSwipeListener -> binding.swipeContainer.isRefreshing = enableSwipeListener }) } private fun showCalendarOutOfDateDialog(calendarId: Long) { val alertDialogFragment = AlertDialogFragment.newInstance(getString(R.string.title_calendar_out_of_date), getString(R.string.message_calendar_out_of_date), getString(R.string.label_update_now), { _: DialogInterface?, _: Int -> trackCalendarEvent(Analytics.Events.CALENDAR_SYNC_UPDATE, Analytics.Values.CALENDAR_SYNC_UPDATE) val newCalId = CalendarUtils.createOrUpdateCalendar( context = contextOrThrow, accountName = accountName, calendarTitle = calendarTitle ) viewModel.addOrUpdateEventsInCalendar( contextOrThrow, newCalId, courseData.courseId, courseData.course.name, isDeepLinkEnabled, true ) }, getString(R.string.label_remove_course_calendar), { _: DialogInterface?, _: Int -> trackCalendarEvent(Analytics.Events.CALENDAR_SYNC_REMOVE, Analytics.Values.CALENDAR_SYNC_REMOVE) deleteCalendar(calendarId) binding.switchSync.isChecked = false }) alertDialogFragment.isCancelable = false alertDialogFragment.show(childFragmentManager, null) } /** * Initialized dates info banner on CourseDatesPageFragment * * @param courseBannerInfo object of course deadline info */ private fun initDatesBanner(courseBannerInfo: CourseBannerInfoModel?) { if (courseBannerInfo == null || courseBannerInfo.hasEnded) { binding.banner.containerLayout.visibility = View.GONE binding.syncCalendarContainer.visibility = View.GONE return } ConfigUtil.checkCalendarSyncEnabled(environment.config, object : ConfigUtil.OnCalendarSyncListener { override fun onCalendarSyncResponse(response: CourseDatesCalendarSync) { if (!response.disabledVersions.contains(VERSION_NAME) && ((response.isSelfPlacedEnable && isSelfPaced) || (response.isInstructorPlacedEnable && !isSelfPaced))) { binding.syncCalendarContainer.visibility = View.VISIBLE isDeepLinkEnabled = response.isDeepLinkEnabled initializedSyncContainer() } } }) CourseDateUtil.setupCourseDatesBanner(view = binding.banner.root, isCourseDatePage = true, courseId = courseData.courseId, enrollmentMode = courseData.mode, isSelfPaced = isSelfPaced, screenName = Analytics.Screens.PLS_COURSE_DATES, analyticsRegistry = environment.analyticsRegistry, courseBannerInfoModel = courseBannerInfo, clickListener = View.OnClickListener { viewModel.resetCourseDatesBanner(courseID = courseData.courseId) }) } private fun initializedSyncContainer() { checkIfCalendarExists() binding.switchSync.setOnCheckedChangeListener { _, isChecked -> if (isChecked) { if (!CalendarUtils.permissions.any { permission -> PermissionsUtil.checkPermissions(permission, contextOrThrow) }) { askCalendarPermission() } else if (isCalendarExist.not()) { askForCalendarSync() } } else if (CalendarUtils.hasPermissions(context = contextOrThrow)) { val calendarId = CalendarUtils.getCalendarId(context = contextOrThrow, accountName = accountName, calendarTitle = calendarTitle) if (calendarId != -1L) { askCalendarRemoveDialog(calendarId) } } trackCalendarEvent(if (isChecked) Analytics.Events.CALENDAR_TOGGLE_ON else Analytics.Events.CALENDAR_TOGGLE_OFF, if (isChecked) Analytics.Values.CALENDAR_TOGGLE_ON else Analytics.Values.CALENDAR_TOGGLE_OFF) } } private fun checkIfCalendarExists() { isCalendarExist = CalendarUtils.isCalendarExists(context = contextOrThrow, accountName = accountName, calendarTitle = calendarTitle) binding.switchSync.isChecked = isCalendarExist } private fun askCalendarPermission() { val title: String = ResourceUtil.getFormattedString(resources, R.string.title_request_calendar_permission, AppConstants.PLATFORM_NAME, environment.config.platformName).toString() val message: String = ResourceUtil.getFormattedString(resources, R.string.message_request_calendar_permission, AppConstants.PLATFORM_NAME, environment.config.platformName).toString() val alertDialog = AlertDialogFragment.newInstance(title, message, getString(R.string.label_ok), { _: DialogInterface, _: Int -> PermissionsUtil.requestPermissions(PermissionsUtil.CALENDAR_PERMISSION_REQUEST, CalendarUtils.permissions, this@CourseDatesPageFragment) }, getString(R.string.label_do_not_allow), { _: DialogInterface?, _: Int -> trackCalendarEvent(Analytics.Events.CALENDAR_ACCESS_DONT_ALLOW, Analytics.Values.CALENDAR_ACCESS_DONT_ALLOW) binding.switchSync.isChecked = false }) alertDialog.isCancelable = false alertDialog.show(childFragmentManager, null) } private fun askForCalendarSync() { val title: String = ResourceUtil.getFormattedString(resources, R.string.title_add_course_calendar, AppConstants.COURSE_NAME, calendarTitle).toString() val message: String = ResourceUtil.getFormattedString(resources, R.string.message_add_course_calendar, keyValMap).toString() val alertDialog = AlertDialogFragment.newInstance(title, message, getString(R.string.label_ok), { _: DialogInterface, _: Int -> trackCalendarEvent(Analytics.Events.CALENDAR_ADD_OK, Analytics.Values.CALENDAR_ADD_OK) insertCalendarEvent() }, getString(R.string.label_cancel), { _: DialogInterface?, _: Int -> trackCalendarEvent(Analytics.Events.CALENDAR_ADD_CANCEL, Analytics.Values.CALENDAR_ADD_CANCEL) binding.switchSync.isChecked = false }) alertDialog.isCancelable = false alertDialog.show(childFragmentManager, null) } private fun showShiftDateSnackBar(isSuccess: Boolean) { val snackbarErrorNotification = SnackbarErrorNotification(binding.root) snackbarErrorNotification.showError( if (isSuccess) R.string.assessment_shift_dates_success_msg else R.string.course_dates_reset_unsuccessful, 0, 0, SnackbarErrorNotification.COURSE_DATE_MESSAGE_DURATION, null) environment.analyticsRegistry.trackPLSCourseDatesShift(courseData.courseId, courseData.mode, Analytics.Screens.PLS_COURSE_DATES, isSuccess) } private fun insertCalendarEvent() { val calendarId: Long = CalendarUtils.createOrUpdateCalendar( context = contextOrThrow, accountName = accountName, calendarTitle = calendarTitle ) // if app unable to create the Calendar for the course if (calendarId == -1L) { Toast.makeText( contextOrThrow, getString(R.string.adding_calendar_error_message), Toast.LENGTH_SHORT ).show() binding.switchSync.isChecked = false return } viewModel.addOrUpdateEventsInCalendar( contextOrThrow, calendarId, courseData.courseId, courseData.course.name, isDeepLinkEnabled, false ) } private fun dismissLoader() { loaderDialog.dismiss() if (viewModel.areEventsUpdated) { showCalendarUpdatedSnackbar() trackCalendarEvent( Analytics.Events.CALENDAR_UPDATE_SUCCESS, Analytics.Values.CALENDAR_UPDATE_SUCCESS ) } else { calendarAddedSuccessDialog() trackCalendarEvent( Analytics.Events.CALENDAR_ADD_SUCCESS, Analytics.Values.CALENDAR_ADD_SUCCESS ) } } private fun calendarAddedSuccessDialog() { isCalendarExist = true if (environment.courseCalendarPrefs.isSyncAlertPopupDisabled(courseData.course.name.replace(" ", "_"))) { showAddCalendarSuccessSnackbar() } else { environment.courseCalendarPrefs.setSyncAlertPopupDisabled(courseData.course.name.replace(" ", "_"), true) val message: String = ResourceUtil.getFormattedString(resources, R.string.message_for_alert_after_course_calendar_added, AppConstants.COURSE_NAME, calendarTitle).toString() AlertDialogFragment.newInstance(null, message, getString(R.string.label_done), { _: DialogInterface, _: Int -> trackCalendarEvent(Analytics.Events.CALENDAR_CONFIRMATION_DONE, Analytics.Values.CALENDAR_CONFIRMATION_DONE) }, getString(R.string.label_view_events), { _: DialogInterface?, _: Int -> trackCalendarEvent(Analytics.Events.CALENDAR_VIEW_EVENTS, Analytics.Values.CALENDAR_VIEW_EVENTS) CalendarUtils.openCalendarApp(this) }).show(childFragmentManager, null) } } private fun showAddCalendarSuccessSnackbar() { val snackbarErrorNotification = SnackbarErrorNotification(binding.root) snackbarErrorNotification.showError(R.string.message_after_course_calendar_added, 0, R.string.label_close, SnackbarErrorNotification.COURSE_DATE_MESSAGE_DURATION) { snackbarErrorNotification.hideError() } } private fun askCalendarRemoveDialog(calendarId: Long) { val title: String = ResourceUtil.getFormattedString(resources, R.string.title_remove_course_calendar, AppConstants.COURSE_NAME, calendarTitle).toString() val message: String = ResourceUtil.getFormattedString(resources, R.string.message_remove_course_calendar, keyValMap).toString() val alertDialog = AlertDialogFragment.newInstance(title, message, getString(R.string.label_remove), { _: DialogInterface, _: Int -> trackCalendarEvent(Analytics.Events.CALENDAR_REMOVE_OK, Analytics.Values.CALENDAR_REMOVE_OK) deleteCalendar(calendarId) }, getString(R.string.label_cancel), { _: DialogInterface?, _: Int -> trackCalendarEvent(Analytics.Events.CALENDAR_REMOVE_CANCEL, Analytics.Values.CALENDAR_REMOVE_CANCEL) binding.switchSync.isChecked = true }) alertDialog.isCancelable = false alertDialog.show(childFragmentManager, null) } private fun deleteCalendar(calendarId: Long) { CalendarUtils.deleteCalendar(context = contextOrThrow, calendarId = calendarId) isCalendarExist = false showCalendarRemovedSnackbar() trackCalendarEvent(Analytics.Events.CALENDAR_REMOVE_SUCCESS, Analytics.Values.CALENDAR_REMOVE_SUCCESS) } private fun showOpenInBrowserDialog(link: String) { AlertDialogFragment.newInstance(null, getString(R.string.assessment_not_available), getString(R.string.assessment_view_on_web), { _: DialogInterface, _: Int -> BrowserUtil.open(activity, link, true) }, getString(R.string.label_cancel), null).show(childFragmentManager, null) } override fun onPermissionGranted(permissions: Array<out String>?, requestCode: Int) { askForCalendarSync() trackCalendarEvent(Analytics.Events.CALENDAR_ACCESS_OK, Analytics.Values.CALENDAR_ACCESS_OK) } override fun onPermissionDenied(permissions: Array<out String>?, requestCode: Int) { binding.switchSync.isChecked = false trackCalendarEvent(Analytics.Events.CALENDAR_ACCESS_DONT_ALLOW, Analytics.Values.CALENDAR_ACCESS_DONT_ALLOW) } private fun trackCalendarEvent(eventName: String, biValue: String) { environment.analyticsRegistry.trackCalendarEvent( eventName, biValue, courseData.courseId, courseData.mode, isSelfPaced, viewModel.getSyncingCalendarTime() ) viewModel.resetSyncingCalendarTime() } }
apache-2.0
5a62ba73f2017ac5a6286a613b4d5f16
47.616228
190
0.652758
5.558927
false
false
false
false
fcostaa/kotlin-microservice
server/src/main/kotlin/com/felipecosta/microservice/server/pagecontroller/PageController.kt
1
598
package com.felipecosta.microservice.server.pagecontroller import com.felipecosta.microservice.server.Request import com.felipecosta.microservice.server.renderer.Renderer import com.felipecosta.microservice.server.renderer.impl.DefaultRenderer abstract class PageController(private val renderer: Renderer = DefaultRenderer()) { var output: String = "" abstract fun doGet(request: Request) fun render(output: Any = emptyMap<String, Any>(), template: String = "", text: String = "") { this.output = if (text.isNotBlank()) text else renderer.render(output, template) } }
mit
7320a4724dd5c982b56858a79a809ebb
34.176471
97
0.754181
4.364964
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/news/NewsViewModel.kt
2
971
package me.proxer.app.news import io.reactivex.Single import io.reactivex.rxkotlin.plusAssign import me.proxer.app.base.PagedContentViewModel import me.proxer.app.util.extension.toInstantBP import me.proxer.library.api.PagingLimitEndpoint import me.proxer.library.entity.notifications.NewsArticle /** * @author Ruben Gees */ class NewsViewModel : PagedContentViewModel<NewsArticle>() { override val itemsOnPage = 15 override val dataSingle: Single<List<NewsArticle>> get() = super.dataSingle.doOnSuccess { if (page == 0) { it.firstOrNull()?.date?.toInstantBP()?.let { date -> preferenceHelper.lastNewsDate = date } } } override val endpoint: PagingLimitEndpoint<List<NewsArticle>> get() = api.notifications.news() .markAsRead(page == 0) init { disposables += bus.register(NewsNotificationEvent::class.java).subscribe() } }
gpl-3.0
90c388bc9038f09a0301611fe5c06fb3
28.424242
82
0.666323
4.516279
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/provider/storage/smiles/SmileManager.kt
2
537
package ru.fantlab.android.provider.storage.smiles import ru.fantlab.android.App import ru.fantlab.android.data.dao.model.Smile import java.io.IOException object SmileManager { private const val PATH = "smiles.json" private var ALL_SMILES: List<Smile>? = null fun load() { try { val stream = App.instance.assets.open(PATH) val smiles = SmileLoader.loadSmiles(stream) ALL_SMILES = smiles stream.close() } catch (e: IOException) { e.printStackTrace() } } fun getAll(): List<Smile>? { return ALL_SMILES } }
gpl-3.0
33bac7545a3d45aa6f9d7a99f8b04e13
19.692308
50
0.711359
3.016854
false
false
false
false
slegrand45/todomvc
examples/kotlin-react/src/utils/HttpUtil.kt
4
1273
package utils import org.w3c.fetch.RequestInit import org.w3c.xhr.XMLHttpRequest import kotlin.browser.window import kotlin.js.Json import kotlin.js.Promise import kotlin.js.json fun <T> makeRequest(method: String, url: String, body: Any? = null, parse: (dynamic) -> T): Promise<T?> { return Promise { resolve, reject -> window.fetch(url, object: RequestInit { override var method: String? = method override var headers: dynamic = json("Content-Type" to "application/json") override var body: dynamic = if (body != null) { JSON.stringify(body) } else { null } }).then { r -> if (method != "DELETE") { r.json().then { obj -> resolve(parse(obj)) } } else { resolve(null) } } } } fun makeSyncRequest(method: String, url: String, body: Any? = null): dynamic? { val xhr = XMLHttpRequest() xhr.open(method, url, false) xhr.setRequestHeader("Content-Type", "application/json") if (body != null) { xhr.send(JSON.stringify(body)) } else { xhr.send() } return JSON.parse(xhr.responseText) as dynamic }
mit
5df16d572367b365a6f3b9bbd245104c
25
105
0.555381
4.015773
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/search/SearchActivity.kt
2
4852
package ru.fantlab.android.ui.modules.search import android.content.Intent import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.widget.ArrayAdapter import com.evernote.android.state.State import com.google.android.material.tabs.TabLayout import com.google.zxing.integration.android.IntentIntegrator import kotlinx.android.synthetic.main.search_layout.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.FragmentPagerAdapterModel import ru.fantlab.android.data.dao.TabsCountStateModel import ru.fantlab.android.helper.AnimHelper import ru.fantlab.android.helper.ViewHelper import ru.fantlab.android.ui.adapter.FragmentsPagerAdapter import ru.fantlab.android.ui.base.BaseActivity import shortbread.Shortcut import java.text.NumberFormat import java.util.* @Shortcut(id = "search", icon = R.drawable.sb_search, shortLabelRes = R.string.search, rank = 1) class SearchActivity : BaseActivity<SearchMvp.View, SearchPresenter>(), SearchMvp.View { @State var tabsCountSet: HashSet<TabsCountStateModel> = LinkedHashSet<TabsCountStateModel>() private val numberFormat = NumberFormat.getNumberInstance() private val adapter: ArrayAdapter<String> by lazy { ArrayAdapter(this, android.R.layout.simple_list_item_1, presenter.getHints()) } override fun layout(): Int = R.layout.search_layout override fun isTransparent(): Boolean = false override fun canBack(): Boolean = true override fun providePresenter(): SearchPresenter = SearchPresenter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) title = "" pager.adapter = FragmentsPagerAdapter(supportFragmentManager, FragmentPagerAdapterModel.buildForSearch(this)) tabs.setupWithViewPager(pager) searchEditText.setAdapter(adapter) searchEditText.setOnItemClickListener { _, _, _, _ -> presenter.onSearchClicked(pager, searchEditText) } searchEditText.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { val text = s.toString() AnimHelper.animateVisibility(clear, text.isNotEmpty()) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } }) if (!tabsCountSet.isEmpty()) { tabsCountSet.forEach { setupTab(count = it.count, index = it.tabIndex) } } if (savedInstanceState == null && intent != null) { if (intent.hasExtra("search")) { searchEditText.setText(intent.getStringExtra("search")) presenter.onSearchClicked(pager, searchEditText) } } tabs.addOnTabSelectedListener(object : TabLayout.ViewPagerOnTabSelectedListener(pager) { override fun onTabReselected(tab: TabLayout.Tab) { super.onTabReselected(tab) onScrollTop(tab.position) } }) search.setOnClickListener { onSearchClicked() } clear.setOnClickListener { searchEditText.setText("") } scan_barcode.setOnClickListener { onScanBarcodeClicked() } searchEditText.setOnEditorActionListener { _, _, _ -> onSearchClicked() true } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data) result?.let { if (result.contents == null) { showMessage("Result", getString(R.string.scan_canceled)) } else { searchEditText.setText(result.contents) presenter.onSearchClicked(pager, searchEditText, true) pager.currentItem = 2 } } } fun onSearchClicked() { presenter.onSearchClicked(pager, searchEditText) } private fun onScanBarcodeClicked() { val integrator = IntentIntegrator(this) with(integrator) { setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES) setPrompt(getString(R.string.scan)) setCameraId(0) setBeepEnabled(false) setBarcodeImageEnabled(false) initiateScan() } } override fun onNotifyAdapter(query: String?) { if (query == null) adapter.notifyDataSetChanged() else adapter.add(query) } override fun onSetCount(count: Int, index: Int) { tabsCountSet.add(TabsCountStateModel(count = count, tabIndex = index)) setupTab(count, index) } private fun setupTab(count: Int, index: Int) { val textView = ViewHelper.getTabTextView(tabs, index) when (index) { 0 -> textView.text = String.format("%s(%s)", getString(R.string.authors), numberFormat.format(count.toLong())) 1 -> textView.text = String.format("%s(%s)", getString(R.string.works), numberFormat.format(count.toLong())) 2 -> textView.text = String.format("%s(%s)", getString(R.string.editions), numberFormat.format(count.toLong())) 3 -> textView.text = String.format("%s(%s)", getString(R.string.awards), numberFormat.format(count.toLong())) } } }
gpl-3.0
a4b4d835485eacf121c19f7b53895cee
33.664286
114
0.753092
3.872306
false
false
false
false
JakeWharton/Reagent
reagent-rxjava2/src/test/kotlin/reagent/rxjava2/MaybeRxToReagentTest.kt
1
837
package reagent.rxjava2 import kotlinx.coroutines.experimental.runBlocking import org.junit.Assert.fail import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertNull import kotlin.test.assertSame import io.reactivex.Maybe as RxMaybe class MaybeRxToReagentTest { @Test fun complete() = runBlocking { val value = RxMaybe.empty<Any>() .toReagent() .produce() assertNull(value) } @Test fun item() = runBlocking { val value = RxMaybe.just("Hello") .toReagent() .produce() assertEquals("Hello", value) } @Test fun error() = runBlocking { val exception = RuntimeException("Oops!") try { RxMaybe.error<Any>(exception) .toReagent() .produce() fail() } catch (t: Throwable) { assertSame(exception, t) } } }
apache-2.0
677ed1c8cefecdfab8c8f8fd5fc04831
21.621622
50
0.65233
3.929577
false
true
false
false
PropaFramework/Propa
src/main/kotlin/io/propa/framework/common/Common.kt
1
921
package io.propa.framework.common /** * Created by gbaldeck on 5/7/2017. */ internal fun String.camelToDashCase(): String { return this.replace(Regex("([a-z])([A-Z])"), { result -> val (g1: String, g2: String) = result.destructured "$g1-$g2" }) } internal fun String.getProperTagName(): String = if (this.indexOf("-") > 0) this.toLowerCase() else throwPropaException("The chosen tag name '$this' is not in the correct custom tag format.") fun jsObjectOf(vararg pairs: Pair<String, dynamic>): dynamic{ val obj: dynamic = Any() pairs.forEach { (key, value) -> obj[key] = value } return obj } fun jsObjectOf(map: Map<String, dynamic>): dynamic = jsObjectOf(*map.toList().toTypedArray()) fun <T> assertSafeCast(obj: Any): T{ @Suppress("UNCHECKED_CAST") return obj as T } fun isNullOrUndefined(value: dynamic) = value === undefined || value === null
mit
2e9151aa0e377dabd4294cb29a64d6c0
24.583333
95
0.646037
3.462406
false
false
false
false
firebase/snippets-android
perf/app/src/main/java/com/google/firebase/example/perf/kotlin/MainActivity.kt
1
5780
package com.google.firebase.example.perf.kotlin import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.google.firebase.example.perf.kotlin.model.ItemCache import com.google.firebase.example.perf.kotlin.model.User import com.google.firebase.ktx.Firebase import com.google.firebase.perf.FirebasePerformance import com.google.firebase.perf.ktx.performance import com.google.firebase.perf.ktx.trace import com.google.firebase.perf.metrics.AddTrace import com.google.firebase.remoteconfig.ktx.remoteConfig import devrel.firebase.google.com.firebaseoptions.R import java.io.DataOutputStream import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.URL class MainActivity : AppCompatActivity() { // [START perf_traced_create] @AddTrace(name = "onCreateTrace", enabled = true /* optional */) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } // [END perf_traced_create] fun basicTrace() { val cache = ItemCache() // [START perf_basic_trace_start] val myTrace = Firebase.performance.newTrace("test_trace") myTrace.start() // [END perf_basic_trace_start] // [START perf_basic_trace_increment] val item = cache.fetch("item") if (item != null) { myTrace.incrementMetric("item_cache_hit", 1) } else { myTrace.incrementMetric("item_cache_miss", 1) } // [END perf_basic_trace_increment] // [START perf_basic_trace_stop] myTrace.stop() // [END perf_basic_trace_stop] } fun traceCustomAttributes() { // [START perf_trace_custom_attrs] Firebase.performance.newTrace("test_trace").trace { // Update scenario. putAttribute("experiment", "A") // Reading scenario. val experimentValue = getAttribute("experiment") // Delete scenario. removeAttribute("experiment") // Read attributes. val traceAttributes = this.attributes } // [END perf_trace_custom_attrs] } fun disableWithConfig() { // [START perf_disable_with_config] // Setup remote config val config = Firebase.remoteConfig // You can uncomment the following two statements to permit more fetches when // validating your app, but you should comment out or delete these lines before // distributing your app in production. // val configSettings = remoteConfigSettings { // minimumFetchIntervalInSeconds = 3600 // } // config.setConfigSettingsAsync(configSettings) // Load in-app defaults from an XML file that sets perf_disable to false until you update // values in the Firebase Console // Observe the remote config parameter "perf_disable" and disable Performance Monitoring if true config.setDefaultsAsync(R.xml.remote_config_defaults) .addOnCompleteListener { task -> if (task.isSuccessful) { Firebase.performance.isPerformanceCollectionEnabled = !config.getBoolean("perf_disable") } else { // An error occurred while setting default parameters } } // [END perf_disable_with_config] } fun activateConfig() { // [START perf_activate_config] // Remote Config fetches and activates parameter values from the service val config = Firebase.remoteConfig config.fetch(3600) .continueWithTask { task -> if (!task.isSuccessful) { task.exception?.let { throw it } } config.activate() } .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Parameter values successfully activated // ... } else { // Handle errors } } // [END perf_activate_config] } @Throws(Exception::class) fun manualNetworkTrace() { val data = "badgerbadgerbadgerbadgerMUSHROOM!".toByteArray() // [START perf_manual_network_trace] val url = URL("https://www.google.com") val metric = Firebase.performance.newHttpMetric("https://www.google.com", FirebasePerformance.HttpMethod.GET) metric.trace { val conn = url.openConnection() as HttpURLConnection conn.doOutput = true conn.setRequestProperty("Content-Type", "application/json") try { val outputStream = DataOutputStream(conn.outputStream) outputStream.write(data) } catch (ignored: IOException) { } // Set HttpMetric attributes setRequestPayloadSize(data.size.toLong()) setHttpResponseCode(conn.responseCode) printStreamContent(conn.inputStream) conn.disconnect() } // [END perf_manual_network_trace] } fun piiExamples() { val trace = Firebase.performance.newTrace("trace") val user = User() // [START perf_attr_no_pii] trace.putAttribute("experiment", "A") // [END perf_attr_no_pii] // [START perf_attr_pii] trace.putAttribute("email", user.getEmailAddress()) // [END perf_attr_pii] } private fun printStreamContent(stream: InputStream) { // Unimplemented // ... } }
apache-2.0
6800bc6ceae39695ee88a6c7b882bca5
33.819277
112
0.593599
4.83682
false
true
false
false
rhdunn/xquery-intellij-plugin
src/lang-xproc/main/uk/co/reecedunn/intellij/plugin/xproc/lang/fileTypes/XProcFileIconPatcher.kt
1
1527
/* * Copyright (C) 2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xproc.lang.fileTypes import com.intellij.ide.FileIconPatcher import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import com.intellij.psi.xml.XmlFile import uk.co.reecedunn.intellij.plugin.xproc.lang.XProc import uk.co.reecedunn.intellij.plugin.xproc.resources.XProcIcons import javax.swing.Icon class XProcFileIconPatcher : FileIconPatcher { override fun patchIcon(baseIcon: Icon, file: VirtualFile?, flags: Int, project: Project?): Icon = when { project == null || file == null -> baseIcon else -> { (PsiManager.getInstance(project).findFile(file) as? XmlFile)?.rootTag?.let { if (it.namespace == XProc.NAMESPACE) { XProcIcons.FileType } else { null } } ?: baseIcon } } }
apache-2.0
44ab00477f0f517b3be0070d0388d865
37.175
108
0.690897
4.172131
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/step/interactor/StepNavigationInteractor.kt
2
8393
package org.stepik.android.domain.step.interactor import io.reactivex.Maybe import io.reactivex.Single import io.reactivex.rxkotlin.Maybes.zip import io.reactivex.rxkotlin.toObservable import org.stepik.android.domain.base.DataSourceType import org.stepik.android.domain.exam.interactor.ExamSessionDataInteractor import org.stepik.android.domain.exam.model.SessionData import ru.nobird.android.domain.rx.toMaybe import org.stepik.android.domain.lesson.model.LessonData import org.stepik.android.domain.lesson.repository.LessonRepository import org.stepik.android.domain.progress.repository.ProgressRepository import org.stepik.android.domain.section.repository.SectionRepository import org.stepik.android.domain.step.model.StepDirectionData import org.stepik.android.domain.step.model.StepNavigationDirection import org.stepik.android.domain.unit.repository.UnitRepository import org.stepik.android.model.Course import org.stepik.android.model.Lesson import org.stepik.android.model.Section import org.stepik.android.model.Step import org.stepik.android.model.Unit import org.stepik.android.view.course_content.model.RequiredSection import ru.nobird.android.domain.rx.filterSingle import ru.nobird.android.domain.rx.maybeFirst import java.util.EnumSet import javax.inject.Inject class StepNavigationInteractor @Inject constructor( private val sectionRepository: SectionRepository, private val unitRepository: UnitRepository, private val lessonRepository: LessonRepository, private val progressRepository: ProgressRepository, private val examSessionDataInteractor: ExamSessionDataInteractor ) { fun getStepNavigationDirections(step: Step, lessonData: LessonData): Single<Set<StepNavigationDirection>> = if (lessonData.unit == null || step.position in 2 until lessonData.lesson.steps.size.toLong()) { Single.just(EnumSet.noneOf(StepNavigationDirection::class.java)) } else { StepNavigationDirection .values() .toObservable() .filterSingle { isCanMoveInDirection(it, step, lessonData) } .reduce(EnumSet.noneOf(StepNavigationDirection::class.java)) { set, direction -> set.add(direction); set } .map { it as Set<StepNavigationDirection> } } fun getStepDirectionData(direction: StepNavigationDirection, step: Step, lessonData: LessonData): Maybe<StepDirectionData> = when { lessonData.unit == null || lessonData.section == null || lessonData.course == null || !isDirectionCompliesStepPosition(direction, step, lessonData.lesson) -> Maybe.empty() isDirectionCompliesUnitPosition(direction, lessonData.unit, lessonData.section) -> unitRepository .getUnit(lessonData.section.units[ when (direction) { StepNavigationDirection.NEXT -> lessonData.unit.position StepNavigationDirection.PREV -> lessonData.unit.position - 2 } ]) .flatMap { unit -> lessonRepository .getLesson(unit.lesson) .map { lesson -> lessonData.copy(unit = unit, lesson = lesson) } } else -> getSlicedSections(direction, lessonData.section, lessonData.course) .flatMapMaybe { sections -> sections .firstOrNull() { it.units.isNotEmpty() } .toMaybe() } .flatMap { section -> val unitId = when (direction) { StepNavigationDirection.NEXT -> section.units.first() StepNavigationDirection.PREV -> section.units.last() } unitRepository .getUnit(unitId) .flatMap { unit -> lessonRepository .getLesson(unit.lesson) .map { lesson -> lessonData.copy(section = section, unit = unit, lesson = lesson) } } } }.flatMap { val requiredSectionSource = if (it.section?.isRequirementSatisfied == false) { getRequiredSection(it.section.requiredSection).onErrorReturnItem(RequiredSection.EMPTY) } else { Maybe.just(RequiredSection.EMPTY) } val examSessionSource = if (it.section != null) { examSessionDataInteractor.getSessionData(it.section, DataSourceType.REMOTE).onErrorReturnItem(SessionData.EMPTY) } else { Single.just(SessionData.EMPTY) } zip( requiredSectionSource, examSessionSource.toMaybe() ) { requiredSection, examSessionData -> StepDirectionData(lessonData = it, requiredSection = requiredSection, examSessionData = examSessionData) } } private fun getRequiredSection(sectionId: Long): Maybe<RequiredSection> = sectionRepository .getSection(sectionId, DataSourceType.CACHE) .flatMap { section -> progressRepository .getProgresses(listOfNotNull(section.progress), primarySourceType = DataSourceType.REMOTE) .maybeFirst() .map { progress -> RequiredSection(section, progress) } } private fun isCanMoveInDirection(direction: StepNavigationDirection, step: Step, lessonData: LessonData): Single<Boolean> = when { lessonData.unit == null || lessonData.section == null || lessonData.course == null || !isDirectionCompliesStepPosition(direction, step, lessonData.lesson) -> Single.just(false) isDirectionCompliesUnitPosition(direction, lessonData.unit, lessonData.section) -> Single.just(true) else -> getSlicedSections(direction, lessonData.section, lessonData.course) .map { sections -> sections.any { it.units.isNotEmpty() } || direction == StepNavigationDirection.NEXT } } private fun isDirectionCompliesStepPosition(direction: StepNavigationDirection, step: Step, lesson: Lesson): Boolean = direction == StepNavigationDirection.PREV && step.position == 1L || direction == StepNavigationDirection.NEXT && step.position == lesson.steps.size.toLong() private fun isDirectionCompliesUnitPosition(direction: StepNavigationDirection, unit: Unit, section: Section): Boolean = direction == StepNavigationDirection.PREV && unit.position > 1 || direction == StepNavigationDirection.NEXT && unit.position < section.units.size private fun getSlicedSections(direction: StepNavigationDirection, section: Section, course: Course): Single<List<Section>> { val sectionIds = course.sections ?: return Single.just(emptyList()) val range = when (direction) { StepNavigationDirection.NEXT -> (section.position until sectionIds.size) StepNavigationDirection.PREV -> (0 until section.position - 1) } return sectionRepository .getSections(sectionIds.slice(range)) .map { sections -> when (direction) { StepNavigationDirection.NEXT -> sections StepNavigationDirection.PREV -> sections.asReversed() } } } }
apache-2.0
ee0fd9f3ff7b60f84813e8f15b31aaaa
43.178947
132
0.580126
5.861034
false
false
false
false
MrSugarCaney/DirtyArrows
src/main/kotlin/nl/sugcube/dirtyarrows/bow/BowManager.kt
1
5512
package nl.sugcube.dirtyarrows.bow import nl.sugcube.dirtyarrows.DirtyArrows import nl.sugcube.dirtyarrows.bow.ability.* import org.bukkit.event.EventHandler import org.bukkit.event.HandlerList import org.bukkit.event.Listener import org.bukkit.event.player.PlayerQuitEvent import java.util.logging.Level /** * Tracks all bow effects. Iterates over all registered bow types. * * @author SugarCaney */ open class BowManager(private val plugin: DirtyArrows): Iterable<BowType>, Listener { /** * Contains all available bows. */ private val bows = HashMap<BowType, BowAbility>() /** * Keeps track of all scheduled task IDs. Mapped from each bow type. */ private val tasks = HashMap<BowType, Int>() /** * Get all bow types that are registered. */ val registeredTypes: Set<BowType> get() = bows.keys /** * Loads all enabled bows. Re-evaluates on second call. */ fun reload() = with(plugin) { // Remove all registered bows, to overwrite with new ones. unload() loadAbilities() plugin.server.pluginManager.registerEvents(this@BowManager, plugin) bows.forEach { (bowType, ability) -> plugin.server.pluginManager.registerEvents(ability, plugin) // Cache task ID to be canceled on reload. val taskId = plugin.server.scheduler.scheduleSyncRepeatingTask(plugin, ability, 0L, 1L) tasks[bowType] = taskId } logger.log(Level.INFO, "Loaded ${bows.size} bows.") } /** * Adds all enabled bow ability implementations to [bows]. */ private fun loadAbilities() { ExplodingBow(plugin).load() LightningBow(plugin).load() CluckyBow(plugin).load() EnderBow(plugin).load() TreeBow(plugin, TreeBow.Tree.OAK).load() TreeBow(plugin, TreeBow.Tree.SPRUCE).load() TreeBow(plugin, TreeBow.Tree.BIRCH).load() TreeBow(plugin, TreeBow.Tree.JUNGLE).load() TreeBow(plugin, TreeBow.Tree.ACACIA).load() TreeBow(plugin, TreeBow.Tree.DARK_OAK).load() BattyBow(plugin).load() NuclearBow(plugin).load() EnlightenedBow(plugin).load() RangedBow(plugin).load() MachineBow(plugin).load() VenomousBow(plugin).load() DisorientingBow(plugin).load() SwapBow(plugin).load() DrainBow(plugin).load() FlintAndBow(plugin).load() DisarmingBow(plugin).load() WitherBow(plugin).load() FireyBow(plugin).load() SlowBow(plugin).load() LevelBow(plugin).load() UndeadBow(plugin).load() WoodmanBow(plugin).load() StarvationBow(plugin).load() MultiBow(plugin).load() BombBow(plugin).load() DropBow(plugin).load() AirstrikeBow(plugin).load() MagmaticBow(plugin).load() AquaticBow(plugin).load() PullBow(plugin).load() ParalyzeBow(plugin).load() ClusterBow(plugin).load() AirshipBow(plugin).load() IronBow(plugin).load() CurseBow(plugin).load() RoundBow(plugin).load() FrozenBow(plugin).load() DrillBow(plugin).load() MusicBow(plugin).load() HomingBow(plugin).load() InterdimensionalBow(plugin).load() SingularityBow(plugin).load() PushyBow(plugin).load() RainbowBow(plugin).load() LaserBow(plugin).load() GrapplingBow(plugin).load() BouncyBow(plugin).load() MiningBow(plugin).load() UpBow(plugin).load() ShearBow(plugin).load() UndyingBow(plugin).load() FireworkBow(plugin).load() BridgeBow(plugin).load() MeteorBow(plugin).load() DraggyBow(plugin).load() BabyBow(plugin).load() SmokyBow(plugin).load() InvincibilityBow(plugin).load() BlockyBow(plugin).load() AcceleratingBow(plugin).load() FarmersBow(plugin).load() BowBow(plugin).load() MineBow(plugin).load() BlasterBow(plugin).load() } /** * Adds the given ability for this bow type if it is enabled in the configuration file. */ private fun BowAbility.load() { if (type.isEnabled(plugin)) { bows[type] = this } } /** * Unregisters all bows. */ fun unload() = with(plugin) { if (bows.isEmpty()) return // Unregister event handlers. bows.entries.forEach { (bowType, ability) -> HandlerList.unregisterAll(ability) tasks[bowType]?.let { server.scheduler.cancelTask(it) } } HandlerList.unregisterAll(this@BowManager) bows.clear() tasks.clear() } /** * Get the ability implementation for the bow with the given type. */ fun implementation(bowType: BowType) = bows[bowType] /** * Adds the given bow type when it is enabled in the config. */ private fun addIfEnabled(bowType: BowType, ability: BowAbility) { if (plugin.config.getBoolean(bowType.enabledNode)) { bows[bowType] = ability } } /** * @see implementation */ operator fun get(bowType: BowType) = implementation(bowType) override fun iterator() = bows.keys.iterator() @EventHandler fun playerQuits(event: PlayerQuitEvent) { val player = event.player bows.values.forEach { it.removeFromCostRequirementsCache(player) } } }
gpl-3.0
8e4ff0f0be0edd51d7eed61560806907
29.291209
99
0.613208
4.110365
false
false
false
false
MrSugarCaney/DirtyArrows
src/main/kotlin/nl/sugcube/dirtyarrows/util/Combat.kt
1
1471
package nl.sugcube.dirtyarrows.util import kotlin.math.ceil import kotlin.math.roundToInt import kotlin.random.Random /** * Rolls whether a hit should be critical. */ fun rollCritical(chance: Double = 0.25) = Random.nextDouble() < chance /** * Calculates the amount of extra bonus damage (additive) that must be added for a critical hit. */ fun criticalDamage(baseDamage: Double): Double { val max = (baseDamage / 2.0).roundToInt() + 1 return Random.nextInt(0, max).toDouble() } /** * Calculates how many damage an arrow should do, based on vanilla behaviour. * * @param arrowVelocity * How quickly the arrow flies (velocity length). * @param criticalHitChance * How much chance there is for the damage to be critical. * @param powerLevel * The power level enchantment of the bow, or 0 for now power level. * @return The damage to deal. */ fun arrowDamage(arrowVelocity: Double, criticalHitChance: Double = 0.25, powerLevel: Int = 0): Double { val baseDamage = ceil(2.0 * arrowVelocity) val powerMultiplier = powerDamageMultiplier(powerLevel) val criticalDamage = if (rollCritical(criticalHitChance)) criticalDamage(baseDamage) else 0.0 return (baseDamage + criticalDamage) * powerMultiplier } /** * With how much to multiply arrow damage given the power enchantment level. */ fun powerDamageMultiplier(powerLevel: Int = 0) = when (powerLevel) { 0 -> 1.0 else -> 1 + 0.5 * (powerLevel + 1) }
gpl-3.0
b1505a28ba294d305e64c19ca86b8a78
32.454545
103
0.710401
3.860892
false
false
false
false
walleth/walleth
app/src/main/java/org/walleth/walletconnect/WalletConnectListApps.kt
1
6006
package org.walleth.walletconnect import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.* import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import coil.load import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.Types.newParameterizedType import kotlinx.android.synthetic.main.activity_list_nofab.* import kotlinx.android.synthetic.main.item_wc_app.view.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.koin.android.ext.android.inject import org.ligi.kaxt.setVisibility import org.walleth.R import org.walleth.base_activities.BaseSubActivity import org.walleth.data.AppDatabase val list = """ [ { "name": "Example dApp", "url": "https://example.walletconnect.org", "icon": "https://example.walletconnect.org/favicon.ico", "networks": ["1","4","5","100"] }, { "name": "ENS", "url": "https://app.ens.domains", "icon": "https://app.ens.domains/favicon-32x32.png", "networks": ["1","4","5","3"] }, { "name": "Etherscan", "url": "https://etherscan.io", "icon": "https://etherscan.io/images/brandassets/etherscan-logo-circle.png", "networks" : ["1"] }, { "name": "Etherscan", "url": "https://goerli.etherscan.io", "icon": "https://etherscan.io/images/brandassets/etherscan-logo-circle.png", "networks" : ["5"] }, { "name": "Gnosis safe", "url": "https://gnosis-safe.io/app", "networks": ["1"], "icon": "https://gnosis-safe.io/app/favicon.ico" }, { "name": "Gnosis safe", "url": "https://rinkeby.gnosis-safe.io/app/", "networks": ["4"], "icon": "https://rinkeby.gnosis-safe.io/app/favicon.ico" }, { "name": "ReMix IDE", "networks": [ "*" ], "url": "http://remix.ethereum.org", "icon": "https://raw.githubusercontent.com/ethereum/remix-ide/master/favicon.ico" }, { "name": "uniswap", "url": "https://app.uniswap.org", "networks": ["1"], "icon": "https://app.uniswap.org/./favicon.png" }, { "name": "zkSync", "url": "https://rinkeby.zksync.io", "networks": ["1"], "icon": "https://rinkeby.zksync.io/_nuxt/icons/icon_64x64.3fdd8f.png" }, { "name": "zkSync", "url": "https://wallet zksync.io", "networks": ["4"], "icon": "https://rinkeby.zksync.io/_nuxt/icons/icon_64x64.3fdd8f.png" }, { "name": "Other Apps", "url": "https://walletconnect.org/apps", "icon": "https://example.walletconnect.org/favicon.ico" } ] """.trimIndent() data class WalletConnectApp(val name: String, val url: String, val icon: String?, val networks: List<String>?) data class WalletConnectEnhancedApp(val name: String, val url: String, val icon: String?, val networks: String?) class WalletConnectListApps : BaseSubActivity() { val moshi: Moshi by inject() val appDatabase: AppDatabase by inject() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_list_nofab) supportActionBar?.subtitle = "WalletConnect Apps" val adapter: JsonAdapter<List<WalletConnectApp>> = moshi.adapter(newParameterizedType(List::class.java, WalletConnectApp::class.java)) lifecycleScope.launch(Dispatchers.Default) { val list = adapter.fromJson(list)!!.map { val networks = it.networks?.map { network -> val chainId = network.toBigIntegerOrNull() when { (chainId != null) -> appDatabase.chainInfo.getByChainId(chainId)?.name (network == "*") -> "All networks" else -> "Unknown" } }?.joinToString(", ") WalletConnectEnhancedApp(it.name, it.url, it.icon, networks) } lifecycleScope.launch(Dispatchers.Main) { recycler_view.layoutManager = LinearLayoutManager(this@WalletConnectListApps) recycler_view.adapter = WalletConnectAdapter(list) } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_manage_wc, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.menu_input_text -> true.also { showWalletConnectURLInputAlert() } else -> super.onOptionsItemSelected(item) } } class WalletConnectAppViewHolder(val view: View) : RecyclerView.ViewHolder(view) { fun bind(app: WalletConnectEnhancedApp) { view.app_name.text = app.name view.app_networks.text = app.networks view.app_networks.setVisibility(app.networks != null) app.icon?.let { view.session_icon.load(it) } view.session_card.setOnClickListener { view.context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(app.url)).apply { flags += Intent.FLAG_ACTIVITY_NEW_TASK }) } } } class WalletConnectAdapter(private val allFunctions: List<WalletConnectEnhancedApp>) : RecyclerView.Adapter<WalletConnectAppViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = WalletConnectAppViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_wc_app, parent, false)) override fun getItemCount() = allFunctions.size override fun onBindViewHolder(holder: WalletConnectAppViewHolder, position: Int) { holder.bind(allFunctions[position]) } }
gpl-3.0
52619b8db89463481770c51b7e6b4c2a
33.125
180
0.614885
4.022773
false
false
false
false
Tait4198/hi_pixiv
app/src/main/java/info/hzvtc/hipixiv/vm/fragment/IllustViewModel.kt
1
9113
package info.hzvtc.hipixiv.vm.fragment import android.content.Intent import android.support.design.widget.Snackbar import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.StaggeredGridLayoutManager import android.util.Log import com.google.gson.Gson import com.like.LikeButton import info.hzvtc.hipixiv.R import info.hzvtc.hipixiv.adapter.* import info.hzvtc.hipixiv.adapter.events.* import info.hzvtc.hipixiv.data.Account import info.hzvtc.hipixiv.databinding.FragmentListBinding import info.hzvtc.hipixiv.net.ApiService import info.hzvtc.hipixiv.pojo.illust.Illust import info.hzvtc.hipixiv.pojo.illust.IllustResponse import info.hzvtc.hipixiv.util.AppMessage import info.hzvtc.hipixiv.util.AppUtil import info.hzvtc.hipixiv.view.fragment.BaseFragment import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import java.net.SocketTimeoutException import javax.inject.Inject class IllustViewModel @Inject constructor(val apiService: ApiService,val gson: Gson) : BaseFragmentViewModel<BaseFragment<FragmentListBinding>, FragmentListBinding>(),ViewModelData<IllustResponse>{ var contentType : IllustAdapter.Type = IllustAdapter.Type.ILLUST var obsNewData : Observable<IllustResponse>? = null lateinit var account: Account private var allowLoadMore = true private var errorIndex = 0 private lateinit var adapter : IllustAdapter override fun initViewModel() { if(contentType == IllustAdapter.Type.MANGA){ val layoutManger = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL) mBind.recyclerView.layoutManager = layoutManger }else{ val layoutManger = GridLayoutManager(mView.context,2) layoutManger.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup(){ override fun getSpanSize(pos: Int): Int = if(adapter.getFull(pos)) 1 else layoutManger.spanCount } mBind.recyclerView.layoutManager = layoutManger } adapter = IllustAdapter(mView.context,contentType) adapter.setItemClick( itemClick = object : ItemClick { override fun itemClick(illust: Illust) { val intent = Intent(mView.getString(R.string.activity_content)) intent.putExtra(mView.getString(R.string.extra_json),gson.toJson(illust)) intent.putExtra(getString(R.string.extra_type),mView.getString(R.string.extra_type_illust)) ActivityCompat.startActivity(mView.context, intent, null) } } ) adapter.setItemLike(itemLike = object : ItemLike { override fun like(id: Int, itemIndex: Int,isRank: Boolean, likeButton: LikeButton) { postLikeOrUnlike(id, itemIndex,true,isRank,likeButton) } override fun unlike(id: Int,itemIndex : Int,isRank: Boolean,likeButton: LikeButton) { postLikeOrUnlike(id,itemIndex,false,isRank,likeButton) } }) mBind.srLayout.setColorSchemeColors(ContextCompat.getColor(mView.context, R.color.primary)) mBind.srLayout.setOnRefreshListener({ getData(obsNewData) }) mBind.recyclerView.addOnScrollListener(object : OnScrollListener() { override fun onBottom() { if(allowLoadMore){ getMoreData() } } override fun scrollUp(dy: Int) { getParent()?.showFab(false) } override fun scrollDown(dy: Int) { getParent()?.showFab(true) } }) mBind.recyclerView.adapter = adapter } override fun runView() { getData(obsNewData) } override fun getData(obs : Observable<IllustResponse>?){ if(obs != null){ Observable.just(obs) .doOnNext({ errorIndex = 0 }) .doOnNext({ if(obs != obsNewData) obsNewData = obs }) .doOnNext({ mBind.srLayout.isRefreshing = true }) .observeOn(Schedulers.io()) .flatMap({ observable -> observable }) .doOnNext({ illustResponse -> adapter.setNewData(illustResponse) }) .observeOn(AndroidSchedulers.mainThread()) .doOnNext({ illustResponse -> if(illustResponse.ranking.isNotEmpty()) rankingTopClick() }) .subscribe({ _ -> adapter.updateUI(true) },{ error -> mBind.srLayout.isRefreshing = false adapter.loadError() processError(error) },{ mBind.srLayout.isRefreshing = false }) } } override fun getMoreData(){ Observable.just(adapter.nextUrl?:"") .doOnNext({ errorIndex = 1 }) .doOnNext({ allowLoadMore = false }) .filter({ url -> !url.isNullOrEmpty() }) .observeOn(AndroidSchedulers.mainThread()) .doOnNext({ adapter.setProgress(true) }) .observeOn(Schedulers.io()) .flatMap({ account.obsToken(mView.context) }) .flatMap({ token -> apiService.getIllustNext(token,adapter.nextUrl?:"")}) .doOnNext({ illustResponse -> adapter.addMoreData(illustResponse) }) .observeOn(AndroidSchedulers.mainThread()) .doOnNext({ (content) -> if (content.size == 0) { AppMessage.toastMessageLong(mView.getString(R.string.no_more_data), mView.context) } }) .doOnNext({ illustResponse -> if(illustResponse.nextUrl.isNullOrEmpty()){ AppMessage.toastMessageLong(mView.getString(R.string.is_last_data), mView.context) } }) .subscribe({ _ -> adapter.setProgress(false) adapter.updateUI(false) },{ error-> adapter.setProgress(false) allowLoadMore = true processError(error) },{ allowLoadMore = true }) } private fun postLikeOrUnlike(illustId : Int,position : Int,isLike : Boolean,isRank : Boolean,likeButton: LikeButton){ account.obsToken(mView.context) .filter({ AppUtil.isNetworkConnected(mView.context) }) .flatMap({ token -> if(isLike){ return@flatMap apiService.postLikeIllust(token,illustId,"public") }else{ return@flatMap apiService.postUnlikeIllust(token,illustId) } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ adapter.updateBookmarked(position,isLike,isRank) },{ error -> processError(error) adapter.updateBookmarked(position,false,isRank) likeButton.isLiked = false },{ if(!AppUtil.isNetworkConnected(mView.context)){ adapter.updateBookmarked(position,false,isRank) likeButton.isLiked = false } }) } private fun rankingTopClick(){ adapter.setRankingTopClick(object : RankingTopClick { override fun itemClick(type: RankingType) { val intent = Intent(mView.getString(R.string.activity_ranking)) intent.putExtra(mView.getString(R.string.extra_string),type.value) ActivityCompat.startActivity(mView.context, intent, null) } }) } private fun processError(error : Throwable){ Log.e("Error",error.printStackTrace().toString()) if(AppUtil.isNetworkConnected(mView.context)){ val msg = if(error is SocketTimeoutException) mView.getString(R.string.load_data_timeout) else mView.getString(R.string.load_data_failed) Snackbar.make(getParent()?.getRootView()?:mBind.root.rootView, msg, Snackbar.LENGTH_LONG) .setAction(mView.getString(R.string.app_dialog_ok),{ if(errorIndex == 0){ getData(obsNewData) }else if(errorIndex == 1){ getMoreData() } }).show() } } }
mit
bcdc5cf44478cd1b4bf775aa318bdae5
41.386047
121
0.568748
5.292102
false
false
false
false
Cognifide/APM
app/aem/core/src/main/kotlin/com/cognifide/apm/core/endpoints/utils/RequestProcessor.kt
1
2855
/* * ========================LICENSE_START================================= * AEM Permission Management * %% * Copyright (C) 2013 Wunderman Thompson Technology * %% * 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. * =========================LICENSE_END================================== */ package com.cognifide.apm.core.endpoints.utils import com.cognifide.apm.core.endpoints.params.RequestParameter import com.cognifide.apm.core.endpoints.response.ErrorBody import com.cognifide.apm.core.endpoints.response.JsonObject import com.cognifide.apm.core.endpoints.response.ResponseEntity import com.cognifide.apm.core.utils.ServletUtils import org.apache.sling.api.SlingHttpServletRequest import org.apache.sling.api.SlingHttpServletResponse import org.apache.sling.api.resource.ResourceResolver import org.apache.sling.models.factory.MissingElementsException import org.apache.sling.models.factory.ModelFactory import javax.servlet.http.HttpServletResponse class RequestProcessor<F>(private val modelFactory: ModelFactory, private val formClass: Class<F>) { fun process(httpRequest: SlingHttpServletRequest, httpResponse: SlingHttpServletResponse, process: (form: F, resourceResolver: ResourceResolver) -> ResponseEntity<Any>) { try { val form = modelFactory.createModel(httpRequest, formClass) val response = process(form, httpRequest.resourceResolver) httpResponse.setStatus(response.statusCode) ServletUtils.writeJson(httpResponse, body(response.body)) } catch (e: MissingElementsException) { httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST) ServletUtils.writeJson(httpResponse, body(ErrorBody("Bad request", toErrors(e)))) } catch (e: Exception) { httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) ServletUtils.writeJson(httpResponse, body(ErrorBody(e.message ?: ""))) } } private fun toErrors(e: MissingElementsException) = e.missingElements.mapNotNull { it.element } .mapNotNull { it.getAnnotation(RequestParameter::class.java) } .map { "Missing required parameter: ${it.value}" } private fun body(body: Any) = if (body is JsonObject) body.toMap() else body }
apache-2.0
c70887dfaa312fa35af51f7348e98fb3
46.423729
100
0.696673
4.575321
false
false
false
false
GDGLima/CodeLab-Kotlin-Infosoft-2017
Infosoft2017/app/src/main/java/com/emedinaa/infosoft2017/MainActivityK.kt
1
2189
package com.emedinaa.infosoft2017 import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentTransaction import android.view.MenuItem import com.emedinaa.infosoft2017.ui.BaseActivityK import com.emedinaa.infosoft2017.ui.fragmentskt.HomeFragmentK import com.emedinaa.infosoft2017.ui.fragmentskt.ScheduleFragmentK import com.emedinaa.infosoft2017.ui.fragmentskt.SpeakersFragmentK import com.emedinaa.infosoft2017.ui.fragmentskt.SponsorsFragmentK import kotlinx.android.synthetic.main.activity_main.* class MainActivityK : BaseActivityK() { private var itemId=0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) app() } /** * Kotlin when * https://kotlinlang.org/docs/reference/basic-syntax.html */ private fun app() { val menuItem:MenuItem= bottomNavigation.menu.getItem(0) itemId= menuItem.itemId changeFragment(HomeFragmentK.newInstance()) bottomNavigation.setOnNavigationItemSelectedListener {item: MenuItem -> var fragment:Fragment?=null var tab=0 itemId= item.itemId when(item.itemId){ R.id.action_home -> { tab = 0 fragment= HomeFragmentK.newInstance() } R.id.action_speakers -> { tab =1 fragment= SpeakersFragmentK.newInstance() } R.id.action_schedule-> { tab=2 fragment= ScheduleFragmentK.newInstance() } R.id.action_sponsors-> { tab=3 fragment= SponsorsFragmentK.newInstance() } } changeFragment(fragment!!) true } } private fun changeFragment(fragment: Fragment){ val fragmenTransaction:FragmentTransaction= supportFragmentManager.beginTransaction() fragmenTransaction.replace(R.id.frameLayout,fragment,null) fragmenTransaction.commit() } }
apache-2.0
e3d6ae074c643d1acda5a05efe31c949
30.724638
93
0.624943
4.908072
false
false
false
false
flurgle/CameraKit-Android
camerakit/src/main/java/com/camerakit/preview/CameraSurfaceTexture.kt
2
1942
package com.camerakit.preview import android.graphics.SurfaceTexture import android.opengl.Matrix import androidx.annotation.Keep import com.camerakit.type.CameraSize class CameraSurfaceTexture(inputTexture: Int, val outputTexture: Int) : SurfaceTexture(inputTexture) { var size: CameraSize = CameraSize(0, 0) set(size) { field = size previewInvalidated = true } private var previewInvalidated = false private val transformMatrix: FloatArray = FloatArray(16) private val extraTransformMatrix: FloatArray = FloatArray(16) init { nativeInit(inputTexture, outputTexture) Matrix.setIdentityM(extraTransformMatrix, 0) } override fun updateTexImage() { if (previewInvalidated) { nativeSetSize(size.width, size.height) previewInvalidated = false } super.updateTexImage() getTransformMatrix(transformMatrix) nativeUpdateTexImage(transformMatrix, extraTransformMatrix) } override fun release() { nativeRelease() } fun setRotation(degrees: Int) { Matrix.setIdentityM(extraTransformMatrix, 0) Matrix.rotateM(extraTransformMatrix, 0, degrees.toFloat(), 0f, 0f, 1f) } // --- override fun finalize() { super.finalize() try { nativeFinalize() } catch (e: Exception) { // ignore } } // --- @Keep private var nativeHandle: Long = 0L private external fun nativeInit(inputTexture: Int, outputTexture: Int) private external fun nativeSetSize(width: Int, height: Int) private external fun nativeUpdateTexImage(transformMatrix: FloatArray, extraTransformMatrix: FloatArray) private external fun nativeFinalize() private external fun nativeRelease() companion object { init { System.loadLibrary("camerakit") } } }
mit
f3c074654878276c78c8a977cdd04449
23.275
108
0.65551
4.855
false
false
false
false
Heiner1/AndroidAPS
database/src/main/java/info/nightscout/androidaps/database/transactions/VersionChangeTransaction.kt
1
986
package info.nightscout.androidaps.database.transactions import info.nightscout.androidaps.database.entities.VersionChange import java.util.* class VersionChangeTransaction( private val versionName: String, private val versionCode: Int, private val gitRemote: String?, private val commitHash: String?) : Transaction<Unit>() { override fun run() { val current = database.versionChangeDao.getMostRecentVersionChange() if (current == null || current.versionName != versionName || current.versionCode != versionCode || current.gitRemote != gitRemote || current.commitHash != commitHash) { database.versionChangeDao.insert(VersionChange( timestamp = System.currentTimeMillis(), versionCode = versionCode, versionName = versionName, gitRemote = gitRemote, commitHash = commitHash )) } } }
agpl-3.0
7dea514c43dd8032fe04e4a0c82051f7
33.034483
76
0.63286
5.699422
false
false
false
false
Adventech/sabbath-school-android-2
features/lessons/src/main/java/com/cryart/sabbathschool/lessons/ui/lessons/LessonsViewModel.kt
1
5377
/* * Copyright (c) 2020 Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.cryart.sabbathschool.lessons.ui.lessons import androidx.compose.runtime.snapshotFlow import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import app.ss.lessons.data.repository.lessons.LessonsRepository import app.ss.lessons.data.repository.quarterly.QuarterliesRepository import app.ss.models.LessonPdf import app.ss.models.PublishingInfo import app.ss.models.SSQuarterlyInfo import app.ss.widgets.AppWidgetHelper import com.cryart.sabbathschool.core.extensions.coroutines.flow.stateIn import com.cryart.sabbathschool.core.extensions.prefs.SSPrefs import com.cryart.sabbathschool.core.misc.SSConstants import com.cryart.sabbathschool.core.response.Result import com.cryart.sabbathschool.core.response.asResult import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class LessonsViewModel @Inject constructor( private val repository: QuarterliesRepository, private val lessonsRepository: LessonsRepository, private val ssPrefs: SSPrefs, private val appWidgetHelper: AppWidgetHelper, private val savedStateHandle: SavedStateHandle ) : ViewModel() { private val quarterlyIndex: String? get() = savedStateHandle.get<String>( SSConstants.SS_QUARTERLY_INDEX_EXTRA ) ?: ssPrefs.getLastQuarterlyIndex() private val publishingInfo: Flow<Result<PublishingInfo?>> = repository.getPublishingInfo() .map { it.data } .asResult() private val quarterlyInfo: Flow<Result<SSQuarterlyInfo?>> = snapshotFlow { quarterlyIndex } .flatMapLatest { index -> index?.run { repository.getQuarterlyInfo(index) .map { it.data } } ?: flowOf(null) } .onEach { info -> info?.run { appWidgetHelper.refreshAll() } } .asResult() private val _selectedPdfs = MutableSharedFlow<Pair<String, List<LessonPdf>>>() val selectedPdfsFlow: SharedFlow<Pair<String, List<LessonPdf>>> = _selectedPdfs val uiState: StateFlow<LessonsScreenState> = combine( publishingInfo, quarterlyInfo ) { publishingInfo, quarterlyInfo -> val publishingInfoState = when (publishingInfo) { is Result.Error -> PublishingInfoState.Error Result.Loading -> PublishingInfoState.Loading is Result.Success -> publishingInfo.data?.let { PublishingInfoState.Success(it) } ?: PublishingInfoState.Error } val quarterlyInfoState = when (quarterlyInfo) { is Result.Error -> QuarterlyInfoState.Error Result.Loading -> QuarterlyInfoState.Loading is Result.Success -> quarterlyInfo.data?.let { QuarterlyInfoState.Success(it) } ?: QuarterlyInfoState.Error } LessonsScreenState( isLoading = quarterlyInfoState == QuarterlyInfoState.Loading, isError = quarterlyInfoState == QuarterlyInfoState.Error, publishingInfo = publishingInfoState, quarterlyInfo = quarterlyInfoState ) }.stateIn(viewModelScope, LessonsScreenState()) private val ssQuarterlyInfo: SSQuarterlyInfo? get() = (uiState.value.quarterlyInfo as? QuarterlyInfoState.Success)?.quarterlyInfo val quarterlyShareIndex: String get() = ssQuarterlyInfo?.shareIndex() ?: "" init { // cache DisplayOptions for read screen launch ssPrefs.getDisplayOptions { } } fun pdfLessonSelected(lessonIndex: String) = viewModelScope.launch { val resource = lessonsRepository.getLessonInfo(lessonIndex) if (resource.isSuccessFul) { val data = resource.data _selectedPdfs.emit(lessonIndex to (data?.pdfs ?: emptyList())) } } }
mit
d423540bb8ea4ce19336b411e3d9b61f
40.682171
133
0.725869
4.906022
false
false
false
false
DuncanCasteleyn/DiscordModBot
src/main/kotlin/be/duncanc/discordmodbot/bot/services/MuteRole.kt
1
5967
/* * Copyright 2018 Duncan Casteleyn * * 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 be.duncanc.discordmodbot.bot.services import be.duncanc.discordmodbot.bot.commands.CommandModule import be.duncanc.discordmodbot.bot.utils.nicknameAndUsername import be.duncanc.discordmodbot.data.entities.MuteRole import be.duncanc.discordmodbot.data.repositories.jpa.MuteRolesRepository import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.Guild import net.dv8tion.jda.api.entities.Role import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent import net.dv8tion.jda.api.events.guild.member.GuildMemberRoleAddEvent import net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent import net.dv8tion.jda.api.events.message.MessageReceivedEvent import net.dv8tion.jda.api.events.role.RoleDeleteEvent import net.dv8tion.jda.api.exceptions.PermissionException import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import org.springframework.transaction.annotation.Transactional import java.awt.Color import java.util.concurrent.TimeUnit @Component @Transactional class MuteRole @Autowired constructor( private val muteRolesRepository: MuteRolesRepository, private val guildLogger: GuildLogger ) : CommandModule( arrayOf("MuteRole"), "[Name of the mute role or nothing to remove the role]", "This command allows you to set the mute role for a guild/server" ) { override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) { if (event.member?.hasPermission(Permission.MANAGE_ROLES) != true) { throw PermissionException("You do not have sufficient permissions to set the mute role for this server") } val guildId = event.guild.idLong if (arguments == null) { muteRolesRepository.deleteById(guildId) event.channel.sendMessage("Mute role has been removed.") .queue { it.delete().queueAfter(1, TimeUnit.MINUTES) } } else { try { muteRolesRepository.save(MuteRole(guildId, event.guild.getRolesByName(arguments, false)[0].idLong)) event.channel.sendMessage("Role has been set as mute role.") .queue { it.delete().queueAfter(1, TimeUnit.MINUTES) } } catch (exception: IndexOutOfBoundsException) { throw IllegalArgumentException("Couldn't find any roles with that name.", exception) } } } override fun onRoleDelete(event: RoleDeleteEvent) { muteRolesRepository.deleteByRoleIdAndGuildId(event.role.idLong, event.guild.idLong) } @Transactional(readOnly = true) fun getMuteRole(guild: Guild): Role { val roleId = muteRolesRepository.findById(guild.idLong) .orElse(null)?.roleId ?: throw IllegalStateException("This guild does not have a mute role set up.") return guild.getRoleById(roleId)!! } override fun onGuildMemberRoleAdd(event: GuildMemberRoleAddEvent) { val muteRole = muteRolesRepository.findById(event.guild.idLong) .orElse(null) if (!(muteRole == null || !event.roles.contains(muteRole.roleId.let { event.guild.getRoleById(it) }))) { muteRole.mutedUsers.add(event.user.idLong) muteRolesRepository.save(muteRole) } } override fun onGuildMemberRoleRemove(event: GuildMemberRoleRemoveEvent) { val muteRole = muteRolesRepository.findById(event.guild.idLong) .orElse(null) if (muteRole != null && event.roles.contains(muteRole.roleId.let { event.guild.getRoleById(it) })) { muteRole.mutedUsers.remove(event.user.idLong) muteRolesRepository.save(muteRole) } } override fun onGuildMemberRemove(event: GuildMemberRemoveEvent) { val member = event.member val muteRole = muteRolesRepository.findById(event.guild.idLong) .orElse(null) if (muteRole != null && member != null) { if (member.roles.contains(muteRole.roleId.let { event.guild.getRoleById(it) })) { muteRole.mutedUsers.add(event.user.idLong) muteRolesRepository.save(muteRole) } else { muteRole.mutedUsers.remove(event.user.idLong) muteRolesRepository.save(muteRole) } } } override fun onGuildMemberJoin(event: GuildMemberJoinEvent) { val muteRole = muteRolesRepository.findById(event.guild.idLong) .orElse(null) if (muteRole?.roleId != null && muteRole.mutedUsers.contains(event.user.idLong)) { event.guild.addRoleToMember(event.member, event.guild.getRoleById(muteRole.roleId)!!).queue() val logEmbed = EmbedBuilder() .setColor(Color.YELLOW) .setTitle("User automatically muted") .addField("User", event.member.nicknameAndUsername, true) .addField("Reason", "Previously muted before leaving the server", false) guildLogger.log( guild = event.guild, associatedUser = event.user, logEmbed = logEmbed, actionType = GuildLogger.LogTypeAction.MODERATOR ) } } }
apache-2.0
6f1d32f079f619f4291090e1632c38f4
42.554745
116
0.690129
4.558442
false
false
false
false
blindpirate/gradle
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/ConfigurationCacheKey.kt
1
4196
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.configurationcache import org.gradle.configurationcache.extensions.unsafeLazy import org.gradle.configurationcache.initialization.ConfigurationCacheStartParameter import org.gradle.internal.buildtree.BuildActionModelRequirements import org.gradle.internal.hash.Hasher import org.gradle.internal.hash.Hashing import org.gradle.internal.service.scopes.Scopes import org.gradle.internal.service.scopes.ServiceScope import org.gradle.util.GradleVersion import org.gradle.util.internal.GFileUtils.relativePathOf import java.io.File @ServiceScope(Scopes.BuildTree::class) class ConfigurationCacheKey( private val startParameter: ConfigurationCacheStartParameter, private val buildActionRequirements: BuildActionModelRequirements ) { val string: String by unsafeLazy { Hashing.md5().newHasher().apply { putCacheKeyComponents() }.hash().toCompactString() } override fun toString() = string override fun hashCode(): Int = string.hashCode() override fun equals(other: Any?): Boolean = (other as? ConfigurationCacheKey)?.string == string private fun Hasher.putCacheKeyComponents() { putString(GradleVersion.current().version) putString( startParameter.settingsFile?.let { relativePathOf(it, startParameter.rootDirectory) } ?: "" ) putAll( startParameter.includedBuilds.map { relativePathOf(it, startParameter.rootDirectory) } ) buildActionRequirements.appendKeyTo(this) // TODO:bamboo review with Adam // require(buildActionRequirements.isRunsTasks || startParameter.requestedTaskNames.isEmpty()) if (buildActionRequirements.isRunsTasks) { appendRequestedTasks() } } private fun Hasher.appendRequestedTasks() { val requestedTaskNames = startParameter.requestedTaskNames putAll(requestedTaskNames) val excludedTaskNames = startParameter.excludedTaskNames putAll(excludedTaskNames) val taskNames = requestedTaskNames.asSequence() + excludedTaskNames.asSequence() val hasRelativeTaskName = taskNames.any { !it.startsWith(':') } if (hasRelativeTaskName) { // Because unqualified task names are resolved relative to the selected // sub-project according to either `projectDirectory` or `currentDirectory`, // the relative directory information must be part of the key. val projectDir = startParameter.projectDirectory if (projectDir != null) { relativePathOf( projectDir, startParameter.rootDirectory ).let { relativeProjectDir -> putString(relativeProjectDir) } } else { relativeChildPathOrNull( startParameter.currentDirectory, startParameter.rootDirectory )?.let { relativeSubDir -> putString(relativeSubDir) } } } } private fun Hasher.putAll(list: Collection<String>) { putInt(list.size) list.forEach(::putString) } /** * Returns the path of [target] relative to [base] if * [target] is a child of [base] or `null` otherwise. */ private fun relativeChildPathOrNull(target: File, base: File): String? = relativePathOf(target, base) .takeIf { !it.startsWith('.') } }
apache-2.0
ababae680a390dddb7153f39f319977f
33.677686
101
0.664442
5.148466
false
true
false
false
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/rename/javaSetterToOrdinaryMethod/before/synthesize.kt
26
182
fun synthesize(p: SyntheticProperty) { val v1 = p.syntheticA p.syntheticA = 1 p.syntheticA += 2 p.syntheticA++ val x = p.syntheticA++ val y = ++p.syntheticA }
apache-2.0
89f95f82f64501664803211ae4a4f77e
21.875
38
0.615385
3.5
false
false
false
false
android/nowinandroid
core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/model/NewsResource.kt
1
2963
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.core.data.model import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceAuthorCrossRef import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceTopicCrossRef import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResourceExpanded fun NetworkNewsResource.asEntity() = NewsResourceEntity( id = id, title = title, content = content, url = url, headerImageUrl = headerImageUrl, publishDate = publishDate, type = type, ) fun NetworkNewsResourceExpanded.asEntity() = NewsResourceEntity( id = id, title = title, content = content, url = url, headerImageUrl = headerImageUrl, publishDate = publishDate, type = type, ) /** * A shell [AuthorEntity] to fulfill the foreign key constraint when inserting * a [NewsResourceEntity] into the DB */ fun NetworkNewsResource.authorEntityShells() = authors.map { authorId -> AuthorEntity( id = authorId, name = "", imageUrl = "", twitter = "", mediumPage = "", bio = "", ) } /** * A shell [TopicEntity] to fulfill the foreign key constraint when inserting * a [NewsResourceEntity] into the DB */ fun NetworkNewsResource.topicEntityShells() = topics.map { topicId -> TopicEntity( id = topicId, name = "", url = "", imageUrl = "", shortDescription = "", longDescription = "", ) } fun NetworkNewsResource.topicCrossReferences(): List<NewsResourceTopicCrossRef> = topics.map { topicId -> NewsResourceTopicCrossRef( newsResourceId = id, topicId = topicId ) } fun NetworkNewsResource.authorCrossReferences(): List<NewsResourceAuthorCrossRef> = authors.map { authorId -> NewsResourceAuthorCrossRef( newsResourceId = id, authorId = authorId ) }
apache-2.0
ea05b8117a11507128b8a1d3178b57c0
30.860215
90
0.682754
4.572531
false
false
false
false
datarank/tempest
src/main/java/com/simplymeasured/elasticsearch/plugins/tempest/balancer/IndexGroupPartitioner.kt
1
3860
/* * The MIT License (MIT) * Copyright (c) 2018 DataRank, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.simplymeasured.elasticsearch.plugins.tempest.balancer import org.eclipse.collections.api.RichIterable import org.eclipse.collections.api.list.ListIterable import org.eclipse.collections.api.map.MapIterable import org.eclipse.collections.api.multimap.Multimap import org.eclipse.collections.impl.factory.Lists import org.eclipse.collections.impl.list.mutable.FastList import org.eclipse.collections.impl.tuple.Tuples import org.eclipse.collections.impl.utility.LazyIterate import org.elasticsearch.cluster.metadata.IndexMetaData import org.elasticsearch.cluster.metadata.MetaData import org.elasticsearch.common.component.AbstractComponent import org.elasticsearch.common.inject.Inject import org.elasticsearch.common.logging.Loggers import org.elasticsearch.common.settings.Settings import java.util.regex.Pattern import java.util.regex.PatternSyntaxException import javax.swing.UIManager.put /** * Partition indexes into groups based on a user defined regular expression */ open class IndexGroupPartitioner @Inject constructor(settings: Settings) : AbstractComponent(settings) { private var indexPatterns: ListIterable<Pattern> = Lists.immutable.of(safeCompile(".*")) // commas aren't perfect here since they can legally be defined in regexes but it seems reasonable for now; // perhaps there is a more generic way to define groups var indexGroupPatternSetting: String = ".*" set (value) { field = value indexPatterns = field .split(",") .mapNotNull { safeCompile(it) } .let { Lists.mutable.ofAll(it) } .apply { this.add(safeCompile(".*")) } .toImmutable() } private fun safeCompile(it: String): Pattern? { return try { Pattern.compile(it) } catch(e: PatternSyntaxException) { logger.warn("failed to compile group pattern ${it}") null } } fun partition(metadata: MetaData): RichIterable<RichIterable<IndexMetaData>> = FastList .newWithNValues(indexPatterns.size()) { Lists.mutable.empty<IndexMetaData>() } .apply { metadata.forEach { this[determineGroupNumber(it.index)].add(it) } } .let { it as RichIterable<RichIterable<IndexMetaData>> } fun patternMapping(metadata: MetaData) : Multimap<String, String> = LazyIterate .adapt(metadata) .collect { it.index } .groupBy { indexPatterns[determineGroupNumber(it)].toString() } private fun determineGroupNumber(indexName: String): Int { return indexPatterns.indexOfFirst { it.matcher(indexName).matches() } } }
mit
2a1b886d3bdefc4354f4935776f4a9f8
42.875
111
0.717358
4.472769
false
false
false
false
JavaEden/Orchid-Core
OrchidCore/src/main/kotlin/com/eden/orchid/api/options/archetypes/AssetMetadataArchetype.kt
2
1671
package com.eden.orchid.api.options.archetypes import com.caseyjbrooks.clog.Clog import com.eden.common.util.EdenUtils import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.OptionArchetype import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.resources.resourcesource.LocalResourceSource import com.eden.orchid.api.theme.assets.AssetPage import com.eden.orchid.utilities.OrchidUtils import javax.inject.Inject @Description( value = "Allows this asset to have configurations from data files in the archetype key's directory. " + "This is especially useful for binary asset files which cannot have Front Matter. Additional asset configs " + "come from a data file at the same path as the asset itself, but in the archetype key's directory.", name = "Asset Config" ) class AssetMetadataArchetype @Inject constructor( private val context: OrchidContext ) : OptionArchetype { override fun getOptions(target: Any, archetypeKey: String): Map<String, Any?>? { var data: Map<String, Any?>? = null if (target is AssetPage) { val metadataFilename = Clog.format( "{}/{}/{}", OrchidUtils.normalizePath(archetypeKey), OrchidUtils.normalizePath(target.resource.reference.originalPath), OrchidUtils.normalizePath(target.resource.reference.originalFileName) ) if (!EdenUtils.isEmpty(metadataFilename)) { data = context.getDataResourceSource(LocalResourceSource).getDatafile(context, metadataFilename) } } return data } }
mit
5189c34e482f8e6f7f7f904d52dd5c2b
35.326087
122
0.704369
4.603306
false
true
false
false
GunoH/intellij-community
java/java-tests/testSrc/com/intellij/java/configurationStore/LoadProjectTest.kt
5
7774
// 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.java.configurationStore import com.intellij.ProjectTopics import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.EDT import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.application.runWriteActionAndWait import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.Computable import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.DisposableRule import com.intellij.testFramework.TemporaryDirectory import com.intellij.testFramework.loadProjectAndCheckResults import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.assertj.core.api.Assertions.assertThat import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.nio.file.Path import java.nio.file.Paths import java.util.function.Consumer class LoadProjectTest { companion object { @JvmField @ClassRule val appRule = ApplicationRule() } @JvmField @Rule val tempDirectory = TemporaryDirectory() @JvmField @Rule val disposable = DisposableRule() @Test fun `load single module`() = runBlocking { loadProjectAndCheckResults("single-module") { project -> val module = ModuleManager.getInstance(project).modules.single() assertThat(module.name).isEqualTo("foo") assertThat(module.moduleTypeName).isEqualTo("EMPTY_MODULE") } } @Test fun `load module with group`() = runBlocking { loadProjectAndCheckResults("module-in-group") { project -> val module = ModuleManager.getInstance(project).modules.single() assertThat(module.name).isEqualTo("foo") assertThat(module.moduleTypeName).isEqualTo("EMPTY_MODULE") assertThat(ModuleManager.getInstance(project).getModuleGroupPath(module)).containsExactly("group") } } @Test fun `load detached module`() = runBlocking { loadProjectAndCheckResults("detached-module") { project -> val fooModule = ModuleManager.getInstance(project).modules.single() assertThat(fooModule.name).isEqualTo("foo") val barModule = withContext(Dispatchers.EDT) { ApplicationManager.getApplication().runWriteAction(Computable { ModuleManager.getInstance(project).loadModule(Path.of("${project.basePath}/bar/bar.iml")) }) } assertThat(barModule.name).isEqualTo("bar") assertThat(barModule.moduleTypeName).isEqualTo("EMPTY_MODULE") assertThat(ModuleManager.getInstance(project).modules).containsExactlyInAnyOrder(fooModule, barModule) } } @Test fun `load detached module via modifiable model`() = runBlocking { loadProjectAndCheckResults("detached-module") { project -> val fooModule = ModuleManager.getInstance(project).modules.single() assertThat(fooModule.name).isEqualTo("foo") runWriteActionAndWait { val model = ModuleManager.getInstance(project).getModifiableModel() model.loadModule("${project.basePath}/bar/bar.iml") model.commit() } val barModule = ModuleManager.getInstance(project).findModuleByName("bar") assertThat(barModule).isNotNull assertThat(barModule!!.moduleTypeName).isEqualTo("EMPTY_MODULE") assertThat(ModuleManager.getInstance(project).modules).containsExactlyInAnyOrder(fooModule, barModule) } } @Test fun `load single library`() = runBlocking { loadProjectAndCheckResults("single-library") { project -> assertThat(ModuleManager.getInstance(project).modules).isEmpty() val library = LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries.single() assertThat(library.name).isEqualTo("foo") val rootUrl = library.getUrls(OrderRootType.CLASSES).single() assertThat(rootUrl).isEqualTo(VfsUtilCore.pathToUrl("${project.basePath}/lib/classes")) } } @Test fun `load module and library`() = runBlocking { loadProjectAndCheckResults("module-and-library", beforeOpen = { project -> //this emulates listener declared in plugin.xml, it's registered before the project is loaded project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) { val library = LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries.single() assertThat(library.name).isEqualTo("foo") } }) }) { project -> val fooModule = ModuleManager.getInstance(project).modules.single() assertThat(fooModule.name).isEqualTo("foo") val library = LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries.single() assertThat(library.name).isEqualTo("foo") val rootUrl = library.getUrls(OrderRootType.CLASSES).single() assertThat(rootUrl).isEqualTo(VfsUtilCore.pathToUrl("${project.basePath}/lib/classes")) } } private val Library.properties: RepositoryLibraryProperties get() = (this as LibraryEx).properties as RepositoryLibraryProperties @Test fun `load repository libraries`() = runBlocking { val projectPath = Paths.get(PathManagerEx.getCommunityHomePath()).resolve("jps/model-serialization/testData/repositoryLibraries") loadProjectAndCheckResults(listOf(projectPath), tempDirectory) { project -> assertThat(ModuleManager.getInstance(project).modules).isEmpty() val libraries = LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries.sortedBy { it.name } assertThat(libraries).hasSize(3) val (plain, withExcluded, withoutTransitive) = libraries assertThat(plain.name).isEqualTo("plain") assertThat(plain.properties.groupId).isEqualTo("junit") assertThat(plain.properties.artifactId).isEqualTo("junit") assertThat(plain.properties.version).isEqualTo("3.8.1") assertThat(plain.properties.isIncludeTransitiveDependencies).isTrue() assertThat(plain.properties.excludedDependencies).isEmpty() assertThat(withExcluded.name).isEqualTo("with-excluded-dependencies") assertThat(withExcluded.properties.isIncludeTransitiveDependencies).isTrue() assertThat(withExcluded.properties.excludedDependencies).containsExactly("org.apache.httpcomponents:httpclient") assertThat(withoutTransitive.name).isEqualTo("without-transitive-dependencies") assertThat(withoutTransitive.properties.isIncludeTransitiveDependencies).isFalse() assertThat(withoutTransitive.properties.excludedDependencies).isEmpty() } } private suspend fun loadProjectAndCheckResults(testDataDirName: String, beforeOpen: Consumer<Project>? = null, checkProject: suspend (Project) -> Unit) { val testDataRoot = Path.of(PathManagerEx.getCommunityHomePath()).resolve("java/java-tests/testData/configurationStore") return loadProjectAndCheckResults(projectPaths = listOf(element = testDataRoot.resolve(testDataDirName)), tempDirectory = tempDirectory, beforeOpen = beforeOpen, checkProject = checkProject) } }
apache-2.0
738640ecae568cd9822588dabeea8cfa
45
155
0.753023
5.071102
false
true
false
false
GunoH/intellij-community
platform/configuration-store-impl/src/TrackingPathMacroSubstitutorImpl.kt
7
2514
// 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.configurationStore import com.intellij.openapi.components.PathMacroManager import com.intellij.openapi.components.PathMacroSubstitutor import com.intellij.openapi.components.TrackingPathMacroSubstitutor import org.jetbrains.annotations.ApiStatus internal fun PathMacroManager?.createTrackingSubstitutor(): TrackingPathMacroSubstitutorImpl? = if (this == null) null else TrackingPathMacroSubstitutorImpl(this) @ApiStatus.Internal class TrackingPathMacroSubstitutorImpl(internal val macroManager: PathMacroManager) : PathMacroSubstitutor by macroManager, TrackingPathMacroSubstitutor { private val lock = Object() private val macroToComponentNames = HashMap<String, MutableSet<String>>() private val componentNameToMacros = HashMap<String, MutableSet<String>>() override fun reset() { synchronized(lock) { macroToComponentNames.clear() componentNameToMacros.clear() } } override fun hashCode() = macroManager.expandMacroMap.hashCode() override fun invalidateUnknownMacros(macros: Set<String>) { synchronized(lock) { for (macro in macros) { val componentNames = macroToComponentNames.remove(macro) ?: continue for (component in componentNames) { componentNameToMacros.remove(component) } } } } override fun getComponents(macros: Collection<String>): Set<String> { synchronized(lock) { val result = HashSet<String>() for (macro in macros) { result.addAll(macroToComponentNames.get(macro) ?: continue) } return result } } override fun getUnknownMacros(componentName: String?): Set<String> { return synchronized(lock) { if (componentName == null) { macroToComponentNames.keys } else { componentNameToMacros.get(componentName) ?: emptySet() } } } override fun addUnknownMacros(componentName: String, unknownMacros: Collection<String>) { if (unknownMacros.isEmpty()) { return } LOG.info("Registering unknown macros ${unknownMacros.joinToString(", ")} in component $componentName") synchronized(lock) { for (unknownMacro in unknownMacros) { macroToComponentNames.computeIfAbsent(unknownMacro, { HashSet() }).add(componentName) } componentNameToMacros.computeIfAbsent(componentName, { HashSet() }).addAll(unknownMacros) } } }
apache-2.0
161e3d44371cf7f0218609fc7703496b
32.52
162
0.723946
5.215768
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/titleLabel/CustomDecorationPath.kt
1
5051
// 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.openapi.wm.impl.customFrameDecorations.header.titleLabel import com.intellij.ide.RecentProjectsManager import com.intellij.ide.RecentProjectsManagerBase import com.intellij.ide.lightEdit.LightEdit import com.intellij.ide.ui.UISettings import com.intellij.ide.ui.UISettingsListener import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.registry.RegistryValue import com.intellij.openapi.util.registry.RegistryValueListener import com.intellij.openapi.wm.impl.customFrameDecorations.header.title.CustomHeaderTitle import com.intellij.ui.awt.RelativeRectangle import com.intellij.util.ui.JBUI.CurrentTheme.CustomFrameDecorations import java.awt.Rectangle import java.beans.PropertyChangeListener import javax.swing.JComponent import javax.swing.JFrame internal open class CustomDecorationPath(val frame: JFrame) : SelectedEditorFilePath(frame), CustomHeaderTitle { companion object { fun createInstance(frame: JFrame): CustomDecorationPath = CustomDecorationPath(frame) fun createMainInstance(frame: JFrame): CustomDecorationPath = MainCustomDecorationPath(frame) } private val projectManagerListener = object : ProjectManagerListener { override fun projectOpened(project: Project) { checkOpenedProjects() } override fun projectClosed(project: Project) { checkOpenedProjects() } } private fun checkOpenedProjects() { val currentProject = project ?: return val manager = RecentProjectsManager.getInstance() as RecentProjectsManagerBase val currentPath = manager.getProjectPath(currentProject) ?: return val currentName = manager.getProjectName(currentPath) val sameNameInRecent = manager.getRecentPaths().any { currentPath != it && currentName == manager.getProjectName(it) } val sameNameInOpen = ProjectManager.getInstance().openProjects.any { val path = manager.getProjectPath(it) ?: return@any false val name = manager.getProjectName(path) currentPath != path && currentName == name } multipleSameNamed = sameNameInRecent || sameNameInOpen } private val titleChangeListener = PropertyChangeListener { updateProjectPath() } override fun getCustomTitle(): String? { if (LightEdit.owns(project)) { return frame.title } return null } override fun setActive(value: Boolean) { val color = if (value) CustomFrameDecorations.titlePaneInfoForeground() else CustomFrameDecorations.titlePaneInactiveInfoForeground() view.foreground = color } override fun getBoundList(): List<RelativeRectangle> { return if (!toolTipNeeded) { emptyList() } else { val hitTestSpots = ArrayList<RelativeRectangle>() hitTestSpots.addAll(getMouseInsetList(label)) hitTestSpots } } override fun installListeners() { super.installListeners() frame.addPropertyChangeListener("title", titleChangeListener) } override fun addAdditionalListeners(disp: Disposable) { super.addAdditionalListeners(disp) project?.let { val busConnection = ApplicationManager.getApplication().messageBus.connect(disp) busConnection.subscribe(ProjectManager.TOPIC, projectManagerListener) busConnection.subscribe(UISettingsListener.TOPIC, UISettingsListener { checkTabPlacement() }) checkTabPlacement() checkOpenedProjects() } } private fun checkTabPlacement() { classPathNeeded = UISettings.getInstance().editorTabPlacement == 0 } override fun unInstallListeners() { super.unInstallListeners() frame.removePropertyChangeListener(titleChangeListener) } private fun getMouseInsetList(view: JComponent, mouseInsets: Int = 1): List<RelativeRectangle> { return listOf( RelativeRectangle(view, Rectangle(0, 0, mouseInsets, view.height)), RelativeRectangle(view, Rectangle(0, 0, view.width, mouseInsets)), RelativeRectangle(view, Rectangle(0, view.height - mouseInsets, view.width, mouseInsets)), RelativeRectangle(view, Rectangle(view.width - mouseInsets, 0, mouseInsets, view.height)) ) } } private class MainCustomDecorationPath(frame: JFrame) : CustomDecorationPath(frame) { private val classKey = "ide.borderless.tab.caption.in.title" private val registryListener = object : RegistryValueListener { override fun afterValueChanged(value: RegistryValue) { updatePaths() } } override val captionInTitle: Boolean get() = Registry.get(classKey).asBoolean() override fun addAdditionalListeners(disp: Disposable) { super.addAdditionalListeners(disp) Registry.get(classKey).addListener(registryListener, disp) } }
apache-2.0
4d53efd67285b4110bdc90395c1bb684
34.829787
137
0.763017
4.981262
false
false
false
false
GunoH/intellij-community
plugins/junit/test/com/intellij/execution/junit/JUnitPlatformPropertiesTest.kt
5
2530
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.execution.junit import com.intellij.lang.properties.codeInspection.unused.UnusedPropertyInspection import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase class JUnitPlatformPropertiesTest : LightJavaCodeInsightFixtureTestCase() { override fun setUp() { super.setUp() // define property source class myFixture.addClass(""" package org.junit.jupiter.engine; public final class Constants { public static final String DEACTIVATE_CONDITIONS_PATTERN_PROPERTY_NAME = "junit.jupiter.conditions.deactivate"; public static final String DEACTIVATE_ALL_CONDITIONS_PATTERN = "*"; public static final String DEFAULT_DISPLAY_NAME_GENERATOR_PROPERTY_NAME = "junit.jupiter.displayname.generator.default"; public static final String EXTENSIONS_AUTODETECTION_ENABLED_PROPERTY_NAME = "junit.jupiter.extensions.autodetection.enabled"; public static final String DEFAULT_TEST_INSTANCE_LIFECYCLE_PROPERTY_NAME = "junit.jupiter.testinstance.lifecycle.default"; public static final String PARALLEL_EXECUTION_ENABLED_PROPERTY_NAME = "junit.jupiter.execution.parallel.enabled"; public static final String DEFAULT_PARALLEL_EXECUTION_MODE = "junit.jupiter.execution.parallel.mode.default"; } """.trimIndent()) } fun testImplicitUsage() { myFixture.enableInspections(UnusedPropertyInspection::class.java) myFixture.configureByText("junit-platform.properties", """ junit.jupiter.displayname.generator.default = {index} <warning descr="Unused property">junit.unknown</warning> = unknown """.trimIndent()) myFixture.checkHighlighting() } fun testCompletion() { myFixture.configureByText("junit-platform.properties", """ junit.jupiter.<caret> """.trimIndent()) myFixture.testCompletionVariants("junit-platform.properties", "junit.jupiter.conditions.deactivate", "junit.jupiter.displayname.generator.default", "junit.jupiter.execution.parallel.enabled", "junit.jupiter.extensions.autodetection.enabled", "junit.jupiter.testinstance.lifecycle.default", "junit.jupiter.execution.parallel.mode.default") } }
apache-2.0
29c69dab35f309b9446945bef0db0a52
47.673077
135
0.690514
5.080321
false
true
false
false
GunoH/intellij-community
plugins/kotlin/native/src/org/jetbrains/kotlin/ide/konan/NativeDefinitions.kt
2
9501
// 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.ide.konan import com.intellij.extapi.psi.PsiFileBase import com.intellij.lang.* import com.intellij.lexer.FlexAdapter import com.intellij.lexer.Lexer import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.HighlighterColors import com.intellij.openapi.fileTypes.* import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.tree.* import javax.swing.Icon import java.io.Reader import org.jetbrains.kotlin.ide.konan.psi.* import org.jetbrains.kotlin.idea.KotlinIcons const val KOTLIN_NATIVE_DEFINITIONS_FILE_EXTENSION = "def" const val KOTLIN_NATIVE_DEFINITIONS_ID = "KND" val KOTLIN_NATIVE_DEFINITIONS_DESCRIPTION get() = KotlinNativeBundle.message("kotlin.native.definitions.description") object NativeDefinitionsFileType : LanguageFileType(NativeDefinitionsLanguage.INSTANCE) { override fun getName(): String = "Kotlin/Native Def" override fun getDescription(): String = KOTLIN_NATIVE_DEFINITIONS_DESCRIPTION override fun getDefaultExtension(): String = KOTLIN_NATIVE_DEFINITIONS_FILE_EXTENSION override fun getIcon(): Icon = KotlinIcons.NATIVE } class NativeDefinitionsLanguage private constructor() : Language(KOTLIN_NATIVE_DEFINITIONS_ID) { companion object { val INSTANCE = NativeDefinitionsLanguage() } override fun getDisplayName(): String = KotlinNativeBundle.message("kotlin.native.definitions.short") } class NativeDefinitionsFile(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, NativeDefinitionsLanguage.INSTANCE) { override fun getFileType(): FileType = NativeDefinitionsFileType override fun toString(): String = KOTLIN_NATIVE_DEFINITIONS_DESCRIPTION override fun getIcon(flags: Int): Icon? = super.getIcon(flags) } class NativeDefinitionsLexerAdapter : FlexAdapter(NativeDefinitionsLexer(null as Reader?)) private object NativeDefinitionsTokenSets { val COMMENTS: TokenSet = TokenSet.create(NativeDefinitionsTypes.COMMENT) } class NativeDefinitionsParserDefinition : ParserDefinition { private val FILE = IFileElementType(NativeDefinitionsLanguage.INSTANCE) override fun getWhitespaceTokens(): TokenSet = TokenSet.WHITE_SPACE override fun getCommentTokens(): TokenSet = NativeDefinitionsTokenSets.COMMENTS override fun getStringLiteralElements(): TokenSet = TokenSet.EMPTY override fun getFileNodeType(): IFileElementType = FILE override fun createLexer(project: Project): Lexer = NativeDefinitionsLexerAdapter() override fun createParser(project: Project): PsiParser = NativeDefinitionsParser() override fun createFile(viewProvider: FileViewProvider): PsiFile = NativeDefinitionsFile(viewProvider) override fun createElement(node: ASTNode): PsiElement = NativeDefinitionsTypes.Factory.createElement(node) override fun spaceExistenceTypeBetweenTokens(left: ASTNode?, right: ASTNode?): ParserDefinition.SpaceRequirements = ParserDefinition.SpaceRequirements.MAY } class CLanguageInjector : LanguageInjector { private val cLanguage = Language.findLanguageByID("ObjectiveC") override fun getLanguagesToInject(host: PsiLanguageInjectionHost, registrar: InjectedLanguagePlaces) { if (!host.isValid) return if (host is NativeDefinitionsCodeImpl && cLanguage != null) { val range = host.getTextRange().shiftLeft(host.startOffsetInParent) registrar.addPlace(cLanguage, range, null, null) } } } object NativeDefinitionsSyntaxHighlighter : SyntaxHighlighterBase() { override fun getTokenHighlights(tokenType: IElementType?): Array<TextAttributesKey> = when (tokenType) { TokenType.BAD_CHARACTER -> BAD_CHAR_KEYS NativeDefinitionsTypes.COMMENT -> COMMENT_KEYS NativeDefinitionsTypes.DELIM -> COMMENT_KEYS NativeDefinitionsTypes.SEPARATOR -> OPERATOR_KEYS NativeDefinitionsTypes.UNKNOWN_KEY -> BAD_CHAR_KEYS NativeDefinitionsTypes.UNKNOWN_PLATFORM -> BAD_CHAR_KEYS NativeDefinitionsTypes.VALUE -> VALUE_KEYS // known properties NativeDefinitionsTypes.COMPILER_OPTS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.DEPENDS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.DISABLE_DESIGNATED_INITIALIZER_CHECKS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.ENTRY_POINT -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.EXCLUDE_DEPENDENT_MODULES -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.EXCLUDE_SYSTEM_LIBS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.EXCLUDED_FUNCTIONS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.EXCLUDED_MACROS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.EXPORT_FORWARD_DECLARATIONS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.HEADERS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.HEADER_FILTER -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.LANGUAGE -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.LIBRARY_PATHS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.LINKER -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.LINKER_OPTS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.MODULES -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.NON_STRICT_ENUMS -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.NO_STRING_CONVERSION -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.PACKAGE -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.STATIC_LIBRARIES -> KNOWN_PROPERTIES_KEYS NativeDefinitionsTypes.STRICT_ENUMS -> KNOWN_PROPERTIES_KEYS // known extensions NativeDefinitionsTypes.ANDROID -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.ANDROID_X64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.ANDROID_X86 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.ANDROID_ARM32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.ANDROID_ARM64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.ARM32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.ARM64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.IOS -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.IOS_ARM32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.IOS_ARM64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.IOS_X64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.LINUX -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.LINUX_ARM32_HFP -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.LINUX_MIPS32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.LINUX_MIPSEL32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.LINUX_X64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.MACOS_X64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.MINGW -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.MINGW_X64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.MIPS32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.MIPSEL32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.OSX -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.TVOS -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.TVOS_ARM64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.TVOS_X64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.WASM -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.WASM32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.WATCHOS -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.WATCHOS_ARM32 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.WATCHOS_ARM64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.WATCHOS_X64 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.WATCHOS_X86 -> KNOWN_EXTENSIONS_KEYS NativeDefinitionsTypes.X64 -> KNOWN_EXTENSIONS_KEYS else -> EMPTY_KEYS } override fun getHighlightingLexer(): Lexer = NativeDefinitionsLexerAdapter() private fun createKeys(externalName: String, key: TextAttributesKey): Array<TextAttributesKey> { return arrayOf(TextAttributesKey.createTextAttributesKey(externalName, key)) } private val BAD_CHAR_KEYS = createKeys("Unknown key", HighlighterColors.BAD_CHARACTER) private val COMMENT_KEYS = createKeys("Comment", DefaultLanguageHighlighterColors.LINE_COMMENT) private val EMPTY_KEYS = emptyArray<TextAttributesKey>() private val KNOWN_EXTENSIONS_KEYS = createKeys("Known extension", DefaultLanguageHighlighterColors.LABEL) private val KNOWN_PROPERTIES_KEYS = createKeys("Known property", DefaultLanguageHighlighterColors.KEYWORD) private val OPERATOR_KEYS = createKeys("Operator", DefaultLanguageHighlighterColors.OPERATION_SIGN) private val VALUE_KEYS = createKeys("Value", DefaultLanguageHighlighterColors.STRING) } class NativeDefinitionsSyntaxHighlighterFactory : SyntaxHighlighterFactory() { override fun getSyntaxHighlighter(project: Project?, virtualFile: VirtualFile?): SyntaxHighlighter = NativeDefinitionsSyntaxHighlighter }
apache-2.0
ec43d6f53f836b5da4d359702745892a
51.497238
125
0.748974
5.615248
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/index/ui/GitStagePanel.kt
2
18760
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.index.ui import com.intellij.dvcs.ui.RepositoryChangesBrowserNode import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAwareWithCallbacks import com.intellij.openapi.components.service import com.intellij.openapi.progress.util.ProgressWindow import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Splitter import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.AbstractVcsHelper import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.ChangeListListener import com.intellij.openapi.vcs.changes.ChangeListManagerImpl import com.intellij.openapi.vcs.changes.ChangesViewManager.createTextStatusFactory import com.intellij.openapi.vcs.changes.EditorTabDiffPreviewManager import com.intellij.openapi.vcs.changes.InclusionListener import com.intellij.openapi.vcs.changes.ui.* import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.REPOSITORY_GROUPING import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.* import com.intellij.ui.ScrollPaneFactory.createScrollPane import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.switcher.QuickActionProvider import com.intellij.util.EditSourceOnDoubleClickHandler import com.intellij.util.EventDispatcher import com.intellij.util.OpenSourceUtil import com.intellij.util.Processor import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.JBUI import com.intellij.util.ui.JBUI.Borders.empty import com.intellij.util.ui.JBUI.Panels.simplePanel import com.intellij.util.ui.ProportionKey import com.intellij.util.ui.ThreeStateCheckBox import com.intellij.util.ui.TwoKeySplitter import com.intellij.util.ui.tree.TreeUtil import com.intellij.vcs.commit.CommitStatusPanel import com.intellij.vcs.commit.CommitWorkflowListener import com.intellij.vcs.commit.EditedCommitNode import com.intellij.vcs.log.runInEdt import com.intellij.vcs.log.runInEdtAsync import com.intellij.vcs.log.ui.frame.ProgressStripe import git4idea.GitVcs import git4idea.conflicts.GitConflictsUtil.canShowMergeWindow import git4idea.conflicts.GitConflictsUtil.showMergeWindow import git4idea.conflicts.GitMergeHandler import git4idea.i18n.GitBundle.message import git4idea.index.GitStageCommitWorkflow import git4idea.index.GitStageCommitWorkflowHandler import git4idea.index.GitStageTracker import git4idea.index.GitStageTrackerListener import git4idea.index.actions.GitAddOperation import git4idea.index.actions.GitResetOperation import git4idea.index.actions.StagingAreaOperation import git4idea.index.actions.performStageOperation import git4idea.merge.GitDefaultMergeDialogCustomizer import git4idea.repo.GitConflict import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.status.GitRefreshListener import org.jetbrains.annotations.NonNls import java.awt.BorderLayout import java.awt.event.InputEvent import java.beans.PropertyChangeListener import java.util.* import javax.swing.JPanel internal class GitStagePanel(private val tracker: GitStageTracker, isVertical: Boolean, isEditorDiffPreview: Boolean, disposableParent: Disposable, private val activate: () -> Unit) : JPanel(BorderLayout()), DataProvider, Disposable { private val project = tracker.project private val disposableFlag = Disposer.newCheckedDisposable() private val _tree: MyChangesTree val tree: ChangesTree get() = _tree private val progressStripe: ProgressStripe private val toolbar: ActionToolbar private val commitPanel: GitStageCommitPanel private val changesStatusPanel: Wrapper private val treeMessageSplitter: Splitter private val commitDiffSplitter: OnePixelSplitter private val commitWorkflowHandler: GitStageCommitWorkflowHandler private var diffPreviewProcessor: GitStageDiffPreview? = null private var editorTabPreview: GitStageEditorDiffPreview? = null private val state: GitStageTracker.State get() = tracker.state private var hasPendingUpdates = false internal val commitMessage get() = commitPanel.commitMessage init { _tree = MyChangesTree(project) commitPanel = GitStageCommitPanel(project) commitPanel.commitActionsPanel.isCommitButtonDefault = { !commitPanel.commitProgressUi.isDumbMode && IdeFocusManager.getInstance(project).getFocusedDescendantFor(this) != null } commitPanel.commitActionsPanel.createActions().forEach { it.registerCustomShortcutSet(this, this) } commitPanel.addEditedCommitListener(_tree::editedCommitChanged, this) commitPanel.setIncludedRoots(_tree.getIncludedRoots()) _tree.addIncludedRootsListener(object : IncludedRootsListener { override fun includedRootsChanged() { commitPanel.setIncludedRoots(_tree.getIncludedRoots()) } }, this) commitWorkflowHandler = GitStageCommitWorkflowHandler(GitStageCommitWorkflow(project), commitPanel) Disposer.register(this, commitPanel) val toolbarGroup = DefaultActionGroup() toolbarGroup.add(ActionManager.getInstance().getAction("Git.Stage.Toolbar")) toolbarGroup.addAll(TreeActionsToolbarPanel.createTreeActions(tree)) toolbar = ActionManager.getInstance().createActionToolbar(GIT_STAGE_PANEL_PLACE, toolbarGroup, true) toolbar.targetComponent = tree PopupHandler.installPopupMenu(tree, "Git.Stage.Tree.Menu", "Git.Stage.Tree.Menu") val statusPanel = CommitStatusPanel(commitPanel).apply { border = empty(0, 1, 0, 6) background = tree.background addToLeft(commitPanel.toolbar.component) } val sideBorder = if (ExperimentalUI.isNewUI()) SideBorder.NONE else SideBorder.TOP val treePanel = simplePanel(createScrollPane(tree, sideBorder)).addToBottom(statusPanel) progressStripe = ProgressStripe(treePanel, this, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS) val treePanelWithToolbar = JPanel(BorderLayout()) treePanelWithToolbar.add(toolbar.component, BorderLayout.NORTH) treePanelWithToolbar.add(progressStripe, BorderLayout.CENTER) treeMessageSplitter = TwoKeySplitter(true, ProportionKey("git.stage.tree.message.splitter", 0.7f, "git.stage.tree.message.splitter.horizontal", 0.5f)) treeMessageSplitter.firstComponent = treePanelWithToolbar treeMessageSplitter.secondComponent = commitPanel changesStatusPanel = Wrapper() changesStatusPanel.minimumSize = JBUI.emptySize() commitDiffSplitter = OnePixelSplitter("git.stage.commit.diff.splitter", 0.5f) commitDiffSplitter.firstComponent = treeMessageSplitter add(commitDiffSplitter, BorderLayout.CENTER) add(changesStatusPanel, BorderLayout.SOUTH) updateLayout(isVertical, isEditorDiffPreview, forceDiffPreview = true) tracker.addListener(MyGitStageTrackerListener(), this) val busConnection = project.messageBus.connect(this) busConnection.subscribe(GitRefreshListener.TOPIC, MyGitChangeProviderListener()) busConnection.subscribe(ChangeListListener.TOPIC, MyChangeListListener()) commitWorkflowHandler.workflow.addListener(MyCommitWorkflowListener(), this) if (isRefreshInProgress()) { tree.setEmptyText(message("stage.loading.status")) progressStripe.startLoadingImmediately() } updateChangesStatusPanel() Disposer.register(disposableParent, this) Disposer.register(this, disposableFlag) runInEdtAsync(disposableFlag) { update() } } private fun isRefreshInProgress(): Boolean { if (GitVcs.getInstance(project).changeProvider!!.isRefreshInProgress) return true return GitRepositoryManager.getInstance(project).repositories.any { it.untrackedFilesHolder.isInUpdateMode || it.ignoredFilesHolder.isInUpdateMode() } } private fun updateChangesStatusPanel() { val manager = ChangeListManagerImpl.getInstanceImpl(project) val factory = manager.updateException?.let { createTextStatusFactory(VcsBundle.message("error.updating.changes", it.message), true) } ?: manager.additionalUpdateInfo changesStatusPanel.setContent(factory?.create()) } @RequiresEdt fun update() { if (commitWorkflowHandler.workflow.isExecuting) { hasPendingUpdates = true return } tree.rebuildTree() commitPanel.setTrackerState(state) commitWorkflowHandler.state = state } override fun getData(dataId: String): Any? { if (QuickActionProvider.KEY.`is`(dataId)) return toolbar if (EditorTabDiffPreviewManager.EDITOR_TAB_DIFF_PREVIEW.`is`(dataId)) return editorTabPreview return null } fun updateLayout(isVertical: Boolean, canUseEditorDiffPreview: Boolean, forceDiffPreview: Boolean = false) { val isEditorDiffPreview = canUseEditorDiffPreview || isVertical val isMessageSplitterVertical = isVertical || !isEditorDiffPreview if (treeMessageSplitter.orientation != isMessageSplitterVertical) { treeMessageSplitter.orientation = isMessageSplitterVertical } setDiffPreviewInEditor(isEditorDiffPreview, forceDiffPreview) } private fun setDiffPreviewInEditor(isInEditor: Boolean, force: Boolean = false) { if (disposableFlag.isDisposed) return if (!force && (isInEditor == (editorTabPreview != null))) return if (diffPreviewProcessor != null) Disposer.dispose(diffPreviewProcessor!!) diffPreviewProcessor = GitStageDiffPreview(project, _tree, tracker, isInEditor, this) diffPreviewProcessor!!.getToolbarWrapper().setVerticalSizeReferent(toolbar.component) if (isInEditor) { editorTabPreview = GitStageEditorDiffPreview(diffPreviewProcessor!!, tree).apply { setup() } commitDiffSplitter.secondComponent = null } else { editorTabPreview = null commitDiffSplitter.secondComponent = diffPreviewProcessor!!.component } } private fun GitStageEditorDiffPreview.setup() { escapeHandler = Runnable { closePreview() activate() } installSelectionHandler(tree, false) installNextDiffActionOn(this@GitStagePanel) tree.putClientProperty(ExpandableItemsHandler.IGNORE_ITEM_SELECTION, true) } override fun dispose() { } private inner class MyChangesTree(project: Project) : GitStageTree(project, project.service<GitStageUiSettingsImpl>(), this@GitStagePanel) { override val state get() = [email protected] override val ignoredFilePaths get() = [email protected] override val operations: List<StagingAreaOperation> = listOf(GitAddOperation, GitResetOperation) private val includedRootsListeners = EventDispatcher.create(IncludedRootsListener::class.java) init { isShowCheckboxes = true setInclusionModel(GitStageRootInclusionModel(project, tracker, this@GitStagePanel)) groupingSupport.addPropertyChangeListener(PropertyChangeListener { includedRootsListeners.multicaster.includedRootsChanged() }) inclusionModel.addInclusionListener(object : InclusionListener { override fun inclusionChanged() { includedRootsListeners.multicaster.includedRootsChanged() } }) tracker.addListener(object : GitStageTrackerListener { override fun update() { includedRootsListeners.multicaster.includedRootsChanged() } }, this@GitStagePanel) doubleClickHandler = Processor { e -> if (EditSourceOnDoubleClickHandler.isToggleEvent(this, e)) return@Processor false processDoubleClickOrEnter(e, true) true } enterKeyHandler = Processor { e -> processDoubleClickOrEnter(e, false) true } } private fun processDoubleClickOrEnter(e: InputEvent?, isDoubleClick: Boolean) { val dataContext = DataManager.getInstance().getDataContext(tree) val mergeAction = ActionManager.getInstance().getAction("Git.Stage.Merge") val event = AnActionEvent.createFromAnAction(mergeAction, e, ActionPlaces.UNKNOWN, dataContext) if (ActionUtil.lastUpdateAndCheckDumb(mergeAction, event, true)) { performActionDumbAwareWithCallbacks(mergeAction, event) return } if (editorTabPreview?.processDoubleClickOrEnter(isDoubleClick) == true) return OpenSourceUtil.openSourcesFrom(dataContext, true) } fun editedCommitChanged() { rebuildTree() commitPanel.editedCommit?.let { val node = TreeUtil.findNodeWithObject(root, it) node?.let { expandPath(TreeUtil.getPathFromRoot(node)) } } } override fun customizeTreeModel(builder: TreeModelBuilder) { super.customizeTreeModel(builder) commitPanel.editedCommit?.let { val commitNode = EditedCommitNode(it) builder.insertSubtreeRoot(commitNode) builder.insertChanges(it.commit.changes, commitNode) } } override fun performStageOperation(nodes: List<GitFileStatusNode>, operation: StagingAreaOperation) { performStageOperation(project, nodes, operation) } override fun getDndOperation(targetKind: NodeKind): StagingAreaOperation? { return when (targetKind) { NodeKind.STAGED -> GitAddOperation NodeKind.UNSTAGED -> GitResetOperation else -> null } } override fun showMergeDialog(conflictedFiles: List<VirtualFile>) { AbstractVcsHelper.getInstance(project).showMergeDialog(conflictedFiles) } override fun createHoverIcon(node: ChangesBrowserGitFileStatusNode): HoverIcon? { val conflict = node.conflict ?: return null val mergeHandler = createMergeHandler(project) if (!canShowMergeWindow(project, mergeHandler, conflict)) return null return GitStageMergeHoverIcon(mergeHandler, conflict) } fun getIncludedRoots(): Collection<VirtualFile> { if (!isInclusionEnabled()) return state.allRoots return inclusionModel.getInclusion().mapNotNull { (it as? GitRepository)?.root } } fun addIncludedRootsListener(listener: IncludedRootsListener, disposable: Disposable) { includedRootsListeners.addListener(listener, disposable) } private fun isInclusionEnabled(): Boolean { return state.rootStates.size > 1 && state.stagedRoots.size > 1 && groupingSupport.isAvailable(REPOSITORY_GROUPING) && groupingSupport[REPOSITORY_GROUPING] } override fun isInclusionEnabled(node: ChangesBrowserNode<*>): Boolean { return isInclusionEnabled() && node is RepositoryChangesBrowserNode && isUnderKind(node, NodeKind.STAGED) } override fun isInclusionVisible(node: ChangesBrowserNode<*>): Boolean = isInclusionEnabled(node) override fun getIncludableUserObjects(treeModelData: VcsTreeModelData): List<Any> { return treeModelData .iterateRawNodes() .filter { node -> isIncludable(node) } .map { node -> node.userObject } .toList() } override fun getNodeStatus(node: ChangesBrowserNode<*>): ThreeStateCheckBox.State { return inclusionModel.getInclusionState(node.userObject) } private fun isUnderKind(node: ChangesBrowserNode<*>, nodeKind: NodeKind): Boolean { val nodePath = node.path ?: return false return (nodePath.find { it is MyKindNode } as? MyKindNode)?.kind == nodeKind } override fun installGroupingSupport(): ChangesGroupingSupport { val result = ChangesGroupingSupport(project, this, false) if (PropertiesComponent.getInstance(project).getList(GROUPING_PROPERTY_NAME) == null) { val oldGroupingKeys = (PropertiesComponent.getInstance(project).getList(GROUPING_KEYS) ?: DEFAULT_GROUPING_KEYS).toMutableSet() oldGroupingKeys.add(REPOSITORY_GROUPING) PropertiesComponent.getInstance(project).setList(GROUPING_PROPERTY_NAME, oldGroupingKeys.toList()) } installGroupingSupport(this, result, GROUPING_PROPERTY_NAME, DEFAULT_GROUPING_KEYS + REPOSITORY_GROUPING) return result } private inner class GitStageMergeHoverIcon(private val handler: GitMergeHandler, private val conflict: GitConflict) : HoverIcon(AllIcons.Vcs.Merge, message("changes.view.merge.action.text")) { override fun invokeAction(node: ChangesBrowserNode<*>) { showMergeWindow(project, handler, listOf(conflict)) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as GitStageMergeHoverIcon if (conflict != other.conflict) return false return true } override fun hashCode(): Int { return conflict.hashCode() } } } interface IncludedRootsListener : EventListener { fun includedRootsChanged() } private inner class MyGitStageTrackerListener : GitStageTrackerListener { override fun update() { [email protected]() } } private inner class MyGitChangeProviderListener : GitRefreshListener { override fun progressStarted() { runInEdt(disposableFlag) { updateProgressState() } } override fun progressStopped() { runInEdt(disposableFlag) { updateProgressState() } } private fun updateProgressState() { if (isRefreshInProgress()) { tree.setEmptyText(message("stage.loading.status")) progressStripe.startLoading() } else { progressStripe.stopLoading() tree.setEmptyText("") } } } private inner class MyChangeListListener : ChangeListListener { override fun changeListUpdateDone() { runInEdt(disposableFlag) { updateChangesStatusPanel() } } } private inner class MyCommitWorkflowListener : CommitWorkflowListener { override fun executionEnded() { if (hasPendingUpdates) { hasPendingUpdates = false update() } } } companion object { @NonNls private const val GROUPING_PROPERTY_NAME = "GitStage.ChangesTree.GroupingKeys" private const val GIT_STAGE_PANEL_PLACE = "GitStagePanelPlace" } } internal fun createMergeHandler(project: Project) = GitMergeHandler(project, GitDefaultMergeDialogCustomizer(project))
apache-2.0
937d7d02cc5b63c93095c60f51c0e883
37.921162
137
0.748721
5.079881
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpRequestProducer.kt
1
3805
/* * 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.client.engine.winhttp.internal import io.ktor.client.call.* import io.ktor.client.engine.* import io.ktor.client.request.* import io.ktor.http.* import io.ktor.http.content.* import io.ktor.util.* import io.ktor.utils.io.* import io.ktor.utils.io.core.* import io.ktor.utils.io.pool.* import kotlinx.atomicfu.* import kotlinx.cinterop.* import kotlinx.coroutines.* import kotlin.collections.MutableMap import kotlin.collections.mutableMapOf import kotlin.collections.set import kotlin.coroutines.* @OptIn(InternalAPI::class) internal class WinHttpRequestProducer( private val request: WinHttpRequest, private val data: HttpRequestData ) { private val closed = atomic(false) private val chunked: Boolean = request.chunkedMode == WinHttpChunkedMode.Enabled && !data.isUpgradeRequest() fun getHeaders(): Map<String, String> { val headers = data.headersToMap() if (chunked) { headers[HttpHeaders.TransferEncoding] = "chunked" } return headers } suspend fun writeBody() { if (closed.value) return val requestBody = data.body.toByteChannel() if (requestBody != null) { val readBuffer = ByteArrayPool.borrow() try { if (chunked) { writeChunkedBody(requestBody, readBuffer) } else { writeRegularBody(requestBody, readBuffer) } } finally { ByteArrayPool.recycle(readBuffer) } } } private suspend fun writeChunkedBody(requestBody: ByteReadChannel, readBuffer: ByteArray) { while (true) { val readBytes = requestBody.readAvailable(readBuffer).takeIf { it > 0 } ?: break writeBodyChunk(readBuffer, readBytes) } chunkTerminator.usePinned { src -> request.writeData(src, chunkTerminator.size) } } private suspend fun writeBodyChunk(readBuffer: ByteArray, length: Int) { // Write chunk length val chunkStart = "${length.toString(16)}\r\n".toByteArray() chunkStart.usePinned { src -> request.writeData(src, chunkStart.size) } // Write chunk data readBuffer.usePinned { src -> request.writeData(src, length) } // Write chunk ending chunkEnd.usePinned { src -> request.writeData(src, chunkEnd.size) } } private suspend fun writeRegularBody(requestBody: ByteReadChannel, readBuffer: ByteArray) { while (true) { val readBytes = requestBody.readAvailable(readBuffer).takeIf { it > 0 } ?: break readBuffer.usePinned { src -> request.writeData(src, readBytes) } } } private fun HttpRequestData.headersToMap(): MutableMap<String, String> { val result = mutableMapOf<String, String>() mergeHeaders(headers, body) { key, value -> result[key] = value } return result } private suspend fun OutgoingContent.toByteChannel(): ByteReadChannel? = when (this) { is OutgoingContent.ByteArrayContent -> ByteReadChannel(bytes()) is OutgoingContent.WriteChannelContent -> GlobalScope.writer(coroutineContext) { writeTo(channel) }.channel is OutgoingContent.ReadChannelContent -> readFrom() is OutgoingContent.NoContent -> null else -> throw UnsupportedContentTypeException(this) } companion object { private val chunkEnd = "\r\n".toByteArray() private val chunkTerminator = "0\r\n\r\n".toByteArray() } }
apache-2.0
f909362736a40f983e54fa72970b04e3
30.97479
119
0.632589
4.726708
false
false
false
false
mdanielwork/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GithubPullRequestsList.kt
1
5801
// 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 org.jetbrains.plugins.github.pullrequest.ui import com.intellij.ide.CopyProvider import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.util.Disposer import com.intellij.ui.ListUtil import com.intellij.ui.ScrollingUtil import com.intellij.ui.components.JBList import com.intellij.util.text.DateFormatUtil import com.intellij.util.ui.* import icons.GithubIcons import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import org.jetbrains.plugins.github.api.data.GithubIssueState import org.jetbrains.plugins.github.api.data.GithubSearchedIssue import org.jetbrains.plugins.github.pullrequest.avatars.CachingGithubAvatarIconsProvider import org.jetbrains.plugins.github.util.GithubUIUtil import java.awt.Component import java.awt.FlowLayout import java.awt.datatransfer.StringSelection import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.* internal class GithubPullRequestsList(private val copyPasteManager: CopyPasteManager, avatarIconsProviderFactory: CachingGithubAvatarIconsProvider.Factory, model: ListModel<GithubSearchedIssue>) : JBList<GithubSearchedIssue>(model), CopyProvider, DataProvider, Disposable { private val avatarIconSize = JBValue.UIInteger("Github.PullRequests.List.Assignee.Avatar.Size", 20) private val avatarIconsProvider = avatarIconsProviderFactory.create(avatarIconSize, this) init { selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION addMouseListener(RightClickSelectionListener()) val renderer = PullRequestsListCellRenderer() cellRenderer = renderer UIUtil.putClientProperty(this, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, listOf(renderer)) ScrollingUtil.installActions(this) Disposer.register(this, avatarIconsProvider) } override fun getToolTipText(event: MouseEvent): String? { val childComponent = ListUtil.getDeepestRendererChildComponentAt(this, event.point) if (childComponent !is JComponent) return null return childComponent.toolTipText } override fun performCopy(dataContext: DataContext) { if (selectedIndex < 0) return val selection = model.getElementAt(selectedIndex) copyPasteManager.setContents(StringSelection("#${selection.number} ${selection.title}")) } override fun isCopyEnabled(dataContext: DataContext) = !isSelectionEmpty override fun isCopyVisible(dataContext: DataContext) = false override fun getData(dataId: String) = if (PlatformDataKeys.COPY_PROVIDER.`is`(dataId)) this else null override fun dispose() {} private inner class PullRequestsListCellRenderer : ListCellRenderer<GithubSearchedIssue>, JPanel() { private val stateIcon = JLabel() private val title = JLabel() private val info = JLabel() private val labels = JPanel(FlowLayout(FlowLayout.LEFT, 4, 0)) private val assignees = JPanel().apply { layout = BoxLayout(this, BoxLayout.X_AXIS) } init { border = JBUI.Borders.empty(5, 8) layout = MigLayout(LC().gridGap("0", "0") .insets("0", "0", "0", "0") .fillX()) add(stateIcon, CC() .gapAfter("${JBUI.scale(5)}px")) add(title, CC() .minWidth("0px")) add(labels, CC() .growX() .pushX()) add(assignees, CC() .spanY(2) .wrap()) add(info, CC() .minWidth("0px") .skip(1) .spanX(2)) } override fun getListCellRendererComponent(list: JList<out GithubSearchedIssue>, value: GithubSearchedIssue, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { UIUtil.setBackgroundRecursively(this, GithubUIUtil.List.WithTallRow.background(list, isSelected)) val primaryTextColor = GithubUIUtil.List.WithTallRow.foreground(list, isSelected) val secondaryTextColor = GithubUIUtil.List.WithTallRow.secondaryForeground(list, isSelected) stateIcon.apply { icon = if (value.state == GithubIssueState.open) GithubIcons.PullRequestOpen else GithubIcons.PullRequestClosed } title.apply { text = value.title foreground = primaryTextColor } info.apply { text = "#${value.number} ${value.user.login} on ${DateFormatUtil.formatDate(value.createdAt)}" foreground = secondaryTextColor } labels.apply { removeAll() for (label in value.labels) add(GithubUIUtil.createIssueLabelLabel(label)) } assignees.apply { removeAll() for (assignee in value.assignees) { if (componentCount != 0) { add(Box.createRigidArea(JBDimension(UIUtil.DEFAULT_HGAP, 0))) } add(JLabel().apply { icon = assignee.let { avatarIconsProvider.getIcon(it) } toolTipText = assignee.login }) } } return this } } private inner class RightClickSelectionListener : MouseAdapter() { override fun mousePressed(e: MouseEvent) { if (JBSwingUtilities.isRightMouseButton(e)) { val row = locationToIndex(e.point) if (row != -1) selectionModel.setSelectionInterval(row, row) } } } }
apache-2.0
8919dbbd5c13d4d41ebb4256059a6f28
36.921569
140
0.68833
4.87479
false
false
false
false
ngthtung2805/dalatlaptop
app/src/main/java/com/tungnui/abccomputer/models/LineItem.kt
1
1258
package com.tungnui.abccomputer.models /** * Created by thanh on 28/10/2017. */ import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName data class LineItem ( @SerializedName("id") @Expose var id: Int? = null, @SerializedName("name") @Expose var name: String? = null, @SerializedName("product_id") @Expose var productId: Int? = null, @SerializedName("variation_id") @Expose var variationId: Int? = null, @SerializedName("quantity") @Expose var quantity: Int? = null, @SerializedName("tax_class") @Expose var taxClass: String? = null, @SerializedName("subtotal") @Expose var subtotal: String? = null, @SerializedName("subtotal_tax") @Expose var subtotalTax: String? = null, @SerializedName("total") @Expose var total: String? = null, @SerializedName("total_tax") @Expose var totalTax: String? = null, @SerializedName("taxes") @Expose var taxes: List<Any>? = null, @SerializedName("meta_data") @Expose var metaData: List<Any>? = null, @SerializedName("sku") @Expose var sku: String? = null, @SerializedName("price") @Expose var price: String? = null )
mit
f13bcdf44d22e156e719d326fbc40bfc
22.314815
49
0.633545
3.789157
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/appsync/src/main/kotlin/com/example/appsync/DeleteDataSource.kt
1
1727
// snippet-sourcedescription:[DeleteApiKey.kt demonstrates how to delete a unique key.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[AWS AppSync] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.example.appsync // snippet-start:[appsync.kotlin.del_ds.import] import aws.sdk.kotlin.services.appsync.AppSyncClient import aws.sdk.kotlin.services.appsync.model.DeleteDataSourceRequest import kotlin.system.exitProcess // snippet-end:[appsync.kotlin.del_ds.import] /** * Before running this Kotlin code example, set up your development environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <apiId> <keyId> Where: apiId - The Id of the API. (You can get this value from the AWS Management Console.) keyId - The Id of the key to delete. """ if (args.size != 2) { println(usage) exitProcess(1) } val apiId = args[0] val dsName = args[1] deleteDS(apiId, dsName) } // snippet-start:[appsync.kotlin.del_ds.main] suspend fun deleteDS(apiIdVal: String?, dsName: String?) { val request = DeleteDataSourceRequest { apiId = apiIdVal name = dsName } AppSyncClient { region = "us-east-1" }.use { appClient -> appClient.deleteDataSource(request) println("The data source was deleted.") } } // snippet-end:[appsync.kotlin.del_ds.main]
apache-2.0
9c9468ea2eb7850df75a0255b9da44ed
27.271186
108
0.654893
3.829268
false
false
false
false
elpassion/mainframer-intellij-plugin
src/main/kotlin/com/elpassion/mainframerplugin/common/StateProvider.kt
1
962
package com.elpassion.mainframerplugin.common import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.project.Project @State(name = "StateProvider", storages = arrayOf(Storage("mainframer_state.xml"))) class StateProvider : PersistentStateComponent<StateProvider.State> { var isTurnOn: Boolean get() = myState.isTurnOn set(value) = with(myState) { isTurnOn = value } override fun loadState(state: State) { isTurnOn = state.isTurnOn } override fun getState(): State = myState private val myState = State() class State { var isTurnOn = true } companion object { fun getInstance(project: Project): StateProvider = ServiceManager.getService(project, StateProvider::class.java) } }
apache-2.0
a3b8b1ed9a09b8f73baeabb634e6de85
28.181818
120
0.720374
4.602871
false
false
false
false
JetBrains/intellij-community
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/WithSoftLinkEntityData.kt
1
10502
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import kotlin.jvm.JvmName import kotlin.jvm.JvmOverloads import kotlin.jvm.JvmStatic import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.MutableEntityStorage // ------------------------------ Persistent Id --------------- data class NameId(private val name: String) : SymbolicEntityId<NamedEntity> { override val presentableName: String get() = name override fun toString(): String = name } data class AnotherNameId(private val name: String) : SymbolicEntityId<NamedEntity> { override val presentableName: String get() = name override fun toString(): String = name } data class ComposedId(val name: String, val link: NameId) : SymbolicEntityId<ComposedIdSoftRefEntity> { override val presentableName: String get() = "$name - ${link.presentableName}" } // ------------------------------ Entity With Persistent Id ------------------ interface NamedEntity : WorkspaceEntityWithSymbolicId { val myName: String val additionalProperty: String? val children: List<@Child NamedChildEntity> override val symbolicId: NameId get() = NameId(myName) //region generated code @GeneratedCodeApiVersion(1) interface Builder : NamedEntity, WorkspaceEntity.Builder<NamedEntity>, ObjBuilder<NamedEntity> { override var entitySource: EntitySource override var myName: String override var additionalProperty: String? override var children: List<NamedChildEntity> } companion object : Type<NamedEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(myName: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): NamedEntity { val builder = builder() builder.myName = myName builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: NamedEntity, modification: NamedEntity.Builder.() -> Unit) = modifyEntity( NamedEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addNamedEntity( name: String, additionalProperty: String? = null, source: EntitySource = MySource ): NamedEntity { val namedEntity = NamedEntity(name, source) { this.additionalProperty = additionalProperty this.children = emptyList() } this.addEntity(namedEntity) return namedEntity } //val NamedEntity.children: List<NamedChildEntity> // get() = TODO() // get() = referrers(NamedChildEntity::parent) // ------------------------------ Child of entity with persistent id ------------------ interface NamedChildEntity : WorkspaceEntity { val childProperty: String val parentEntity: NamedEntity //region generated code @GeneratedCodeApiVersion(1) interface Builder : NamedChildEntity, WorkspaceEntity.Builder<NamedChildEntity>, ObjBuilder<NamedChildEntity> { override var entitySource: EntitySource override var childProperty: String override var parentEntity: NamedEntity } companion object : Type<NamedChildEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(childProperty: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): NamedChildEntity { val builder = builder() builder.childProperty = childProperty builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: NamedChildEntity, modification: NamedChildEntity.Builder.() -> Unit) = modifyEntity( NamedChildEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addNamedChildEntity( parentEntity: NamedEntity, childProperty: String = "child", source: EntitySource = MySource ): NamedChildEntity { val namedChildEntity = NamedChildEntity(childProperty, source) { this.parentEntity = parentEntity } this.addEntity(namedChildEntity) return namedChildEntity } // ------------------------------ Entity with soft link -------------------- interface WithSoftLinkEntity : WorkspaceEntity { val link: NameId //region generated code @GeneratedCodeApiVersion(1) interface Builder : WithSoftLinkEntity, WorkspaceEntity.Builder<WithSoftLinkEntity>, ObjBuilder<WithSoftLinkEntity> { override var entitySource: EntitySource override var link: NameId } companion object : Type<WithSoftLinkEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(link: NameId, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): WithSoftLinkEntity { val builder = builder() builder.link = link builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: WithSoftLinkEntity, modification: WithSoftLinkEntity.Builder.() -> Unit) = modifyEntity( WithSoftLinkEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addWithSoftLinkEntity(link: NameId, source: EntitySource = MySource): WithSoftLinkEntity { val withSoftLinkEntity = WithSoftLinkEntity(link, source) this.addEntity(withSoftLinkEntity) return withSoftLinkEntity } interface ComposedLinkEntity : WorkspaceEntity { val link: ComposedId //region generated code @GeneratedCodeApiVersion(1) interface Builder : ComposedLinkEntity, WorkspaceEntity.Builder<ComposedLinkEntity>, ObjBuilder<ComposedLinkEntity> { override var entitySource: EntitySource override var link: ComposedId } companion object : Type<ComposedLinkEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(link: ComposedId, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ComposedLinkEntity { val builder = builder() builder.link = link builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ComposedLinkEntity, modification: ComposedLinkEntity.Builder.() -> Unit) = modifyEntity( ComposedLinkEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addComposedLinkEntity(link: ComposedId, source: EntitySource = MySource): ComposedLinkEntity { val composedLinkEntity = ComposedLinkEntity(link, source) this.addEntity(composedLinkEntity) return composedLinkEntity } // ------------------------- Entity with SymbolicId and the list of soft links ------------------ interface WithListSoftLinksEntity : WorkspaceEntityWithSymbolicId { val myName: String val links: List<NameId> override val symbolicId: AnotherNameId get() = AnotherNameId(myName) //region generated code @GeneratedCodeApiVersion(1) interface Builder : WithListSoftLinksEntity, WorkspaceEntity.Builder<WithListSoftLinksEntity>, ObjBuilder<WithListSoftLinksEntity> { override var entitySource: EntitySource override var myName: String override var links: MutableList<NameId> } companion object : Type<WithListSoftLinksEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(myName: String, links: List<NameId>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): WithListSoftLinksEntity { val builder = builder() builder.myName = myName builder.links = links.toMutableWorkspaceList() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: WithListSoftLinksEntity, modification: WithListSoftLinksEntity.Builder.() -> Unit) = modifyEntity( WithListSoftLinksEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addWithListSoftLinksEntity( name: String, links: List<NameId>, source: EntitySource = MySource ): WithListSoftLinksEntity { val withListSoftLinksEntity = WithListSoftLinksEntity(name, links, source) this.addEntity(withListSoftLinksEntity) return withListSoftLinksEntity } // --------------------------- Entity with composed persistent id via soft reference ------------------ interface ComposedIdSoftRefEntity : WorkspaceEntityWithSymbolicId { val myName: String val link: NameId override val symbolicId: ComposedId get() = ComposedId(myName, link) //region generated code @GeneratedCodeApiVersion(1) interface Builder : ComposedIdSoftRefEntity, WorkspaceEntity.Builder<ComposedIdSoftRefEntity>, ObjBuilder<ComposedIdSoftRefEntity> { override var entitySource: EntitySource override var myName: String override var link: NameId } companion object : Type<ComposedIdSoftRefEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(myName: String, link: NameId, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ComposedIdSoftRefEntity { val builder = builder() builder.myName = myName builder.link = link builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ComposedIdSoftRefEntity, modification: ComposedIdSoftRefEntity.Builder.() -> Unit) = modifyEntity( ComposedIdSoftRefEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addComposedIdSoftRefEntity( name: String, link: NameId, source: EntitySource = MySource ): ComposedIdSoftRefEntity { val composedIdSoftRefEntity = ComposedIdSoftRefEntity(name, link, source) this.addEntity(composedIdSoftRefEntity) return composedIdSoftRefEntity }
apache-2.0
d333687a0d4dea5a214fa4cc72383017
31.018293
134
0.722053
5.438633
false
false
false
false
JetBrains/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/compilation/PortableCompilationCacheUploader.kt
1
9234
// 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.intellij.build.impl.compilation import com.intellij.diagnostic.telemetry.use import com.intellij.diagnostic.telemetry.useWithScope import com.intellij.openapi.util.io.FileUtil import com.intellij.util.io.Compressor import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import okhttp3.Request import okhttp3.RequestBody import okio.BufferedSink import okio.source import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.intellij.build.impl.compilation.cache.CommitsHistory import org.jetbrains.intellij.build.impl.compilation.cache.SourcesStateProcessor import org.jetbrains.intellij.build.io.moveFile import org.jetbrains.intellij.build.io.retryWithExponentialBackOff import org.jetbrains.intellij.build.io.zipWithCompression import org.jetbrains.jps.cache.model.BuildTargetState import org.jetbrains.jps.incremental.storage.ProjectStamps import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.ForkJoinTask import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger internal class PortableCompilationCacheUploader( private val context: CompilationContext, private val remoteCache: PortableCompilationCache.RemoteCache, private val remoteGitUrl: String, private val commitHash: String, s3Folder: String, private val uploadCompilationOutputsOnly: Boolean, private val forcedUpload: Boolean, ) { private val uploadedOutputCount = AtomicInteger() private val sourcesStateProcessor = SourcesStateProcessor(context.compilationData.dataStorageRoot, context.classesOutputDirectory) private val uploader = Uploader(remoteCache.uploadUrl, remoteCache.authHeader) private val commitHistory = CommitsHistory(mapOf(remoteGitUrl to setOf(commitHash))) private val s3Folder = Path.of(s3Folder) init { FileUtil.delete(this.s3Folder) Files.createDirectories(this.s3Folder) } fun upload(messages: BuildMessages) { if (!Files.exists(sourcesStateProcessor.sourceStateFile)) { messages.warning("Compilation outputs doesn't contain source state file, " + "please enable '${ProjectStamps.PORTABLE_CACHES_PROPERTY}' flag") return } val start = System.nanoTime() val tasks = mutableListOf<ForkJoinTask<*>>() if (!uploadCompilationOutputsOnly) { // Jps Caches upload is started first because of significant size tasks.add(ForkJoinTask.adapt(::uploadJpsCaches)) } val currentSourcesState = sourcesStateProcessor.parseSourcesStateFile() uploadCompilationOutputs(currentSourcesState, uploader, tasks) ForkJoinTask.invokeAll(tasks) messages.reportStatisticValue("Compilation upload time, ms", (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start).toString())) val totalOutputs = (sourcesStateProcessor.getAllCompilationOutputs(currentSourcesState).size).toString() messages.reportStatisticValue("Total outputs", totalOutputs) messages.reportStatisticValue("Uploaded outputs", uploadedOutputCount.get().toString()) uploadMetadata() uploadToS3() } private fun uploadToS3() { spanBuilder("aws s3 sync").useWithScope { context.messages.info(awsS3Cli("sync", "--no-progress", "--include", "*", "$s3Folder", "s3://intellij-jps-cache")) println("##teamcity[setParameter name='jps.caches.aws.sync.skip' value='true']") } } private fun uploadJpsCaches() { val dataStorageRoot = context.compilationData.dataStorageRoot val zipFile = dataStorageRoot.parent.resolve(commitHash) Compressor.Zip(zipFile).use { zip -> zip.addDirectory(dataStorageRoot) } val cachePath = "caches/$commitHash" if (forcedUpload || !uploader.isExist(cachePath, true)) { uploader.upload(cachePath, zipFile) } moveFile(zipFile, s3Folder.resolve(cachePath)) } private fun uploadMetadata() { val metadataPath = "metadata/$commitHash" val sourceStateFile = sourcesStateProcessor.sourceStateFile uploader.upload(metadataPath, sourceStateFile) moveFile(sourceStateFile, s3Folder.resolve(metadataPath)) } private fun uploadCompilationOutputs(currentSourcesState: Map<String, Map<String, BuildTargetState>>, uploader: Uploader, tasks: MutableList<ForkJoinTask<*>>): List<ForkJoinTask<*>> { return sourcesStateProcessor.getAllCompilationOutputs(currentSourcesState).mapTo(tasks) { compilationOutput -> ForkJoinTask.adapt { val sourcePath = compilationOutput.remotePath val outputFolder = Path.of(compilationOutput.path) if (!Files.exists(outputFolder)) { Span.current().addEvent("$outputFolder doesn't exist, was a respective module removed?") return@adapt } val zipFile = context.paths.tempDir.resolve("compilation-output-zips").resolve(sourcePath) zipWithCompression(zipFile, mapOf(outputFolder to "")) if (forcedUpload || !uploader.isExist(sourcePath)) { uploader.upload(sourcePath, zipFile) uploadedOutputCount.incrementAndGet() } moveFile(zipFile, s3Folder.resolve(sourcePath)) } } } /** * Upload and publish file with commits history */ fun updateCommitHistory(commitHistory: CommitsHistory = this.commitHistory, overrideRemoteHistory: Boolean = false) { for (commitHash in commitHistory.commitsForRemote(remoteGitUrl)) { val cacheUploaded = uploader.isExist("caches/$commitHash") val metadataUploaded = uploader.isExist("metadata/$commitHash") if (!cacheUploaded && !metadataUploaded) { val msg = "Unable to publish $commitHash due to missing caches/$commitHash and metadata/$commitHash. " + "Probably caused by previous cleanup build." if (overrideRemoteHistory) context.messages.error(msg) else context.messages.warning(msg) return } check(cacheUploaded == metadataUploaded) { "JPS Caches are uploaded: $cacheUploaded, metadata is uploaded: $metadataUploaded" } } uploader.upload(path = CommitsHistory.JSON_FILE, file = writeCommitHistory(if (overrideRemoteHistory) commitHistory else commitHistory.plus(remoteCommitHistory()))) } private fun remoteCommitHistory(): CommitsHistory { return if (uploader.isExist(CommitsHistory.JSON_FILE)) { CommitsHistory(uploader.getAsString(CommitsHistory.JSON_FILE, remoteCache.authHeader)) } else { CommitsHistory(emptyMap()) } } private fun writeCommitHistory(commitHistory: CommitsHistory): Path { val commitHistoryFile = s3Folder.resolve(CommitsHistory.JSON_FILE) Files.createDirectories(commitHistoryFile.parent) val json = commitHistory.toJson() Files.writeString(commitHistoryFile, json) Span.current().addEvent("write commit history", Attributes.of(AttributeKey.stringKey("data"), json)) return commitHistoryFile } } private class Uploader(serverUrl: String, val authHeader: String) { private val serverUrl = toUrlWithTrailingSlash(serverUrl) fun upload(path: String, file: Path): Boolean { val url = pathToUrl(path) spanBuilder("upload").setAttribute("url", url).setAttribute("path", path).useWithScope { check(Files.exists(file)) { "The file $file does not exist" } retryWithExponentialBackOff { httpClient.newCall(Request.Builder().url(url) .header("Authorization", authHeader) .put(object : RequestBody() { override fun contentType() = MEDIA_TYPE_BINARY override fun contentLength() = Files.size(file) override fun writeTo(sink: BufferedSink) { file.source().use(sink::writeAll) } }).build()).execute().useSuccessful {} } } return true } fun isExist(path: String, logIfExists: Boolean = false): Boolean { val url = pathToUrl(path) spanBuilder("head").setAttribute("url", url).use { span -> val code = retryWithExponentialBackOff { httpClient.head(url, authHeader).use { check(it.code == 200 || it.code == 404) { "HEAD $url responded with unexpected ${it.code}" } it.code } } if (code == 200) { try { /** * FIXME dirty workaround for unreliable [serverUrl] */ httpClient.get(url, authHeader).use { it.peekBody(byteCount = 1) } } catch (ignored: Exception) { return false } if (logIfExists) { span.addEvent("File '$path' already exists on server, nothing to upload") } return true } } return false } fun getAsString(path: String, authHeader: String) = retryWithExponentialBackOff { httpClient.get(pathToUrl(path), authHeader).useSuccessful { it.body.string() } } private fun pathToUrl(path: String) = "$serverUrl${path.trimStart('/')}" }
apache-2.0
4d5adb12f11f985b9fd3bfcc4f5c96a2
38.635193
135
0.708794
4.665993
false
false
false
false
Atsky/haskell-idea-plugin
generator/src/org/jetbrains/generator/GrammarParser.kt
1
3588
package org.jetbrains.generator import org.jetbrains.generator.grammar.Grammar import org.jetbrains.generator.grammar.TokenDescription import java.util.ArrayList import org.jetbrains.generator.grammar.Rule import org.jetbrains.generator.TokenType.* import org.jetbrains.generator.grammar.Variant import org.jetbrains.generator.grammar.RuleRef import org.jetbrains.generator.grammar.NonFinalVariant import org.jetbrains.generator.grammar.FinalVariant /** * Created by atsky on 11/7/14. */ class GrammarParser(val tokens : List<Token>) { var current : Int = -1 fun parseGrammar( ) : Grammar? { match("token") match(OBRACE) val tokens = parseTokens() match(CBRACE) val rules = parseRules() return Grammar(tokens, rules) } fun text(): String { return tokens[current].text } fun parseTokens( ) : List<TokenDescription> { val list = ArrayList<TokenDescription>() while (true) { if (tryMatch(TokenType.STRING)) { val tokenText = text() list.add(TokenDescription(tokenText.substring(1, tokenText.length - 1), getNext()!!.text, true)) } else if (tryMatch(TokenType.ID)) { val tokenText = text() list.add(TokenDescription(tokenText, getNext()!!.text, false)) } else { break } } return list } fun match(text: String) { getNext() if (text() == text) { throw RuntimeException() } } fun match(expected: TokenType) : Token { val next = getNext() if (next == null || next.type != expected) { throw ParserException(next, "${expected} expected, but ${next?.type}") } return next } fun tryMatch(type: TokenType): Boolean { if (getNext()!!.type != type) { current-- return false } return true } fun getNext(): Token? { if (current < tokens.size) { current++ return if (current < tokens.size) tokens[current] else null } else { return null } } fun parseRules() : List<Rule> { val list = ArrayList<Rule>() while (!eof()) { list.add(parseRule()) } return list } fun parseRule() : Rule { val name = match(ID).text match(COLON) val variants = ArrayList<Variant>() while (true) { variants.add(parseVariant()) if (!tryMatch(VBAR)) { break } } match(SEMICOLON) return Rule(name, variants) } fun eof(): Boolean { return current >= tokens.size - 1 } fun parseVariant() : Variant { val list = ArrayList<RuleRef>() while (true) { if (tryMatch(TokenType.STRING)) { val t = text() list.add(RuleRef(t.substring(1, t.length - 1), false)) } else if (tryMatch(TokenType.ID)) { list.add(RuleRef(text(), true)) } else { break } } val name = if (tryMatch(OBRACE)) { match(TokenType.ID) val text = text() match(CBRACE) text } else { null } var variant : Variant = FinalVariant(name) for (ref in list.reversed()) { variant = NonFinalVariant(ref, listOf(variant)) } return variant } }
apache-2.0
c51f3ed417da27a1e8beb875e85ea202
23.751724
112
0.530936
4.496241
false
false
false
false
credding/injekt
src/main/kotlin/com/devtub/injekt/tooling/Provider.kt
1
5435
package com.devtub.injekt.tooling import kotlin.reflect.KClass import kotlin.reflect.primaryConstructor class Provider internal constructor(private val context: Context) { private companion object { fun shim(instance: Any): (Any?) -> Any = { instance } fun shim(kClass: KClass<*>): (Any?) -> Any = { kClass.primaryConstructor!!.call() } fun shim(factory: () -> Any): (Any?) -> Any = { factory() } fun <A> shim(factory: (A) -> Any): (Any?) -> Any = { @Suppress("UNCHECKED_CAST") factory(it as A) } } val global by lazy { Context.global.provide } val parent by lazy { context.parent!!.provide } inline fun <reified T : Any> singleton(instance: T, tag: String? = null, override: Boolean = false) { singleton(T::class, tag, instance, override) } inline fun <reified T : Any> singleton(implClass: KClass<out T>, tag: String? = null, override: Boolean = false) { singleton(T::class, tag, implClass, override) } inline fun <reified T : Any> singleton(tag: String? = null, override: Boolean = false, noinline factory: () -> T) { singleton(T::class, tag, factory, override) } inline fun <reified T : Any, A> singleton(tag: String? = null, override: Boolean = false, noinline factory: (A) -> T) { singleton(T::class, tag, factory, override) } inline fun <reified T : Any> eager(implClass: KClass<out T>, tag: String? = null, override: Boolean = false) { eager(T::class, tag, implClass, override) } inline fun <reified T : Any> eager(tag: String? = null, override: Boolean = false, noinline factory: () -> T) { eager(T::class, tag, factory, override) } inline fun <reified T : Any> thread(implClass: KClass<out T>, tag: String? = null, override: Boolean = false) { thread(T::class, tag, implClass, override) } inline fun <reified T : Any> thread(tag: String? = null, override: Boolean = false, noinline factory: () -> T) { thread(T::class, tag, factory, override) } inline fun <reified T : Any, A> thread(tag: String? = null, override: Boolean = false, noinline factory: (A) -> T) { thread(T::class, tag, factory, override) } inline fun <reified T : Any> factory(implClass: KClass<out T>, tag: String? = null, override: Boolean = false) { factory(T::class, tag, implClass, override) } inline fun <reified T : Any> factory(tag: String? = null, override: Boolean = false, noinline factory: () -> T) { factory(T::class, tag, factory, override) } inline fun <reified T : Any, A> factory(tag: String? = null, override: Boolean = false, noinline factory: (A) -> T) { factory(T::class, tag, factory, override) } fun <T : Any> singleton(kClass: KClass<T>, tag: String?, instance: T, override: Boolean) { context.provide(ProviderData(kClass, tag, ProviderScope.APPLICATION, shim(instance), false, false), override) } fun <T : Any> singleton(kClass: KClass<T>, tag: String?, implClass: KClass<out T>, override: Boolean) { context.provide(ProviderData(kClass, tag, ProviderScope.APPLICATION, shim(implClass), false, false), override) } fun <T : Any> singleton(kClass: KClass<T>, tag: String?, factory: () -> T, override: Boolean) { context.provide(ProviderData(kClass, tag, ProviderScope.APPLICATION, shim(factory), false, false), override) } fun <T : Any, A> singleton(kClass: KClass<T>, tag: String?, factory: (A) -> T, override: Boolean) { context.provide(ProviderData(kClass, tag, ProviderScope.APPLICATION, shim(factory), true, false), override) } fun <T : Any> eager(kClass: KClass<T>, tag: String?, implClass: KClass<out T>, override: Boolean) { context.provide(ProviderData(kClass, tag, ProviderScope.APPLICATION, shim(implClass), false, true), override) } fun <T : Any> eager(kClass: KClass<T>, tag: String?, factory: () -> T, override: Boolean) { context.provide(ProviderData(kClass, tag, ProviderScope.APPLICATION, shim(factory), false, true), override) } fun <T : Any> thread(kClass: KClass<T>, tag: String?, implClass: KClass<out T>, override: Boolean) { context.provide(ProviderData(kClass, tag, ProviderScope.THREAD, shim(implClass), false, false), override) } fun <T : Any> thread(kClass: KClass<T>, tag: String?, factory: () -> T, override: Boolean) { context.provide(ProviderData(kClass, tag, ProviderScope.THREAD, shim(factory), false, false), override) } fun <T : Any, A> thread(kClass: KClass<T>, tag: String?, factory: (A) -> T, override: Boolean) { context.provide(ProviderData(kClass, tag, ProviderScope.THREAD, shim(factory), true, false), override) } fun <T : Any> factory(kClass: KClass<T>, tag: String?, implClass: KClass<out T>, override: Boolean) { context.provide(ProviderData(kClass, tag, ProviderScope.INSTANCE, shim(implClass), false, false), override) } fun <T : Any> factory(kClass: KClass<T>, tag: String?, factory: () -> T, override: Boolean) { context.provide(ProviderData(kClass, tag, ProviderScope.INSTANCE, shim(factory), false, false), override) } fun <T : Any, A> factory(kClass: KClass<T>, tag: String?, factory: (A) -> T, override: Boolean) { context.provide(ProviderData(kClass, tag, ProviderScope.INSTANCE, shim(factory), true, false), override) } }
mit
21174fbbec7957860b5b4bda234c4574
47.106195
123
0.64655
3.779555
false
false
false
false
square/okio
okio/src/jvmTest/kotlin/okio/CipherAlgorithm.kt
1
2251
/* * Copyright (C) 2020 Square, Inc. and others. * * 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 okio import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec import kotlin.random.Random data class CipherAlgorithm( val transformation: String, val padding: Boolean, val keyLength: Int, val ivLength: Int? = null ) { fun createCipherFactory(random: Random): CipherFactory { val key = random.nextBytes(keyLength) val secretKeySpec = SecretKeySpec(key, transformation.substringBefore('/')) return if (ivLength == null) { CipherFactory(transformation) { mode -> init(mode, secretKeySpec) } } else { val iv = random.nextBytes(ivLength) val ivParameterSpec = IvParameterSpec(iv) CipherFactory(transformation) { mode -> init(mode, secretKeySpec, ivParameterSpec) } } } override fun toString() = transformation companion object { val BLOCK_CIPHER_ALGORITHMS get() = listOf( CipherAlgorithm("AES/CBC/NoPadding", false, 16, 16), CipherAlgorithm("AES/CBC/PKCS5Padding", true, 16, 16), CipherAlgorithm("AES/ECB/NoPadding", false, 16), CipherAlgorithm("AES/ECB/PKCS5Padding", true, 16), CipherAlgorithm("DES/CBC/NoPadding", false, 8, 8), CipherAlgorithm("DES/CBC/PKCS5Padding", true, 8, 8), CipherAlgorithm("DES/ECB/NoPadding", false, 8), CipherAlgorithm("DES/ECB/PKCS5Padding", true, 8), CipherAlgorithm("DESede/CBC/NoPadding", false, 24, 8), CipherAlgorithm("DESede/CBC/PKCS5Padding", true, 24, 8), CipherAlgorithm("DESede/ECB/NoPadding", false, 24), CipherAlgorithm("DESede/ECB/PKCS5Padding", true, 24) ) } }
apache-2.0
37e42f78cba0d447987dc786c90801a2
34.730159
79
0.68725
4.115174
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/CreateAllServicesAndExtensionsAction.kt
1
8002
// 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.ide.plugins import com.intellij.diagnostic.PluginException import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.plugins.cl.PluginClassLoader import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.extensions.impl.ExtensionPointImpl import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.runModalTask import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.psi.stubs.StubElementTypeHolderEP import com.intellij.serviceContainer.ComponentManagerImpl import io.github.classgraph.AnnotationEnumValue import io.github.classgraph.ClassGraph import io.github.classgraph.ClassInfo import java.util.function.BiConsumer import kotlin.properties.Delegates.notNull @Suppress("HardCodedStringLiteral") private class CreateAllServicesAndExtensionsAction : AnAction("Create All Services And Extensions"), DumbAware { companion object { @JvmStatic fun createAllServicesAndExtensions() { val errors = mutableListOf<Throwable>() runModalTask("Creating All Services And Extensions", cancellable = true) { indicator -> val logger = logger<ComponentManagerImpl>() val taskExecutor: (task: () -> Unit) -> Unit = { task -> try { task() } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { logger.error(e) errors.add(e) } } // check first checkExtensionPoint(StubElementTypeHolderEP.EP_NAME.point as ExtensionPointImpl<*>, taskExecutor) checkContainer(ApplicationManager.getApplication() as ComponentManagerImpl, indicator, taskExecutor) ProjectUtil.getOpenProjects().firstOrNull()?.let { checkContainer(it as ComponentManagerImpl, indicator, taskExecutor) } indicator.text2 = "Checking light services..." checkLightServices(taskExecutor) } // some errors are not thrown but logged val message = (if (errors.isEmpty()) "No errors" else "${errors.size} errors were logged") + ". Check also that no logged errors." Notification("Error Report", null, "", message, NotificationType.INFORMATION, null) .notify(null) } } override fun actionPerformed(e: AnActionEvent) { createAllServicesAndExtensions() } } @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") private val badServices = java.util.Set.of( "com.intellij.usageView.impl.UsageViewContentManagerImpl", "com.jetbrains.python.scientific.figures.PyPlotToolWindow", "org.jetbrains.plugins.grails.runner.GrailsConsole", "com.intellij.analysis.pwa.analyser.PwaServiceImpl", "com.intellij.analysis.pwa.view.toolwindow.PwaProblemsViewImpl", ) @Suppress("HardCodedStringLiteral") private fun checkContainer(container: ComponentManagerImpl, indicator: ProgressIndicator, taskExecutor: (task: () -> Unit) -> Unit) { indicator.text2 = "Checking ${container.activityNamePrefix()}services..." ComponentManagerImpl.createAllServices(container, badServices) indicator.text2 = "Checking ${container.activityNamePrefix()}extensions..." container.extensionArea.processExtensionPoints { extensionPoint -> // requires read action if (extensionPoint.name == "com.intellij.favoritesListProvider" || extensionPoint.name == "com.intellij.favoritesListProvider") { return@processExtensionPoints } checkExtensionPoint(extensionPoint, taskExecutor) } } private fun checkExtensionPoint(extensionPoint: ExtensionPointImpl<*>, taskExecutor: (task: () -> Unit) -> Unit) { extensionPoint.processImplementations(false, BiConsumer { supplier, pluginDescriptor -> var extensionClass: Class<out Any> by notNull() taskExecutor { extensionClass = extensionPoint.extensionClass } taskExecutor { try { val extension = supplier.get() if (!extensionClass.isInstance(extension)) { throw PluginException("Extension ${extension.javaClass.name} does not implement $extensionClass", pluginDescriptor.pluginId) } } catch (ignore: ExtensionNotApplicableException) { } } }) taskExecutor { extensionPoint.extensionList } } private fun checkLightServices(taskExecutor: (task: () -> Unit) -> Unit) { for (plugin in PluginManagerCore.getLoadedPlugins(null)) { // we don't check classloader for sub descriptors because url set is the same if (plugin.classLoader !is PluginClassLoader || plugin.pluginDependencies == null) { continue } ClassGraph() .enableAnnotationInfo() .ignoreParentClassLoaders() .overrideClassLoaders(plugin.classLoader) .scan() .use { scanResult -> val lightServices = scanResult.getClassesWithAnnotation(Service::class.java.name) for (lightService in lightServices) { // not clear - from what classloader light service will be loaded in reality val lightServiceClass = loadLightServiceClass(lightService, plugin) val isProjectLevel: Boolean val isAppLevel: Boolean val annotationParameterValue = lightService.getAnnotationInfo(Service::class.java.name).parameterValues.find { it.name == "value" } if (annotationParameterValue == null) { isAppLevel = lightServiceClass.declaredConstructors.any { it.parameterCount == 0 } isProjectLevel = lightServiceClass.declaredConstructors.any { it.parameterCount == 1 && it.parameterTypes.get(0) == Project::class.java } } else { val list = annotationParameterValue.value as Array<*> isAppLevel = list.any { v -> (v as AnnotationEnumValue).valueName == Service.Level.APP.name } isProjectLevel = list.any { v -> (v as AnnotationEnumValue).valueName == Service.Level.PROJECT.name } } if (isAppLevel) { taskExecutor { ApplicationManager.getApplication().getService(lightServiceClass) } } if (isProjectLevel) { taskExecutor { ProjectUtil.getOpenProjects().firstOrNull()?.getService(lightServiceClass) } } } } } } private fun loadLightServiceClass(lightService: ClassInfo, mainDescriptor: IdeaPluginDescriptorImpl): Class<*> { // for (pluginDependency in mainDescriptor.pluginDependencies!!) { val subPluginClassLoader = pluginDependency.subDescriptor?.classLoader as? PluginClassLoader ?: continue val packagePrefix = subPluginClassLoader.packagePrefix ?: continue if (lightService.name.startsWith(packagePrefix)) { return subPluginClassLoader.loadClass(lightService.name, true) } } for (pluginDependency in mainDescriptor.pluginDependencies!!) { val subPluginClassLoader = pluginDependency.subDescriptor?.classLoader as? PluginClassLoader ?: continue val clazz = subPluginClassLoader.loadClass(lightService.name, true) if (clazz != null && clazz.classLoader === subPluginClassLoader) { // light class is resolved from this sub plugin classloader - check successful return clazz } } // ok, or no plugin dependencies at all, or all are disabled, resolve from main return (mainDescriptor.classLoader as PluginClassLoader).loadClass(lightService.name, true) }
apache-2.0
5d9602f97b9a47918c7e00ce0b02292f
41.121053
149
0.72082
5.113099
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/main/kotlin/com/aemtools/refactoring/htl/rename/HtlDeclarationAttributeRenameProcessor.kt
1
3724
package com.aemtools.refactoring.htl.rename import com.aemtools.lang.util.htlAttributeName import com.aemtools.lang.util.htlVariableName import com.aemtools.lang.util.isHtlDeclarationAttribute import com.aemtools.reference.common.reference.HtlPropertyAccessReference import com.aemtools.reference.htl.reference.HtlDeclarationReference import com.aemtools.reference.htl.reference.HtlListHelperReference import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.xml.XmlAttribute import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.refactoring.rename.RenameDialog import com.intellij.refactoring.rename.RenamePsiElementProcessor import com.intellij.usageView.UsageInfo import java.awt.GridBagConstraints import javax.swing.JCheckBox import javax.swing.JPanel /** * @author Dmytro Troynikov */ class HtlDeclarationAttributeRenameProcessor : RenamePsiElementProcessor() { override fun canProcessElement(element: PsiElement): Boolean { return element is XmlAttribute && element.isHtlDeclarationAttribute() } override fun renameElement( element: PsiElement, newName: String, usages: Array<out UsageInfo>, listener: RefactoringElementListener?) { val attribute = element as? XmlAttribute ?: return val htlAttributeName = attribute.htlAttributeName() ?: return val newAttributeName = "$htlAttributeName.$newName" attribute.name = newAttributeName val htlDeclarationUsages: ArrayList<UsageInfo> = ArrayList() val htlListHelperUsages: ArrayList<UsageInfo> = ArrayList() val propertyAccessUsages: ArrayList<UsageInfo> = ArrayList() usages.filterTo(htlDeclarationUsages, { it.reference is HtlDeclarationReference }) usages.filterTo(htlListHelperUsages, { it.reference is HtlListHelperReference }) usages.filterTo(propertyAccessUsages, { it.reference is HtlPropertyAccessReference }) htlListHelperUsages.forEach { it.reference?.handleElementRename("${newName}List") } htlDeclarationUsages.forEach { it.reference?.handleElementRename(newName) } propertyAccessUsages.forEach { it.reference?.handleElementRename(newName) } listener?.elementRenamed(attribute) } override fun isInplaceRenameSupported(): Boolean { return true } override fun createRenameDialog(project: Project, element: PsiElement, nameSuggestionContext: PsiElement?, editor: Editor?): RenameDialog { return HtlAttributeRenameDialog(project, element, nameSuggestionContext, editor) } } /** * Htl attribute rename dialog. */ class HtlAttributeRenameDialog(project: Project, element: PsiElement, context: PsiElement?, editor: Editor?) : RenameDialog(project, element, context, editor) { override fun hasPreviewButton(): Boolean = false override fun isToSearchForTextOccurrencesForRename(): Boolean = false override fun isToSearchInCommentsForRename(): Boolean = false override fun createCheckboxes(panel: JPanel?, gbConstraints: GridBagConstraints?) { super.createCheckboxes(panel, gbConstraints) // hide checkboxes panel?.let { it.components.filter { it is JCheckBox }.forEach { it.isVisible = false } } } override fun getSuggestedNames(): Array<String> { val attribute = psiElement as? XmlAttribute val name = attribute?.htlVariableName() return arrayOf(name ?: "") } }
gpl-3.0
5a64dd94536e9a301fec87fa178e3fac
31.955752
89
0.720193
5.143646
false
false
false
false
zdary/intellij-community
platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileModifiableModel.kt
5
4831
// 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.codeInspection.ex import com.intellij.openapi.project.Project import com.intellij.openapi.util.InvalidDataException import com.intellij.openapi.util.WriteExternalException import com.intellij.profile.codeInspection.InspectionProjectProfileManager import com.intellij.psi.PsiElement import com.intellij.psi.search.scope.packageSet.NamedScope import com.intellij.util.Consumer open class InspectionProfileModifiableModel(val source: InspectionProfileImpl) : InspectionProfileImpl(source.name, source.myToolSupplier, source.profileManager, source.myBaseProfile, null) { private var modified = false init { myUninitializedSettings.putAll(source.myUninitializedSettings) isProjectLevel = source.isProjectLevel myLockedProfile = source.myLockedProfile copyFrom(source) } fun isChanged(): Boolean = modified || source.myLockedProfile != myLockedProfile fun setModified(value: Boolean) { modified = value } override fun resetToBase(toolId: String, scope: NamedScope?, project: Project) { super.resetToBase(toolId, scope, project) setModified(true) } override fun copyToolsConfigurations(project: Project?) { copyToolsConfigurations(source, project) } override fun createTools(project: Project?) = source.getDefaultStates(project).map { it.tool } private fun copyToolsConfigurations(profile: InspectionProfileImpl, project: Project?) { try { for (toolList in profile.myTools.values) { val tools = myTools[toolList.shortName]!! val defaultState = toolList.defaultState tools.setDefaultState(copyToolSettings(defaultState.tool), defaultState.isEnabled, defaultState.level) tools.removeAllScopes() val nonDefaultToolStates = toolList.nonDefaultTools if (nonDefaultToolStates != null) { for (state in nonDefaultToolStates) { val toolWrapper = copyToolSettings(state.tool) val scope = state.getScope(project) if (scope == null) { tools.addTool(state.scopeName, toolWrapper, state.isEnabled, state.level) } else { tools.addTool(scope, toolWrapper, state.isEnabled, state.level) } } } tools.isEnabled = toolList.isEnabled } } catch (e: WriteExternalException) { LOG.error(e) } catch (e: InvalidDataException) { LOG.error(e) } } fun isProperSetting(toolId: String): Boolean { if (myBaseProfile != null) { val tools = myBaseProfile.getToolsOrNull(toolId, null) val currentTools = myTools[toolId] return tools != currentTools } return false } fun isProperSetting(toolId: String, scope: NamedScope, project: Project): Boolean { if (myBaseProfile != null) { val baseDefaultWrapper = myBaseProfile.getToolsOrNull(toolId, null)?.defaultState?.tool val actualWrapper = myTools[toolId]?.tools?.first { s -> scope == s.getScope(project) }?.tool return baseDefaultWrapper != null && actualWrapper != null && ScopeToolState.areSettingsEqual(baseDefaultWrapper, actualWrapper) } return false } fun resetToBase(project: Project?) { initInspectionTools(project) copyToolsConfigurations(myBaseProfile, project) myChangedToolNames = null myUninitializedSettings.clear() } //invoke when isChanged() == true fun commit() { source.commit(this) modified = false } fun resetToEmpty(project: Project) { initInspectionTools(project) for (toolWrapper in getInspectionTools(null)) { setToolEnabled(toolWrapper.shortName, false, project, fireEvents = false) } } private fun InspectionProfileImpl.commit(model: InspectionProfileImpl) { name = model.name description = model.description isProjectLevel = model.isProjectLevel myLockedProfile = model.myLockedProfile myChangedToolNames = null if (model.wasInitialized()) { myTools = model.myTools } profileManager = model.profileManager scopesOrder = model.scopesOrder } fun disableTool(toolShortName: String, element: PsiElement) { getTools(toolShortName, element.project).disableTool(element) } override fun toString(): String = "$name (copy)" } fun modifyAndCommitProjectProfile(project: Project, action: Consumer<InspectionProfileModifiableModel>) { InspectionProjectProfileManager.getInstance(project).currentProfile.edit { action.consume(this) } } inline fun InspectionProfileImpl.edit(task: InspectionProfileModifiableModel.() -> Unit) { val model = InspectionProfileModifiableModel(this) model.task() model.commit() profileManager.fireProfileChanged(this) }
apache-2.0
549709ca07a5471a2df560213429a525
34.007246
191
0.72366
4.592205
false
false
false
false
zdary/intellij-community
python/src/com/jetbrains/python/actions/PyExecuteInConsole.kt
2
7687
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.actions import com.intellij.execution.ui.RunContentDescriptor import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.IdeFocusManager import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.xdebugger.XDebuggerManager import com.jetbrains.python.console.* import com.jetbrains.python.run.PythonRunConfiguration object PyExecuteInConsole { @JvmStatic fun executeCodeInConsole(project: Project, commandText: String?, editor: Editor?, canUseExistingConsole: Boolean, canUseDebugConsole: Boolean, requestFocusToConsole: Boolean, config: PythonRunConfiguration?) { var existingConsole: RunContentDescriptor? = null var isDebug = false var newConsoleListener: PydevConsoleRunner.ConsoleListener? = null if (canUseExistingConsole) { if (canUseDebugConsole) { existingConsole = getCurrentDebugConsole(project) } if (existingConsole != null) { isDebug = true } else { val virtualFile = (editor as? EditorImpl)?.virtualFile if (virtualFile != null && PyExecuteConsoleCustomizer.instance.isCustomDescriptorSupported(virtualFile)) { val (descriptor, listener) = getCustomDescriptor(project, editor) existingConsole = descriptor newConsoleListener = listener } else { existingConsole = getSelectedPythonConsole(project) } } } if (existingConsole != null) { val console = existingConsole.executionConsole (console as PyCodeExecutor).executeCode(commandText, editor) val consoleView = showConsole(project, existingConsole, isDebug) requestFocus(requestFocusToConsole, editor, consoleView) } else { startNewConsoleInstance(project, commandText, config, newConsoleListener) } } private fun getCustomDescriptor(project: Project, editor: Editor?): Pair<RunContentDescriptor?, PydevConsoleRunner.ConsoleListener?> { val virtualFile = (editor as? EditorImpl)?.virtualFile ?: return Pair(null, null) val executeCustomizer = PyExecuteConsoleCustomizer.instance when (executeCustomizer.getCustomDescriptorType(virtualFile)) { DescriptorType.NEW -> { return Pair(null, createNewConsoleListener(project, executeCustomizer, virtualFile)) } DescriptorType.EXISTING -> { val console = executeCustomizer.getExistingDescriptor(virtualFile) if (console != null && isAlive(console)) { return Pair(console, null) } else { return Pair(null, createNewConsoleListener(project, executeCustomizer, virtualFile)) } } else -> { throw IllegalStateException("Custom descriptor for ${virtualFile} is null") } } } private fun createNewConsoleListener(project: Project, executeCustomizer: PyExecuteConsoleCustomizer, virtualFile: VirtualFile): PydevConsoleRunner.ConsoleListener { return PydevConsoleRunner.ConsoleListener { consoleView -> val consoles = getAllRunningConsoles(project) val newDescriptor = consoles.find { it.executionConsole === consoleView } executeCustomizer.updateDescriptor(virtualFile, DescriptorType.EXISTING, newDescriptor) } } private fun getCurrentDebugConsole(project: Project): RunContentDescriptor? { XDebuggerManager.getInstance(project).currentSession?.let { currentSession -> val descriptor = currentSession.runContentDescriptor if (isAlive(descriptor)) { return descriptor } } return null } fun getAllRunningConsoles(project: Project?): List<RunContentDescriptor> { val toolWindow = PythonConsoleToolWindow.getInstance(project!!) return if (toolWindow != null && toolWindow.isInitialized) { toolWindow.consoleContentDescriptors.filter { isAlive(it) } } else emptyList() } private fun getSelectedPythonConsole(project: Project): RunContentDescriptor? { val toolWindow = PythonConsoleToolWindow.getInstance(project) ?: return null if (!toolWindow.isInitialized) return null val consoles = toolWindow.consoleContentDescriptors.filter { isAlive(it) } return consoles.singleOrNull() ?: toolWindow.selectedContentDescriptor.takeIf { it in consoles } ?: consoles.firstOrNull() } fun isAlive(dom: RunContentDescriptor): Boolean { val processHandler = dom.processHandler return processHandler != null && !processHandler.isProcessTerminated } private fun startNewConsoleInstance(project: Project, runFileText: String?, config: PythonRunConfiguration?, listener: PydevConsoleRunner.ConsoleListener?) { val consoleRunnerFactory = PythonConsoleRunnerFactory.getInstance() val runner = if (runFileText == null || config == null) { consoleRunnerFactory.createConsoleRunner(project, null) } else { consoleRunnerFactory.createConsoleRunnerWithFile(project, null, runFileText, config) } val toolWindow = PythonConsoleToolWindow.getInstance(project) runner.addConsoleListener { consoleView -> if (consoleView is PyCodeExecutor) { (consoleView as PyCodeExecutor).executeCode(runFileText, null) toolWindow?.toolWindow?.show(null) } } if (listener != null) { runner.addConsoleListener(listener) } runner.run(false) } private fun showConsole(project: Project, descriptor: RunContentDescriptor, isDebug: Boolean): PythonConsoleView? { if (isDebug) { val console = descriptor.executionConsole val currentSession = XDebuggerManager.getInstance(project).currentSession if (currentSession != null) { ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.DEBUG)?.let { debugToolWindow -> if (!debugToolWindow.isVisible) { debugToolWindow.show() } } // Select "Console" tab in case of Debug console val contentManager = currentSession.ui.contentManager contentManager.findContent("Console")?.let { content -> contentManager.setSelectedContent(content) } return (console as PythonDebugLanguageConsoleView).pydevConsoleView } } else { PythonConsoleToolWindow.getInstance(project)?.toolWindow?.let { toolWindow -> if (!toolWindow.isVisible) { toolWindow.show(null) } val contentManager = toolWindow.contentManager contentManager.findContent(PyExecuteConsoleCustomizer.instance.getDescriptorName(descriptor))?.let { contentManager.setSelectedContent(it) } } return descriptor.executionConsole as? PythonConsoleView } return null } private fun requestFocus(requestFocusToConsole: Boolean, editor: Editor?, consoleView: PythonConsoleView?) { if (requestFocusToConsole) { consoleView?.requestFocus() } else { if (editor != null) { IdeFocusManager.findInstance().requestFocus(editor.contentComponent, true) } } } }
apache-2.0
a54b5af6e7d525e8ce6e9b3b1edee877
39.463158
140
0.685573
5.52227
false
false
false
false
blokadaorg/blokada
android5/app/src/main/java/ui/settings/leases/LeasesAdapter.kt
1
2905
/* * This file is part of Blokada. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package ui.settings.leases import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.View.OnClickListener import android.widget.TextView import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import model.Lease import org.blokada.R class LeasesAdapter(private val interaction: Interaction) : ListAdapter<Lease, LeasesAdapter.LeaseViewHolder>(LeaseDC()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = LeaseViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.item_lease, parent, false), interaction ) override fun onBindViewHolder(holder: LeaseViewHolder, position: Int) = holder.bind(getItem(position)) fun swapData(data: List<Lease>) { submitList(data.toMutableList()) } inner class LeaseViewHolder( itemView: View, private val interaction: Interaction ) : RecyclerView.ViewHolder(itemView), OnClickListener { private val name: TextView = itemView.findViewById(R.id.lease_name) private val deleteButton: View = itemView.findViewById(R.id.lease_delete) private val thisDevice: View = itemView.findViewById(R.id.lease_thisdevice) init { deleteButton.setOnClickListener(this) } override fun onClick(v: View) { if (adapterPosition == RecyclerView.NO_POSITION) return val clicked = getItem(adapterPosition) interaction.onDelete(clicked) itemView.alpha = 0.5f } fun bind(item: Lease) = with(itemView) { name.text = item.niceName() if (interaction.isThisDevice(item)) { thisDevice.visibility = View.VISIBLE deleteButton.visibility = View.GONE } else { thisDevice.visibility = View.GONE deleteButton.visibility = View.VISIBLE } } } interface Interaction { fun onDelete(lease: Lease) fun isThisDevice(lease: Lease): Boolean } private class LeaseDC : DiffUtil.ItemCallback<Lease>() { override fun areItemsTheSame( oldItem: Lease, newItem: Lease ): Boolean { return oldItem == newItem } override fun areContentsTheSame( oldItem: Lease, newItem: Lease ): Boolean { return oldItem == newItem } } }
mpl-2.0
109a5c55d9191577ec7d3b603fa6d42e
30.236559
88
0.650826
4.661316
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/methodCallExpression/stringMethods.kt
5
4073
// ERROR: Type mismatch: inferred type is String but Charset was expected // ERROR: Type mismatch: inferred type is String but Charset was expected import java.nio.charset.Charset import java.util.Locale internal class A { @Throws(Exception::class) fun constructors() { String() // TODO: new String("original"); String(charArrayOf('a', 'b', 'c')) String(charArrayOf('b', 'd'), 1, 1) String(intArrayOf(32, 65, 127), 0, 3) val bytes = byteArrayOf(32, 65, 100, 81) val charset = Charset.forName("utf-8") String(bytes) String(bytes, charset) String(bytes, 0, 2) String(bytes, "utf-8") String(bytes, 0, 2, "utf-8") String(bytes, 0, 2, charset) String(StringBuilder("content")) String(StringBuffer("content")) } fun normalMethods() { val s = "test string" s.length s.isEmpty() s[1] s.codePointAt(2) s.codePointBefore(2) s.codePointCount(0, s.length) s.offsetByCodePoints(0, 4) s.compareTo("test 2") s.contains("seq") s.contentEquals(StringBuilder(s)) s.contentEquals(StringBuffer(s)) s.endsWith("ng") s.startsWith("te") s.startsWith("st", 2) s.indexOf("st") s.indexOf("st", 5) s.lastIndexOf("st") s.lastIndexOf("st", 4) s.indexOf('t') s.indexOf('t', 5) s.lastIndexOf('t') s.lastIndexOf('t', 5) s.substring(1) s.substring(0, 4) s.subSequence(0, 4) s.replace('e', 'i') s.replace("est", "oast") s.intern() s.lowercase(Locale.getDefault()) s.lowercase(Locale.FRENCH) s.uppercase(Locale.getDefault()) s.uppercase(Locale.FRENCH) s s.toCharArray() } @Throws(Exception::class) fun specialMethods() { val s = "test string" s == "test" s.equals( "tesT", ignoreCase = true ) s.compareTo("Test", ignoreCase = true) s.regionMatches( 0, "TE", 0, 2, ignoreCase = true ) s.regionMatches(0, "st", 1, 2) s.replace("\\w+".toRegex(), "---") .replaceFirst("([s-t])".toRegex(), "A$1") useSplit(s.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) useSplit(s.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) useSplit(s.split("\\s+".toRegex()).toTypedArray()) useSplit(s.split("\\s+".toRegex(), limit = 2).toTypedArray()) val pattern = "\\s+" useSplit(s.split(pattern.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) val limit = 5 useSplit(s.split("\\s+".toRegex(), limit.coerceAtLeast(0)).toTypedArray()) useSplit(s.split("\\s+".toRegex(), (limit + 5).coerceAtLeast(0)).toTypedArray()) /* TODO s.matches("\\w+"); */s.trim { it <= ' ' } "$s another" s.toByteArray() s.toByteArray(Charset.forName("utf-8")) s.toByteArray(charset("utf-8")) val chars = CharArray(10) s.toCharArray(chars, 0, 1, 11) } fun staticMethods() { 1.toString() 1L.toString() 'a'.toString() true.toString() 1.11f.toString() 3.14.toString() Any().toString() String.format( Locale.FRENCH, "Je ne mange pas %d jours", 6 ) String.format("Operation completed with %s", "success") val chars = charArrayOf('a', 'b', 'c') String(chars) String(chars, 1, 2) String(chars) String(chars, 1, 2) val order = java.lang.String.CASE_INSENSITIVE_ORDER } fun unsupportedMethods() { val s = "test string" /* TODO: s.indexOf(32); s.indexOf(32, 2); s.lastIndexOf(32); s.lastIndexOf(32, 2); */ } fun useSplit(result: Array<String?>?) {} }
apache-2.0
ddf8d3ba02091cf164ed90e65e3afdfb
29.395522
90
0.523693
3.871673
false
true
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/FixCharacterValuesActivity.kt
1
5016
package com.habitrpg.android.habitica.ui.activities import android.app.ProgressDialog import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import androidx.core.content.ContextCompat import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.databinding.ActivityFixcharacterBinding import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.user.Stats import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.modules.AppModule import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import com.habitrpg.android.habitica.ui.views.settings.FixValuesEditText import io.reactivex.functions.Action import io.reactivex.functions.Consumer import javax.inject.Inject import javax.inject.Named class FixCharacterValuesActivity: BaseActivity() { private lateinit var binding: ActivityFixcharacterBinding @Inject lateinit var repository: UserRepository @field:[Inject Named(AppModule.NAMED_USER_ID)] lateinit var userId: String override fun getLayoutResId(): Int = R.layout.activity_fixcharacter override fun getContentView(): View { binding = ActivityFixcharacterBinding.inflate(layoutInflater) return binding.root } override fun injectActivity(component: UserComponent?) { component?.inject(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setTitle(R.string.fix_character_values) setupToolbar(binding.toolbar) compositeSubscription.add(repository.getUser(userId).firstElement().subscribe(Consumer { user = it }, RxErrorHandler.handleEmptyError())) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_save, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == R.id.action_save_changes) { @Suppress("DEPRECATION") val progressDialog = ProgressDialog.show(this, getString(R.string.saving), "") val userInfo = HashMap<String, Any>() userInfo["stats.hp"] = binding.healthEditText.getDoubleValue() userInfo["stats.exp"] = binding.experienceEditText.getDoubleValue() userInfo["stats.gp"] = binding.goldEditText.getDoubleValue() userInfo["stats.mp"] = binding.manaEditText.getDoubleValue() userInfo["stats.lvl"] = binding.levelEditText.getDoubleValue().toInt() userInfo["achievements.streak"] = binding.streakEditText.getDoubleValue().toInt() compositeSubscription.add(repository.updateUser(user, userInfo).subscribe(Consumer {}, RxErrorHandler.handleEmptyError(), Action { progressDialog.dismiss() finish() })) return true } return super.onOptionsItemSelected(item) } private var user: User? = null set(value) { field = value if (value != null) { updateFields(value) } } private fun updateFields(user: User) { val stats = user.stats ?: return binding.healthEditText.text = stats.hp.toString() binding.experienceEditText.text = stats.exp.toString() binding.goldEditText.text = stats.gp.toString() binding.manaEditText.text = stats.mp.toString() binding.levelEditText.text = stats.lvl.toString() binding.streakEditText.text = user.streakCount.toString() when (stats.habitClass) { Stats.WARRIOR -> { binding.levelEditText.iconBackgroundColor = ContextCompat.getColor(this, R.color.red_500) binding.levelEditText.setIconBitmap(HabiticaIconsHelper.imageOfWarriorLightBg()) } Stats.MAGE -> { binding.levelEditText.iconBackgroundColor = ContextCompat.getColor(this, R.color.blue_500) binding.levelEditText.setIconBitmap(HabiticaIconsHelper.imageOfMageLightBg()) } Stats.HEALER -> { binding.levelEditText.iconBackgroundColor = ContextCompat.getColor(this, R.color.yellow_500) binding.levelEditText.setIconBitmap(HabiticaIconsHelper.imageOfHealerLightBg()) } Stats.ROGUE -> { binding.levelEditText.iconBackgroundColor = ContextCompat.getColor(this, R.color.brand_500) binding.levelEditText.setIconBitmap(HabiticaIconsHelper.imageOfRogueLightBg()) } } } private fun FixValuesEditText.getDoubleValue(): Double { val stringValue = this.text return try { stringValue.toDouble() } catch (_: NumberFormatException) { 0.0 } } }
gpl-3.0
96d528fe18b87b9c60f38c011f500124
37.891473
142
0.686204
4.879377
false
false
false
false
mvysny/vaadin-on-kotlin
vok-framework-vokdb/src/test/kotlin/eu/vaadinonkotlin/vaadin/vokdb/DataProvidersTest.kt
1
3140
package eu.vaadinonkotlin.vaadin.vokdb import com.github.mvysny.dynatest.DynaTest import com.github.mvysny.dynatest.expectList import com.github.mvysny.karibudsl.v10.grid import com.github.mvysny.kaributesting.v10.MockVaadin import com.github.mvysny.kaributesting.v10._findAll import com.github.mvysny.kaributesting.v10.getSuggestions import com.github.mvysny.kaributesting.v10.setUserInput import com.github.vokorm.dataloader.SqlDataLoader import com.github.vokorm.dataloader.dataLoader import com.vaadin.flow.component.UI import com.vaadin.flow.component.combobox.ComboBox import com.vaadin.flow.component.grid.Grid import kotlin.test.expect class DataProvidersTest : DynaTest({ group("API test: populating components with data providers") { usingH2Database() beforeEach { MockVaadin.setup() } afterEach { MockVaadin.tearDown() } group("combobox") { // test that the EntityDataProvider and SqlDataProviders are compatible with Vaadin ComboBox // since ComboBox emits String as a filter (it emits whatever the user typed into the ComboBox). test("entity data provider") { (0..10).forEach { Person(null, "foo $it", it).save() } val dp = Person.dataLoader val cb = ComboBox<Person>().apply { setItemLabelGenerator { it.personName } setItems(dp.withStringFilterOn(Person::personName)) } expect((0..10).map { "foo $it" }) { cb.getSuggestions() } cb.setUserInput("foo 1") expectList("foo 1", "foo 10") { cb.getSuggestions() } } // tests that the EntityDataProvider and SqlDataProviders are compatible with Vaadin ComboBox // since ComboBox emits String as a filter (it emits whatever the user typed into the ComboBox). test("sql data provider") { (0..10).forEach { Person(null, "foo $it", it).save() } val dp = SqlDataLoader(Person::class.java, "select * from Test where 1=1 {{WHERE}} order by 1=1{{ORDER}} {{PAGING}}") val cb = ComboBox<Person>().apply { setItemLabelGenerator { it.personName } setItems(dp.withStringFilterOn("name")) } expect((0..10).map { "foo $it" }) { cb.getSuggestions() } cb.setUserInput("foo 1") expectList("foo 1", "foo 10") { cb.getSuggestions() } } } group("grid") { // test that the EntityDataProvider and SqlDataProviders are compatible with Vaadin ComboBox // since ComboBox emits String as a filter (it emits whatever the user typed into the ComboBox). test("entity data provider") { (0..10).forEach { Person(null, "foo $it", it).save() } val cb: Grid<Person> = UI.getCurrent().grid<Person> { setDataLoader(Person.dataLoader) } expect((0..10).map { "foo $it" }) { cb._findAll().map { it.personName } } } } } })
mit
291d57e36feb49a9ed10fdbe23060f1c
47.307692
133
0.608599
4.313187
false
true
false
false
moko256/twicalico
app/src/main/java/com/github/moko256/twitlatte/EmojiAdapter.kt
1
2743
/* * Copyright 2015-2019 The twitlatte authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.moko256.twitlatte import android.content.Context import android.view.ViewGroup import android.widget.ImageView import androidx.annotation.DrawableRes import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.RequestManager import com.github.moko256.latte.client.base.entity.Emoji import com.github.moko256.twitlatte.view.dpToPx /** * Created by moko256 on 2018/12/11. * * @author moko256 */ class EmojiAdapter( private val list: List<Emoji>, private val context: Context, private val glideRequests: RequestManager, private val onEmojiClick: (Emoji) -> Unit, private val onLoadClick: () -> Unit ) : RecyclerView.Adapter<EmojiViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EmojiViewHolder { val imageView = ImageView(context) val dp32 = context.dpToPx(32) imageView.layoutParams = ViewGroup.LayoutParams(dp32, dp32) return EmojiViewHolder( imageView = imageView, glideRequests = glideRequests ) } override fun getItemCount(): Int { return list.size + 1 } override fun onBindViewHolder(holder: EmojiViewHolder, position: Int) { if (position != list.size) { val emoji = list[position] holder.setImage(emoji.url) holder.itemView.setOnClickListener { onEmojiClick(emoji) } } else { holder.setImage(R.drawable.list_add_icon) holder.itemView.setOnClickListener { onLoadClick() } } } override fun onViewRecycled(holder: EmojiViewHolder) { holder.clearImage() } } class EmojiViewHolder(private val imageView: ImageView, private val glideRequests: RequestManager) : RecyclerView.ViewHolder(imageView) { fun setImage(url: String) { glideRequests.load(url).into(imageView) } fun setImage(@DrawableRes resId: Int) { glideRequests.load(resId).into(imageView) } fun clearImage() { glideRequests.clear(imageView) } }
apache-2.0
50e1e9d7862d2ee07300a1c6c18291e0
30.54023
137
0.67809
4.571667
false
false
false
false
JetBrains/xodus
entity-store/src/main/kotlin/jetbrains/exodus/crypto/EncryptedBlobVault.kt
1
4305
/** * Copyright 2010 - 2022 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 * * 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 jetbrains.exodus.crypto import jetbrains.exodus.core.dataStructures.hash.LongHashMap import jetbrains.exodus.core.dataStructures.hash.LongSet import jetbrains.exodus.entitystore.BlobVault import jetbrains.exodus.entitystore.BlobVaultItem import jetbrains.exodus.entitystore.DiskBasedBlobVault import jetbrains.exodus.entitystore.FileSystemBlobVaultOld import jetbrains.exodus.env.Transaction import java.io.File import java.io.FileInputStream import java.io.InputStream import java.io.OutputStream class EncryptedBlobVault(private val decorated: FileSystemBlobVaultOld, private val cipherProvider: StreamCipherProvider, private val cipherKey: ByteArray, private val cipherBasicIV: Long) : BlobVault(decorated), DiskBasedBlobVault { override fun getSourceVault() = decorated override fun clear() = decorated.clear() override fun getBackupStrategy() = decorated.backupStrategy override fun getBlob(blobHandle: Long): BlobVaultItem { return decorated.getBlob(blobHandle) } override fun getContent(blobHandle: Long, txn: Transaction): InputStream? { return decorated.getContent(blobHandle, txn)?.run { StreamCipherInputStream(this) { newCipher(blobHandle) } } } override fun delete(blobHandle: Long): Boolean { return decorated.delete(blobHandle) } override fun getBlobLocation(blobHandle: Long): File { return decorated.getBlobLocation(blobHandle) } override fun getBlobLocation(blobHandle: Long, readonly: Boolean): File { return decorated.getBlobLocation(blobHandle, readonly) } override fun getBlobKey(blobHandle: Long): String { return decorated.getBlobKey(blobHandle) } override fun getSize(blobHandle: Long, txn: Transaction) = decorated.getSize(blobHandle, txn) override fun requiresTxn() = decorated.requiresTxn() override fun flushBlobs(blobStreams: LongHashMap<InputStream>?, blobFiles: LongHashMap<File>?, deferredBlobsToDelete: LongSet?, txn: Transaction) { val streams = LongHashMap<InputStream>() blobStreams?.forEach { streams[it.key] = StreamCipherInputStream(it.value) { newCipher(it.key) } } var openFiles: MutableList<InputStream>? = null try { if (blobFiles != null && blobFiles.isNotEmpty()) { openFiles = mutableListOf() blobFiles.forEach { streams[it.key] = StreamCipherInputStream( FileInputStream(it.value) .also { openFiles.add(it) } .asBuffered .apply { mark(Int.MAX_VALUE) } ) { newCipher(it.key) } } } decorated.flushBlobs(streams, null, deferredBlobsToDelete, txn) } finally { openFiles?.forEach { it.close() } } } override fun size() = decorated.size() override fun nextHandle(txn: Transaction) = decorated.nextHandle(txn) override fun close() = decorated.close() fun wrapOutputStream(blobHandle: Long, output: OutputStream): StreamCipherOutputStream { return StreamCipherOutputStream(output, newCipher(blobHandle)) } private fun newCipher(blobHandle: Long) = cipherProvider.newCipher().apply { init(cipherKey, (cipherBasicIV - blobHandle).asHashedIV()) } }
apache-2.0
2f9281ddd1de10143f8142bf57b9cf4d
36.112069
107
0.645296
5.046893
false
false
false
false
siosio/intellij-community
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/configuration/KotlinGradleSourceSetDataService.kt
1
14970
// 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.application.ApplicationManager import com.intellij.openapi.application.runReadAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.LibraryData import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.util.Key import com.intellij.util.PathUtil import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments import org.jetbrains.kotlin.config.* import org.jetbrains.kotlin.extensions.ProjectExtensionDescriptor import org.jetbrains.kotlin.gradle.ArgsInfo import org.jetbrains.kotlin.gradle.CompilerArgumentsBySourceSet import org.jetbrains.kotlin.ide.konan.NativeLibraryKind import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCommonCompilerArgumentsHolder import org.jetbrains.kotlin.idea.configuration.GradlePropertiesFileFacade.Companion.KOTLIN_CODE_STYLE_GRADLE_SETTING import org.jetbrains.kotlin.idea.configuration.klib.KotlinNativeLibraryNameUtil.KOTLIN_NATIVE_LIBRARY_PREFIX import org.jetbrains.kotlin.idea.facet.* import org.jetbrains.kotlin.idea.formatter.ProjectCodeStyleImporter import org.jetbrains.kotlin.idea.framework.CommonLibraryKind import org.jetbrains.kotlin.idea.framework.JSLibraryKind import org.jetbrains.kotlin.idea.framework.detectLibraryKind import org.jetbrains.kotlin.idea.gradle.KotlinGradleFacadeImpl import org.jetbrains.kotlin.idea.inspections.gradle.getResolvedVersionByModuleData import org.jetbrains.kotlin.idea.platform.tooling import org.jetbrains.kotlin.idea.roots.findAll import org.jetbrains.kotlin.idea.roots.migrateNonJvmSourceFolders import org.jetbrains.kotlin.idea.statistics.KotlinGradleFUSLogger import org.jetbrains.kotlin.library.KLIB_FILE_EXTENSION import org.jetbrains.kotlin.platform.IdePlatformKind import org.jetbrains.kotlin.platform.impl.isCommon import org.jetbrains.kotlin.platform.impl.isJavaScript import org.jetbrains.kotlin.platform.impl.isJvm import org.jetbrains.kotlin.psi.UserDataProperty import org.jetbrains.plugins.gradle.model.data.BuildScriptClasspathData import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData import org.jetbrains.plugins.gradle.util.GradleConstants import java.io.File import java.util.* var Module.compilerArgumentsBySourceSet by UserDataProperty(Key.create<CompilerArgumentsBySourceSet>("CURRENT_COMPILER_ARGUMENTS")) var Module.sourceSetName by UserDataProperty(Key.create<String>("SOURCE_SET_NAME")) interface GradleProjectImportHandler { companion object : ProjectExtensionDescriptor<GradleProjectImportHandler>( "org.jetbrains.kotlin.gradleProjectImportHandler", GradleProjectImportHandler::class.java ) fun importBySourceSet(facet: KotlinFacet, sourceSetNode: DataNode<GradleSourceSetData>) fun importByModule(facet: KotlinFacet, moduleNode: DataNode<ModuleData>) } class KotlinGradleProjectSettingsDataService : AbstractProjectDataService<ProjectData, Void>() { override fun getTargetDataKey() = ProjectKeys.PROJECT override fun postProcess( toImport: MutableCollection<out DataNode<ProjectData>>, projectData: ProjectData?, project: Project, modelsProvider: IdeModifiableModelsProvider ) { val allSettings = modelsProvider.modules.mapNotNull { module -> if (module.isDisposed) return@mapNotNull null val settings = modelsProvider .getModifiableFacetModel(module) .findFacet(KotlinFacetType.TYPE_ID, KotlinFacetType.INSTANCE.defaultFacetName) ?.configuration ?.settings ?: return@mapNotNull null if (settings.useProjectSettings) null else settings } val languageVersion = allSettings.asSequence().mapNotNullTo(LinkedHashSet()) { it.languageLevel }.singleOrNull() val apiVersion = allSettings.asSequence().mapNotNullTo(LinkedHashSet()) { it.apiLevel }.singleOrNull() KotlinCommonCompilerArgumentsHolder.getInstance(project).update { if (languageVersion != null) { this.languageVersion = languageVersion.versionString } if (apiVersion != null) { this.apiVersion = apiVersion.versionString } } } } class KotlinGradleSourceSetDataService : AbstractProjectDataService<GradleSourceSetData, Void>() { override fun getTargetDataKey() = GradleSourceSetData.KEY override fun postProcess( toImport: Collection<out DataNode<GradleSourceSetData>>, projectData: ProjectData?, project: Project, modelsProvider: IdeModifiableModelsProvider ) { for (sourceSetNode in toImport) { val sourceSetData = sourceSetNode.data val ideModule = modelsProvider.findIdeModule(sourceSetData) ?: continue val moduleNode = ExternalSystemApiUtil.findParent(sourceSetNode, ProjectKeys.MODULE) ?: continue val kotlinFacet = configureFacetByGradleModule(ideModule, modelsProvider, moduleNode, sourceSetNode) ?: continue GradleProjectImportHandler.getInstances(project).forEach { it.importBySourceSet(kotlinFacet, sourceSetNode) } } } } class KotlinGradleProjectDataService : AbstractProjectDataService<ModuleData, Void>() { override fun getTargetDataKey() = ProjectKeys.MODULE override fun postProcess( toImport: MutableCollection<out DataNode<ModuleData>>, projectData: ProjectData?, project: Project, modelsProvider: IdeModifiableModelsProvider ) { for (moduleNode in toImport) { // If source sets are present, configure facets in the their modules if (ExternalSystemApiUtil.getChildren(moduleNode, GradleSourceSetData.KEY).isNotEmpty()) continue val moduleData = moduleNode.data val ideModule = modelsProvider.findIdeModule(moduleData) ?: continue val kotlinFacet = configureFacetByGradleModule(ideModule, modelsProvider, moduleNode, null) ?: continue GradleProjectImportHandler.getInstances(project).forEach { it.importByModule(kotlinFacet, moduleNode) } } runReadAction { val codeStyleStr = GradlePropertiesFileFacade.forProject(project).readProperty(KOTLIN_CODE_STYLE_GRADLE_SETTING) ProjectCodeStyleImporter.apply(project, codeStyleStr) } ApplicationManager.getApplication().executeOnPooledThread { KotlinGradleFUSLogger.reportStatistics() } } } class KotlinGradleLibraryDataService : AbstractProjectDataService<LibraryData, Void>() { override fun getTargetDataKey() = ProjectKeys.LIBRARY override fun postProcess( toImport: MutableCollection<out DataNode<LibraryData>>, projectData: ProjectData?, project: Project, modelsProvider: IdeModifiableModelsProvider ) { if (toImport.isEmpty()) return val projectDataNode = toImport.first().parent!! @Suppress("UNCHECKED_CAST") val moduleDataNodes = projectDataNode.children.filter { it.data is ModuleData } as List<DataNode<ModuleData>> val anyNonJvmModules = moduleDataNodes .any { node -> detectPlatformKindByPlugin(node)?.takeIf { !it.isJvm } != null } for (libraryDataNode in toImport) { val ideLibrary = modelsProvider.findIdeLibrary(libraryDataNode.data) ?: continue val modifiableModel = modelsProvider.getModifiableLibraryModel(ideLibrary) as LibraryEx.ModifiableModelEx if (anyNonJvmModules || ideLibrary.looksAsNonJvmLibrary()) { detectLibraryKind(modifiableModel.getFiles(OrderRootType.CLASSES))?.let { modifiableModel.kind = it } } else if ( ideLibrary is LibraryEx && (ideLibrary.kind === JSLibraryKind || ideLibrary.kind === NativeLibraryKind || ideLibrary.kind === CommonLibraryKind) ) { modifiableModel.kind = null } } } private fun Library.looksAsNonJvmLibrary(): Boolean { name?.let { name -> if (nonJvmSuffixes.any { it in name } || name.startsWith(KOTLIN_NATIVE_LIBRARY_PREFIX)) return true } return getFiles(OrderRootType.CLASSES).firstOrNull()?.extension == KLIB_FILE_EXTENSION } companion object { val LOG = Logger.getInstance(KotlinGradleLibraryDataService::class.java) val nonJvmSuffixes = listOf("-common", "-js", "-native", "-kjsm", "-metadata") } } fun detectPlatformKindByPlugin(moduleNode: DataNode<ModuleData>): IdePlatformKind<*>? { val pluginId = moduleNode.platformPluginId return IdePlatformKind.ALL_KINDS.firstOrNull { it.tooling.gradlePluginId == pluginId } } @Suppress("DEPRECATION_ERROR") @Deprecated( "Use detectPlatformKindByPlugin() instead", replaceWith = ReplaceWith("detectPlatformKindByPlugin(moduleNode)"), level = DeprecationLevel.ERROR ) fun detectPlatformByPlugin(moduleNode: DataNode<ModuleData>): TargetPlatformKind<*>? { return when (moduleNode.platformPluginId) { "kotlin-platform-jvm" -> TargetPlatformKind.Jvm[JvmTarget.DEFAULT] "kotlin-platform-js" -> TargetPlatformKind.JavaScript "kotlin-platform-common" -> TargetPlatformKind.Common else -> null } } private fun detectPlatformByLibrary(moduleNode: DataNode<ModuleData>): IdePlatformKind<*>? { val detectedPlatforms = mavenLibraryIdToPlatform.entries .filter { moduleNode.getResolvedVersionByModuleData(KOTLIN_GROUP_ID, listOf(it.key)) != null } .map { it.value }.distinct() return detectedPlatforms.singleOrNull() ?: detectedPlatforms.firstOrNull { !it.isCommon } } @Suppress("unused") // Used in the Android plugin fun configureFacetByGradleModule( moduleNode: DataNode<ModuleData>, sourceSetName: String?, ideModule: Module, modelsProvider: IdeModifiableModelsProvider ): KotlinFacet? { return configureFacetByGradleModule(ideModule, modelsProvider, moduleNode, null, sourceSetName) } fun configureFacetByGradleModule( ideModule: Module, modelsProvider: IdeModifiableModelsProvider, moduleNode: DataNode<ModuleData>, sourceSetNode: DataNode<GradleSourceSetData>?, sourceSetName: String? = sourceSetNode?.data?.id?.let { it.substring(it.lastIndexOf(':') + 1) } ): KotlinFacet? { if (moduleNode.kotlinSourceSet != null) return null // Suppress in the presence of new MPP model if (!moduleNode.isResolved) return null if (!moduleNode.hasKotlinPlugin) { val facetModel = modelsProvider.getModifiableFacetModel(ideModule) val facet = facetModel.getFacetByType(KotlinFacetType.TYPE_ID) if (facet != null) { facetModel.removeFacet(facet) } return null } val compilerVersion = KotlinGradleFacadeImpl.findKotlinPluginVersion(moduleNode) ?: return null val platformKind = detectPlatformKindByPlugin(moduleNode) ?: detectPlatformByLibrary(moduleNode) // TODO there should be a way to figure out the correct platform version val platform = platformKind?.defaultPlatform val kotlinFacet = ideModule.getOrCreateFacet(modelsProvider, false, GradleConstants.SYSTEM_ID.id) kotlinFacet.configureFacet( compilerVersion, platform, modelsProvider ) if (sourceSetNode == null) { ideModule.compilerArgumentsBySourceSet = moduleNode.compilerArgumentsBySourceSet ideModule.sourceSetName = sourceSetName } ideModule.hasExternalSdkConfiguration = sourceSetNode?.data?.sdkName != null val argsInfo = moduleNode.compilerArgumentsBySourceSet?.get(sourceSetName ?: "main") if (argsInfo != null) { configureFacetByCompilerArguments(kotlinFacet, argsInfo, modelsProvider) } with(kotlinFacet.configuration.settings) { implementedModuleNames = (sourceSetNode ?: moduleNode).implementedModuleNames productionOutputPath = getExplicitOutputPath(moduleNode, platformKind, "main") testOutputPath = getExplicitOutputPath(moduleNode, platformKind, "test") } kotlinFacet.noVersionAutoAdvance() if (platformKind != null && !platformKind.isJvm) { migrateNonJvmSourceFolders(modelsProvider.getModifiableRootModel(ideModule)) } return kotlinFacet } fun configureFacetByCompilerArguments(kotlinFacet: KotlinFacet, argsInfo: ArgsInfo, modelsProvider: IdeModifiableModelsProvider?) { val currentCompilerArguments = argsInfo.currentArguments val defaultCompilerArguments = argsInfo.defaultArguments val dependencyClasspath = argsInfo.dependencyClasspath.map { PathUtil.toSystemIndependentName(it) } if (currentCompilerArguments.isNotEmpty()) { parseCompilerArgumentsToFacet(currentCompilerArguments, defaultCompilerArguments, kotlinFacet, modelsProvider) } adjustClasspath(kotlinFacet, dependencyClasspath) } private fun getExplicitOutputPath(moduleNode: DataNode<ModuleData>, platformKind: IdePlatformKind<*>?, sourceSet: String): String? { if (!platformKind.isJavaScript) { return null } val k2jsArgumentList = moduleNode.compilerArgumentsBySourceSet?.get(sourceSet)?.currentArguments ?: return null return K2JSCompilerArguments().apply { parseCommandLineArguments(k2jsArgumentList, this) }.outputFile } internal fun adjustClasspath(kotlinFacet: KotlinFacet, dependencyClasspath: List<String>) { if (dependencyClasspath.isEmpty()) return val arguments = kotlinFacet.configuration.settings.compilerArguments as? K2JVMCompilerArguments ?: return val fullClasspath = arguments.classpath?.split(File.pathSeparator) ?: emptyList() if (fullClasspath.isEmpty()) return val newClasspath = fullClasspath - dependencyClasspath arguments.classpath = if (newClasspath.isNotEmpty()) newClasspath.joinToString(File.pathSeparator) else null }
apache-2.0
9d6a4ba4cdc76c7b918d561c9460ca79
45.346749
158
0.752305
5.46151
false
true
false
false
jwren/intellij-community
xml/xml-psi-impl/src/com/intellij/documentation/mdn/MdnDocumentation.kt
7
26158
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.documentation.mdn import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.TreeNode import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.fasterxml.jackson.databind.node.ObjectNode import com.fasterxml.jackson.databind.node.TextNode import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import com.github.benmanes.caffeine.cache.Caffeine import com.github.benmanes.caffeine.cache.LoadingCache import com.intellij.lang.documentation.DocumentationMarkup import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.StringUtil.capitalize import com.intellij.openapi.util.text.StringUtil.toLowerCase import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.html.dtd.HtmlSymbolDeclaration import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.xml.* import com.intellij.util.castSafelyTo import com.intellij.xml.psi.XmlPsiBundle import com.intellij.xml.util.HtmlUtil import java.util.* import java.util.concurrent.TimeUnit import java.util.function.Consumer import kotlin.text.Regex.Companion.escapeReplacement fun getJsMdnDocumentation(namespace: MdnApiNamespace, qualifiedName: String): MdnSymbolDocumentation? { assert(namespace == MdnApiNamespace.WebApi || namespace == MdnApiNamespace.GlobalObjects) val mdnQualifiedName = qualifiedName.let { when { it.startsWith("HTMLDocument") -> it.removePrefix("HTML") it.contains('.') -> it.replace("Constructor", "") it.endsWith("Constructor") -> "$it.$it" else -> it } }.lowercase(Locale.US).let { webApiIndex[it] ?: it } val jsNamespace = qualifiedName.takeWhile { it != '.' } if (jsNamespace.endsWith("EventMap")) { getDomEventDocumentation(qualifiedName.substring(jsNamespace.length + 1))?.let { return it } } val documentation = documentationCache[ Pair(namespace, if (namespace == MdnApiNamespace.WebApi) getWebApiFragment(mdnQualifiedName) else null) ] as? MdnJsDocumentation ?: return null return documentation.symbols[mdnQualifiedName] ?.let { MdnSymbolDocumentationAdapter(mdnQualifiedName, documentation, it) } ?: qualifiedName.takeIf { it.startsWith("CSSStyleDeclaration.") } ?.let { getCssMdnDocumentation(it.substring("CSSStyleDeclaration.".length).toKebabCase(), MdnCssSymbolKind.Property) } } fun getDomEventDocumentation(name: String): MdnSymbolDocumentation? = innerGetEventDoc(name)?.let { MdnSymbolDocumentationAdapter(name, it.first, it.second) } fun getCssMdnDocumentation(name: String, kind: MdnCssSymbolKind): MdnSymbolDocumentation? { val documentation = documentationCache[Pair(MdnApiNamespace.Css, null)] as? MdnCssDocumentation ?: return null return kind.getSymbolDoc(documentation, name) ?: getUnprefixedName(name)?.let { kind.getSymbolDoc(documentation, it) } } fun getHtmlMdnDocumentation(element: PsiElement, context: XmlTag?): MdnSymbolDocumentation? { var symbolName: String? = null return when { // Directly from the file element is XmlTag && !element.containingFile.name.endsWith(".xsd", true) -> { symbolName = element.localName getTagDocumentation(getHtmlApiNamespace(element.namespace, element, toLowerCase(symbolName)), toLowerCase(symbolName)) } // TODO support special documentation for attribute values element is XmlAttribute || element is XmlAttributeValue -> { PsiTreeUtil.getParentOfType(element, XmlAttribute::class.java, false)?.let { attr -> symbolName = attr.localName getAttributeDocumentation(getHtmlApiNamespace(attr.namespace, attr, toLowerCase(symbolName)), attr.parent.localName, toLowerCase(symbolName)) } } else -> { var isTag = true when (element) { // XSD is XmlTag -> { element.metaData?.let { metaData -> isTag = element.localName == "element" symbolName = metaData.name } } // DTD is XmlElementDecl -> { symbolName = element.name } is XmlAttributeDecl -> { isTag = false symbolName = element.nameElement.text } is HtmlSymbolDeclaration -> { isTag = element.kind == HtmlSymbolDeclaration.Kind.ELEMENT symbolName = element.name } } symbolName?.let { val lcName = toLowerCase(it) val namespace = getHtmlApiNamespace(context?.namespace, context, lcName) if (isTag) { getTagDocumentation(namespace, lcName) } else { getAttributeDocumentation(namespace, context?.localName?.let(::toLowerCase), lcName) } } } } ?.takeIf { symbolName != null } ?.let { (source, doc) -> MdnSymbolDocumentationAdapter(if (context?.isCaseSensitive == true) symbolName!! else toLowerCase(symbolName!!), source, doc) } } fun getHtmlMdnTagDocumentation(namespace: MdnApiNamespace, tagName: String): MdnSymbolDocumentation? { assert(namespace == MdnApiNamespace.Html || namespace == MdnApiNamespace.MathML || namespace == MdnApiNamespace.Svg) return getTagDocumentation(namespace, tagName)?.let { (source, doc) -> MdnSymbolDocumentationAdapter(tagName, source, doc) } } fun getHtmlMdnAttributeDocumentation(namespace: MdnApiNamespace, tagName: String?, attributeName: String): MdnSymbolDocumentation? { assert(namespace == MdnApiNamespace.Html || namespace == MdnApiNamespace.MathML || namespace == MdnApiNamespace.Svg) return getAttributeDocumentation(namespace, tagName, attributeName)?.let { (source, doc) -> MdnSymbolDocumentationAdapter(attributeName, source, doc) } } private fun getTagDocumentation(namespace: MdnApiNamespace, tagName: String): Pair<MdnHtmlDocumentation, MdnHtmlElementDocumentation>? { val documentation = documentationCache[Pair(namespace, null)] as? MdnHtmlDocumentation ?: return null return documentation.tags[tagName.let { documentation.tagAliases[it] ?: it }]?.let { Pair(documentation, it) } } private fun getAttributeDocumentation(namespace: MdnApiNamespace, tagName: String?, attributeName: String): Pair<MdnDocumentation, MdnRawSymbolDocumentation>? { val documentation = documentationCache[Pair(namespace, null)] as? MdnHtmlDocumentation ?: return null return tagName ?.let { name -> getTagDocumentation(namespace, name) ?.let { (source, tagDoc) -> tagDoc.attrs?.get(attributeName) ?.let { mergeWithGlobal(it, documentation.attrs[attributeName]) } ?.let { Pair(source, it) } } } ?: documentation.attrs[attributeName]?.let { Pair(documentation, it) } ?: attributeName.takeIf { it.startsWith("on") } ?.let { innerGetEventDoc(it.substring(2)) } } private fun mergeWithGlobal(tag: MdnHtmlAttributeDocumentation, global: MdnHtmlAttributeDocumentation?): MdnHtmlAttributeDocumentation = global?.let { MdnHtmlAttributeDocumentation( tag.url, tag.status ?: global.status, tag.compatibility ?: global.compatibility, tag.doc ?: global.doc ) } ?: tag private fun innerGetEventDoc(eventName: String): Pair<MdnDocumentation, MdnDomEventDocumentation>? = (documentationCache[Pair(MdnApiNamespace.DomEvents, null)] as MdnDomEventsDocumentation) .let { Pair(it, it.events[eventName] ?: return@let null) } interface MdnSymbolDocumentation { val name: String val url: String val isDeprecated: Boolean val isExperimental: Boolean val description: String val sections: Map<String, String> val footnote: String? fun getDocumentation(withDefinition: Boolean): @NlsSafe String fun getDocumentation(withDefinition: Boolean, additionalSectionsContent: Consumer<java.lang.StringBuilder>?): @NlsSafe String } private const val defaultBcdContext = "default_context" class MdnSymbolDocumentationAdapter(override val name: String, private val source: MdnDocumentation, private val doc: MdnRawSymbolDocumentation) : MdnSymbolDocumentation { override val url: String get() = fixMdnUrls(doc.url, source.lang) override val isDeprecated: Boolean get() = doc.status?.contains(MdnApiStatus.Deprecated) == true override val isExperimental: Boolean get() = doc.status?.contains(MdnApiStatus.Experimental) == true override val description: String get() = capitalize(doc.doc ?: "").fixUrls() override val sections: Map<String, String> get() { val result = doc.sections.toMutableMap() if (doc.compatibility != null) { doc.compatibility!!.entries.forEach { (id, map) -> val actualId = if (id == defaultBcdContext) "browser_compatibility" else id val bundleKey = "mdn.documentation.section.compat.$actualId" val sectionName: String = if (actualId.startsWith("support_of_") && !XmlPsiBundle.hasKey(bundleKey)) { XmlPsiBundle.message("mdn.documentation.section.compat.support_of", actualId.substring("support_of_".length)) } else { XmlPsiBundle.message(bundleKey) } result[sectionName] = map.entries .joinToString(", ") { it.key.displayName + (if (it.value.isNotEmpty()) " " + it.value else "") } .ifBlank { XmlPsiBundle.message("mdn.documentation.section.compat.supported_by.none") } } } doc.status?.asSequence() ?.filter { it != MdnApiStatus.StandardTrack } ?.map { Pair(XmlPsiBundle.message("mdn.documentation.section.status." + it.name), "") } ?.toMap(result) return result.map { (key, value) -> Pair(key.fixUrls(), value.fixUrls()) }.toMap() } override val footnote: String get() = "By <a href='${doc.url}/contributors.txt'>Mozilla Contributors</a>, <a href='https://creativecommons.org/licenses/by-sa/2.5/'>CC BY-SA 2.5</a>" .fixUrls() override fun getDocumentation(withDefinition: Boolean): String = getDocumentation(withDefinition, null) override fun getDocumentation(withDefinition: Boolean, additionalSectionsContent: Consumer<java.lang.StringBuilder>?) = buildDoc(this, withDefinition, additionalSectionsContent) private fun String.fixUrls(): String = fixMdnUrls(replace(Regex("<a[ \n\t]+href=[ \t]*['\"]#([^'\"]*)['\"]"), "<a href=\"${escapeReplacement(doc.url)}#$1\""), source.lang) } typealias CompatibilityMap = Map<String, Map<MdnJavaScriptRuntime, String>> interface MdnRawSymbolDocumentation { val url: String val status: Set<MdnApiStatus>? val compatibility: CompatibilityMap? val doc: String? val sections: Map<String, String> get() = emptyMap() } interface MdnDocumentation { val lang: String } data class MdnHtmlDocumentation(override val lang: String, val attrs: Map<String, MdnHtmlAttributeDocumentation>, val tags: Map<String, MdnHtmlElementDocumentation>, val tagAliases: Map<String, String> = emptyMap()) : MdnDocumentation data class MdnJsDocumentation(override val lang: String, val symbols: Map<String, MdnJsSymbolDocumentation>) : MdnDocumentation data class MdnDomEventsDocumentation(override val lang: String, val events: Map<String, MdnDomEventDocumentation>) : MdnDocumentation data class MdnCssDocumentation(override val lang: String, val atRules: Map<String, MdnCssAtRuleSymbolDocumentation>, val properties: Map<String, MdnCssPropertySymbolDocumentation>, val pseudoClasses: Map<String, MdnCssBasicSymbolDocumentation>, val pseudoElements: Map<String, MdnCssBasicSymbolDocumentation>, val functions: Map<String, MdnCssBasicSymbolDocumentation>, val dataTypes: Map<String, MdnCssBasicSymbolDocumentation>) : MdnDocumentation data class MdnHtmlElementDocumentation(override val url: String, override val status: Set<MdnApiStatus>?, @JsonDeserialize(using = CompatibilityMapDeserializer::class) override val compatibility: CompatibilityMap?, override val doc: String, val details: Map<String, String>?, val attrs: Map<String, MdnHtmlAttributeDocumentation>?) : MdnRawSymbolDocumentation data class MdnHtmlAttributeDocumentation(override val url: String, override val status: Set<MdnApiStatus>?, @JsonDeserialize(using = CompatibilityMapDeserializer::class) override val compatibility: CompatibilityMap?, override val doc: String?) : MdnRawSymbolDocumentation data class MdnDomEventDocumentation(override val url: String, override val status: Set<MdnApiStatus>?, @JsonDeserialize(using = CompatibilityMapDeserializer::class) override val compatibility: CompatibilityMap?, override val doc: String?) : MdnRawSymbolDocumentation data class MdnJsSymbolDocumentation(override val url: String, override val status: Set<MdnApiStatus>?, @JsonDeserialize(using = CompatibilityMapDeserializer::class) override val compatibility: CompatibilityMap?, override val doc: String?, val parameters: Map<String, String>?, val returns: String?, val throws: Map<String, String>?) : MdnRawSymbolDocumentation { override val sections: Map<String, String> get() { val result = mutableMapOf<String, String>() parameters?.takeIf { it.isNotEmpty() }?.let { result.put(XmlPsiBundle.message("mdn.documentation.section.parameters"), buildSubSection(it)) } returns?.let { result.put(XmlPsiBundle.message("mdn.documentation.section.returns"), it) } throws?.takeIf { it.isNotEmpty() }?.let { result.put(XmlPsiBundle.message("mdn.documentation.section.throws"), buildSubSection(it)) } return result } } data class MdnCssBasicSymbolDocumentation(override val url: String, override val status: Set<MdnApiStatus>?, @JsonDeserialize(using = CompatibilityMapDeserializer::class) override val compatibility: CompatibilityMap?, override val doc: String?) : MdnRawSymbolDocumentation data class MdnCssAtRuleSymbolDocumentation(override val url: String, override val status: Set<MdnApiStatus>?, @JsonDeserialize(using = CompatibilityMapDeserializer::class) override val compatibility: CompatibilityMap?, override val doc: String?, val properties: Map<String, MdnCssPropertySymbolDocumentation>?) : MdnRawSymbolDocumentation data class MdnCssPropertySymbolDocumentation(override val url: String, override val status: Set<MdnApiStatus>?, @JsonDeserialize(using = CompatibilityMapDeserializer::class) override val compatibility: CompatibilityMap?, override val doc: String?, val formalSyntax: String?, val values: Map<String, String>?) : MdnRawSymbolDocumentation { override val sections: Map<String, String> get() { val result = mutableMapOf<String, String>() formalSyntax?.takeIf { it.isNotEmpty() }?.let { result.put(XmlPsiBundle.message("mdn.documentation.section.syntax"), "<pre><code>$it</code></pre>") } values?.takeIf { it.isNotEmpty() }?.let { result.put(XmlPsiBundle.message("mdn.documentation.section.values"), buildSubSection(values)) } return result } } enum class MdnApiNamespace { Html, Svg, MathML, WebApi, GlobalObjects, DomEvents, Css } enum class MdnApiStatus { Experimental, StandardTrack, Deprecated } enum class MdnJavaScriptRuntime(displayName: String? = null, mdnId: String? = null, val firstVersion: String = "1") { Chrome, ChromeAndroid(displayName = "Chrome Android", mdnId = "chrome_android", firstVersion = "18"), Edge(firstVersion = "12"), Firefox, IE, Opera, Safari, SafariIOS(displayName = "Safari iOS", mdnId = "safari_ios"), Nodejs(displayName = "Node.js", firstVersion = "0.10.0"); val mdnId: String = mdnId ?: toLowerCase(name) val displayName: String = displayName ?: name } enum class MdnCssSymbolKind { AtRule { override fun decorateName(name: String): String = "@$name" override fun getDocumentationMap(documentation: MdnCssDocumentation): Map<String, MdnRawSymbolDocumentation> = documentation.atRules }, Property { override fun decorateName(name: String): String = name override fun getDocumentationMap(documentation: MdnCssDocumentation): Map<String, MdnRawSymbolDocumentation> = documentation.properties override fun getSymbolDoc(documentation: MdnCssDocumentation, name: String): MdnSymbolDocumentation? { if (name.startsWith("@")) { val atRule = name.takeWhile { it != '.' }.substring(1).lowercase(Locale.US) val propertyName = name.takeLastWhile { it != '.' }.lowercase(Locale.US) documentation.atRules[atRule]?.properties?.get(propertyName)?.let { return MdnSymbolDocumentationAdapter(name, documentation, it) } return super.getSymbolDoc(documentation, propertyName) } return super.getSymbolDoc(documentation, name) } }, PseudoClass { override fun decorateName(name: String): String = ":$name" override fun getDocumentationMap(documentation: MdnCssDocumentation): Map<String, MdnRawSymbolDocumentation> = documentation.pseudoClasses override fun getSymbolDoc(documentation: MdnCssDocumentation, name: String): MdnSymbolDocumentation? = // In case of pseudo class query we should fallback to pseudo element super.getSymbolDoc(documentation, name) ?: PseudoElement.getSymbolDoc(documentation, name) }, PseudoElement { override fun decorateName(name: String): String = "::$name" override fun getDocumentationMap(documentation: MdnCssDocumentation): Map<String, MdnRawSymbolDocumentation> = documentation.pseudoElements }, Function { override fun decorateName(name: String): String = "$name()" override fun getDocumentationMap(documentation: MdnCssDocumentation): Map<String, MdnRawSymbolDocumentation> = documentation.functions }, DataType { override fun decorateName(name: String): String = name override fun getDocumentationMap(documentation: MdnCssDocumentation): Map<String, MdnRawSymbolDocumentation> = documentation.dataTypes }, ; protected abstract fun getDocumentationMap(documentation: MdnCssDocumentation): Map<String, MdnRawSymbolDocumentation> protected abstract fun decorateName(name: String): String open fun getSymbolDoc(documentation: MdnCssDocumentation, name: String): MdnSymbolDocumentation? = getDocumentationMap(documentation)[name.lowercase(Locale.US)]?.let { MdnSymbolDocumentationAdapter(decorateName(name), documentation, it) } } val webApiFragmentStarts = arrayOf('a', 'e', 'l', 'r', 'u') private class CompatibilityMapDeserializer : JsonDeserializer<CompatibilityMap>() { override fun deserialize(p: JsonParser, ctxt: DeserializationContext): CompatibilityMap = p.readValueAsTree<TreeNode>() .castSafelyTo<ObjectNode>() ?.let { if (it.firstOrNull() is ObjectNode) { it.fields().asSequence() .map { (key, value) -> Pair(key, (value as ObjectNode).toBcdMap()) } .toMap() } else { mapOf(Pair(defaultBcdContext, it.toBcdMap())) } } ?: emptyMap() private fun ObjectNode.toBcdMap(): Map<MdnJavaScriptRuntime, String> = this.fields().asSequence().map { (key, value) -> Pair(MdnJavaScriptRuntime.valueOf(key), (value as TextNode).asText()) }.toMap() } private fun getWebApiFragment(name: String): Char = webApiFragmentStarts.findLast { it <= name[0].lowercaseChar() }!! private const val MDN_DOCS_URL_PREFIX = "\$MDN_URL\$" private val documentationCache: LoadingCache<Pair<MdnApiNamespace, Char?>, MdnDocumentation> = Caffeine.newBuilder() .expireAfterAccess(10, TimeUnit.MINUTES) .build { (namespace, segment) -> loadDocumentation(namespace, segment) } private val webApiIndex: Map<String, String> by lazy { MdnHtmlDocumentation::class.java.getResource("WebApi-index.json")!! .let { jacksonObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(it) } } private fun fixMdnUrls(content: String, lang: String): String = content.replace("$MDN_DOCS_URL_PREFIX/", "https://developer.mozilla.org/$lang/docs/") .replace(MDN_DOCS_URL_PREFIX, "https://developer.mozilla.org/$lang/docs") fun getHtmlApiNamespace(namespace: String?, element: PsiElement?, symbolName: String): MdnApiNamespace = when { symbolName.equals("svg", true) -> MdnApiNamespace.Svg symbolName.equals("math", true) -> MdnApiNamespace.MathML namespace == HtmlUtil.SVG_NAMESPACE -> MdnApiNamespace.Svg namespace == HtmlUtil.MATH_ML_NAMESPACE -> MdnApiNamespace.MathML else -> PsiTreeUtil.findFirstParent(element, false) { parent -> parent is XmlTag && parent.localName.lowercase(Locale.US).let { it == "svg" || it == "math" } }?.castSafelyTo<XmlTag>()?.let { when (it.name.lowercase(Locale.US)) { "svg" -> MdnApiNamespace.Svg "math" -> MdnApiNamespace.MathML else -> null } } ?: MdnApiNamespace.Html } private fun loadDocumentation(namespace: MdnApiNamespace, segment: Char?): MdnDocumentation = loadDocumentation(namespace, segment, when (namespace) { MdnApiNamespace.Css -> MdnCssDocumentation::class.java MdnApiNamespace.WebApi, MdnApiNamespace.GlobalObjects -> MdnJsDocumentation::class.java MdnApiNamespace.DomEvents -> MdnDomEventsDocumentation::class.java else -> MdnHtmlDocumentation::class.java }) private fun <T : MdnDocumentation> loadDocumentation(namespace: MdnApiNamespace, segment: Char?, clazz: Class<T>): T = MdnHtmlDocumentation::class.java.getResource("${namespace.name}${segment?.let { "-$it" } ?: ""}.json")!! .let { jacksonObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(it, clazz) } private fun buildDoc(doc: MdnSymbolDocumentation, withDefinition: Boolean, additionalSectionsContent: Consumer<java.lang.StringBuilder>?): @NlsSafe String { val buf = StringBuilder() if (withDefinition) buf.append(DocumentationMarkup.DEFINITION_START) .append(doc.name) .append(DocumentationMarkup.DEFINITION_END) .append("\n") buf.append(DocumentationMarkup.CONTENT_START) .append(doc.description) .append(DocumentationMarkup.CONTENT_END) val sections = doc.sections if (sections.isNotEmpty() || additionalSectionsContent != null) { buf.append("\n") .append(DocumentationMarkup.SECTIONS_START) for (entry in sections) { buf.append("\n") .append(DocumentationMarkup.SECTION_HEADER_START) .append(entry.key) if (entry.value.isNotEmpty()) { if (!entry.key.endsWith(":")) buf.append(':') buf.append(DocumentationMarkup.SECTION_SEPARATOR) .append(entry.value) } buf.append(DocumentationMarkup.SECTION_END) } additionalSectionsContent?.accept(buf) buf.append(DocumentationMarkup.SECTIONS_END) } buf.append("\n") .append(DocumentationMarkup.CONTENT_START) .append(doc.footnote) .append(DocumentationMarkup.CONTENT_END) .append("\n") // Expand MDN URL prefix and fix relative "#" references to point to external MDN docs return buf.toString() } fun buildSubSection(items: Map<String, String>): String { val result = StringBuilder() items.forEach { (name, doc) -> result.append("<p><code>") .append(name) .append("</code> &ndash; ") .append(doc) .append("<br><span style='font-size:0.2em'>&nbsp;</span>\n") } return result.toString() } private fun getUnprefixedName(name: String): String? { if (name.length < 4 || name[0] != '-' || name[1] == '-') return null val index = name.indexOf('-', 2) return if (index < 0 || index == name.length - 1) null else name.substring(index + 1) } private val UPPER_CASE = Regex("(?=\\p{Upper})") private fun String.toKebabCase() = this.split(UPPER_CASE).joinToString("-") { it.lowercase(Locale.US) }
apache-2.0
7b2e44b39fbe51ec5592f38039ddb347
44.256055
158
0.66538
4.994844
false
false
false
false
androidx/androidx
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/input/key/Key.desktop.kt
3
31749
/* * 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.input.key import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.input.key.Key.Companion.Number import java.awt.event.KeyEvent import java.awt.event.KeyEvent.KEY_LOCATION_LEFT import java.awt.event.KeyEvent.KEY_LOCATION_NUMPAD import java.awt.event.KeyEvent.KEY_LOCATION_RIGHT import java.awt.event.KeyEvent.KEY_LOCATION_STANDARD import androidx.compose.ui.util.unpackInt1 // TODO(demin): implement most of key codes /** * Actual implementation of [Key] for Desktop. * * @param keyCode an integer code representing the key pressed. Note: This keycode can be used to * uniquely identify a hardware key. It is different from the native keycode. */ @JvmInline actual value class Key(val keyCode: Long) { actual companion object { /** Unknown key. */ @ExperimentalComposeUiApi actual val Unknown = Key(KeyEvent.VK_UNDEFINED) /** * Home key. * * This key is handled by the framework and is never delivered to applications. */ @ExperimentalComposeUiApi actual val Home = Key(KeyEvent.VK_HOME) /** Help key. */ @ExperimentalComposeUiApi actual val Help = Key(KeyEvent.VK_HELP) /** * Up Arrow Key / Directional Pad Up key. * * May also be synthesized from trackball motions. */ @ExperimentalComposeUiApi actual val DirectionUp = Key(KeyEvent.VK_UP) /** * Down Arrow Key / Directional Pad Down key. * * May also be synthesized from trackball motions. */ @ExperimentalComposeUiApi actual val DirectionDown = Key(KeyEvent.VK_DOWN) /** * Left Arrow Key / Directional Pad Left key. * * May also be synthesized from trackball motions. */ @ExperimentalComposeUiApi actual val DirectionLeft = Key(KeyEvent.VK_LEFT) /** * Right Arrow Key / Directional Pad Right key. * * May also be synthesized from trackball motions. */ @ExperimentalComposeUiApi actual val DirectionRight = Key(KeyEvent.VK_RIGHT) /** '0' key. */ @ExperimentalComposeUiApi actual val Zero = Key(KeyEvent.VK_0) /** '1' key. */ @ExperimentalComposeUiApi actual val One = Key(KeyEvent.VK_1) /** '2' key. */ @ExperimentalComposeUiApi actual val Two = Key(KeyEvent.VK_2) /** '3' key. */ @ExperimentalComposeUiApi actual val Three = Key(KeyEvent.VK_3) /** '4' key. */ @ExperimentalComposeUiApi actual val Four = Key(KeyEvent.VK_4) /** '5' key. */ @ExperimentalComposeUiApi actual val Five = Key(KeyEvent.VK_5) /** '6' key. */ @ExperimentalComposeUiApi actual val Six = Key(KeyEvent.VK_6) /** '7' key. */ @ExperimentalComposeUiApi actual val Seven = Key(KeyEvent.VK_7) /** '8' key. */ @ExperimentalComposeUiApi actual val Eight = Key(KeyEvent.VK_8) /** '9' key. */ @ExperimentalComposeUiApi actual val Nine = Key(KeyEvent.VK_9) /** '+' key. */ @ExperimentalComposeUiApi actual val Plus = Key(KeyEvent.VK_PLUS) /** '-' key. */ @ExperimentalComposeUiApi actual val Minus = Key(KeyEvent.VK_MINUS) /** '*' key. */ @ExperimentalComposeUiApi actual val Multiply = Key(KeyEvent.VK_MULTIPLY) /** '=' key. */ @ExperimentalComposeUiApi actual val Equals = Key(KeyEvent.VK_EQUALS) /** '#' key. */ @ExperimentalComposeUiApi actual val Pound = Key(KeyEvent.VK_NUMBER_SIGN) /** 'A' key. */ @ExperimentalComposeUiApi actual val A = Key(KeyEvent.VK_A) /** 'B' key. */ @ExperimentalComposeUiApi actual val B = Key(KeyEvent.VK_B) /** 'C' key. */ @ExperimentalComposeUiApi actual val C = Key(KeyEvent.VK_C) /** 'D' key. */ @ExperimentalComposeUiApi actual val D = Key(KeyEvent.VK_D) /** 'E' key. */ @ExperimentalComposeUiApi actual val E = Key(KeyEvent.VK_E) /** 'F' key. */ @ExperimentalComposeUiApi actual val F = Key(KeyEvent.VK_F) /** 'G' key. */ @ExperimentalComposeUiApi actual val G = Key(KeyEvent.VK_G) /** 'H' key. */ @ExperimentalComposeUiApi actual val H = Key(KeyEvent.VK_H) /** 'I' key. */ @ExperimentalComposeUiApi actual val I = Key(KeyEvent.VK_I) /** 'J' key. */ @ExperimentalComposeUiApi actual val J = Key(KeyEvent.VK_J) /** 'K' key. */ @ExperimentalComposeUiApi actual val K = Key(KeyEvent.VK_K) /** 'L' key. */ @ExperimentalComposeUiApi actual val L = Key(KeyEvent.VK_L) /** 'M' key. */ @ExperimentalComposeUiApi actual val M = Key(KeyEvent.VK_M) /** 'N' key. */ @ExperimentalComposeUiApi actual val N = Key(KeyEvent.VK_N) /** 'O' key. */ @ExperimentalComposeUiApi actual val O = Key(KeyEvent.VK_O) /** 'P' key. */ @ExperimentalComposeUiApi actual val P = Key(KeyEvent.VK_P) /** 'Q' key. */ @ExperimentalComposeUiApi actual val Q = Key(KeyEvent.VK_Q) /** 'R' key. */ @ExperimentalComposeUiApi actual val R = Key(KeyEvent.VK_R) /** 'S' key. */ @ExperimentalComposeUiApi actual val S = Key(KeyEvent.VK_S) /** 'T' key. */ @ExperimentalComposeUiApi actual val T = Key(KeyEvent.VK_T) /** 'U' key. */ @ExperimentalComposeUiApi actual val U = Key(KeyEvent.VK_U) /** 'V' key. */ @ExperimentalComposeUiApi actual val V = Key(KeyEvent.VK_V) /** 'W' key. */ @ExperimentalComposeUiApi actual val W = Key(KeyEvent.VK_W) /** 'X' key. */ @ExperimentalComposeUiApi actual val X = Key(KeyEvent.VK_X) /** 'Y' key. */ @ExperimentalComposeUiApi actual val Y = Key(KeyEvent.VK_Y) /** 'Z' key. */ @ExperimentalComposeUiApi actual val Z = Key(KeyEvent.VK_Z) /** ',' key. */ @ExperimentalComposeUiApi actual val Comma = Key(KeyEvent.VK_COMMA) /** '.' key. */ @ExperimentalComposeUiApi actual val Period = Key(KeyEvent.VK_PERIOD) /** Left Alt modifier key. */ @ExperimentalComposeUiApi actual val AltLeft = Key(KeyEvent.VK_ALT, KEY_LOCATION_LEFT) /** Right Alt modifier key. */ @ExperimentalComposeUiApi actual val AltRight = Key(KeyEvent.VK_ALT, KEY_LOCATION_RIGHT) /** Left Shift modifier key. */ @ExperimentalComposeUiApi actual val ShiftLeft = Key(KeyEvent.VK_SHIFT, KEY_LOCATION_LEFT) /** Right Shift modifier key. */ @ExperimentalComposeUiApi actual val ShiftRight = Key(KeyEvent.VK_SHIFT, KEY_LOCATION_RIGHT) /** Tab key. */ @ExperimentalComposeUiApi actual val Tab = Key(KeyEvent.VK_TAB) /** Space key. */ @ExperimentalComposeUiApi actual val Spacebar = Key(KeyEvent.VK_SPACE) /** Enter key. */ @ExperimentalComposeUiApi actual val Enter = Key(KeyEvent.VK_ENTER) /** * Backspace key. * * Deletes characters before the insertion point, unlike [Delete]. */ @ExperimentalComposeUiApi actual val Backspace = Key(KeyEvent.VK_BACK_SPACE) /** * Delete key. * * Deletes characters ahead of the insertion point, unlike [Backspace]. */ @ExperimentalComposeUiApi actual val Delete = Key(KeyEvent.VK_DELETE) /** Escape key. */ @ExperimentalComposeUiApi actual val Escape = Key(KeyEvent.VK_ESCAPE) /** Left Control modifier key. */ @ExperimentalComposeUiApi actual val CtrlLeft = Key(KeyEvent.VK_CONTROL, KEY_LOCATION_LEFT) /** Right Control modifier key. */ @ExperimentalComposeUiApi actual val CtrlRight = Key(KeyEvent.VK_CONTROL, KEY_LOCATION_RIGHT) /** Caps Lock key. */ @ExperimentalComposeUiApi actual val CapsLock = Key(KeyEvent.VK_CAPS_LOCK) /** Scroll Lock key. */ @ExperimentalComposeUiApi actual val ScrollLock = Key(KeyEvent.VK_SCROLL_LOCK) /** Left Meta modifier key. */ @ExperimentalComposeUiApi actual val MetaLeft = Key(KeyEvent.VK_META, KEY_LOCATION_LEFT) /** Right Meta modifier key. */ @ExperimentalComposeUiApi actual val MetaRight = Key(KeyEvent.VK_META, KEY_LOCATION_RIGHT) /** System Request / Print Screen key. */ @ExperimentalComposeUiApi actual val PrintScreen = Key(KeyEvent.VK_PRINTSCREEN) /** * Insert key. * * Toggles insert / overwrite edit mode. */ @ExperimentalComposeUiApi actual val Insert = Key(KeyEvent.VK_INSERT) /** Cut key. */ @ExperimentalComposeUiApi actual val Cut = Key(KeyEvent.VK_CUT) /** Copy key. */ @ExperimentalComposeUiApi actual val Copy = Key(KeyEvent.VK_COPY) /** Paste key. */ @ExperimentalComposeUiApi actual val Paste = Key(KeyEvent.VK_PASTE) /** '`' (backtick) key. */ @ExperimentalComposeUiApi actual val Grave = Key(KeyEvent.VK_BACK_QUOTE) /** '[' key. */ @ExperimentalComposeUiApi actual val LeftBracket = Key(KeyEvent.VK_OPEN_BRACKET) /** ']' key. */ @ExperimentalComposeUiApi actual val RightBracket = Key(KeyEvent.VK_CLOSE_BRACKET) /** '/' key. */ @ExperimentalComposeUiApi actual val Slash = Key(KeyEvent.VK_SLASH) /** '\' key. */ @ExperimentalComposeUiApi actual val Backslash = Key(KeyEvent.VK_BACK_SLASH) /** ';' key. */ @ExperimentalComposeUiApi actual val Semicolon = Key(KeyEvent.VK_SEMICOLON) /** ''' (apostrophe) key. */ @ExperimentalComposeUiApi actual val Apostrophe = Key(KeyEvent.VK_QUOTE) /** '@' key. */ @ExperimentalComposeUiApi actual val At = Key(KeyEvent.VK_AT) /** Page Up key. */ @ExperimentalComposeUiApi actual val PageUp = Key(KeyEvent.VK_PAGE_UP) /** Page Down key. */ @ExperimentalComposeUiApi actual val PageDown = Key(KeyEvent.VK_PAGE_DOWN) /** F1 key. */ @ExperimentalComposeUiApi actual val F1 = Key(KeyEvent.VK_F1) /** F2 key. */ @ExperimentalComposeUiApi actual val F2 = Key(KeyEvent.VK_F2) /** F3 key. */ @ExperimentalComposeUiApi actual val F3 = Key(KeyEvent.VK_F3) /** F4 key. */ @ExperimentalComposeUiApi actual val F4 = Key(KeyEvent.VK_F4) /** F5 key. */ @ExperimentalComposeUiApi actual val F5 = Key(KeyEvent.VK_F5) /** F6 key. */ @ExperimentalComposeUiApi actual val F6 = Key(KeyEvent.VK_F6) /** F7 key. */ @ExperimentalComposeUiApi actual val F7 = Key(KeyEvent.VK_F7) /** F8 key. */ @ExperimentalComposeUiApi actual val F8 = Key(KeyEvent.VK_F8) /** F9 key. */ @ExperimentalComposeUiApi actual val F9 = Key(KeyEvent.VK_F9) /** F10 key. */ @ExperimentalComposeUiApi actual val F10 = Key(KeyEvent.VK_F10) /** F11 key. */ @ExperimentalComposeUiApi actual val F11 = Key(KeyEvent.VK_F11) /** F12 key. */ @ExperimentalComposeUiApi actual val F12 = Key(KeyEvent.VK_F12) /** * Num Lock key. * * This is the Num Lock key; it is different from [Number]. * This key alters the behavior of other keys on the numeric keypad. */ @ExperimentalComposeUiApi actual val NumLock = Key(KeyEvent.VK_NUM_LOCK, KEY_LOCATION_NUMPAD) /** Numeric keypad '0' key. */ @ExperimentalComposeUiApi actual val NumPad0 = Key(KeyEvent.VK_NUMPAD0, KEY_LOCATION_NUMPAD) /** Numeric keypad '1' key. */ @ExperimentalComposeUiApi actual val NumPad1 = Key(KeyEvent.VK_NUMPAD1, KEY_LOCATION_NUMPAD) /** Numeric keypad '2' key. */ @ExperimentalComposeUiApi actual val NumPad2 = Key(KeyEvent.VK_NUMPAD2, KEY_LOCATION_NUMPAD) /** Numeric keypad '3' key. */ @ExperimentalComposeUiApi actual val NumPad3 = Key(KeyEvent.VK_NUMPAD3, KEY_LOCATION_NUMPAD) /** Numeric keypad '4' key. */ @ExperimentalComposeUiApi actual val NumPad4 = Key(KeyEvent.VK_NUMPAD4, KEY_LOCATION_NUMPAD) /** Numeric keypad '5' key. */ @ExperimentalComposeUiApi actual val NumPad5 = Key(KeyEvent.VK_NUMPAD5, KEY_LOCATION_NUMPAD) /** Numeric keypad '6' key. */ @ExperimentalComposeUiApi actual val NumPad6 = Key(KeyEvent.VK_NUMPAD6, KEY_LOCATION_NUMPAD) /** Numeric keypad '7' key. */ @ExperimentalComposeUiApi actual val NumPad7 = Key(KeyEvent.VK_NUMPAD7, KEY_LOCATION_NUMPAD) /** Numeric keypad '8' key. */ @ExperimentalComposeUiApi actual val NumPad8 = Key(KeyEvent.VK_NUMPAD8, KEY_LOCATION_NUMPAD) /** Numeric keypad '9' key. */ @ExperimentalComposeUiApi actual val NumPad9 = Key(KeyEvent.VK_NUMPAD9, KEY_LOCATION_NUMPAD) /** Numeric keypad '/' key (for division). */ @ExperimentalComposeUiApi actual val NumPadDivide = Key(KeyEvent.VK_DIVIDE, KEY_LOCATION_NUMPAD) /** Numeric keypad '*' key (for multiplication). */ @ExperimentalComposeUiApi actual val NumPadMultiply = Key(KeyEvent.VK_MULTIPLY, KEY_LOCATION_NUMPAD) /** Numeric keypad '-' key (for subtraction). */ @ExperimentalComposeUiApi actual val NumPadSubtract = Key(KeyEvent.VK_SUBTRACT, KEY_LOCATION_NUMPAD) /** Numeric keypad '+' key (for addition). */ @ExperimentalComposeUiApi actual val NumPadAdd = Key(KeyEvent.VK_ADD, KEY_LOCATION_NUMPAD) /** Numeric keypad '.' key (for decimals or digit grouping). */ @ExperimentalComposeUiApi actual val NumPadDot = Key(KeyEvent.VK_PERIOD, KEY_LOCATION_NUMPAD) /** Numeric keypad ',' key (for decimals or digit grouping). */ @ExperimentalComposeUiApi actual val NumPadComma = Key(KeyEvent.VK_COMMA, KEY_LOCATION_NUMPAD) /** Numeric keypad Enter key. */ @ExperimentalComposeUiApi actual val NumPadEnter = Key(KeyEvent.VK_ENTER, KEY_LOCATION_NUMPAD) /** Numeric keypad '=' key. */ @ExperimentalComposeUiApi actual val NumPadEquals = Key(KeyEvent.VK_EQUALS, KEY_LOCATION_NUMPAD) /** Numeric keypad '(' key. */ @ExperimentalComposeUiApi actual val NumPadLeftParenthesis = Key(KeyEvent.VK_LEFT_PARENTHESIS, KEY_LOCATION_NUMPAD) /** Numeric keypad ')' key. */ @ExperimentalComposeUiApi actual val NumPadRightParenthesis = Key(KeyEvent.VK_RIGHT_PARENTHESIS, KEY_LOCATION_NUMPAD) @ExperimentalComposeUiApi actual val MoveHome = Key(KeyEvent.VK_HOME) @ExperimentalComposeUiApi actual val MoveEnd = Key(KeyEvent.VK_END) // Unsupported Keys. These keys will never be sent by the desktop. However we need unique // keycodes so that these constants can be used in a when statement without a warning. @ExperimentalComposeUiApi actual val SoftLeft = Key(-1000000001) @ExperimentalComposeUiApi actual val SoftRight = Key(-1000000002) @ExperimentalComposeUiApi actual val Back = Key(-1000000003) @ExperimentalComposeUiApi actual val NavigatePrevious = Key(-1000000004) @ExperimentalComposeUiApi actual val NavigateNext = Key(-1000000005) @ExperimentalComposeUiApi actual val NavigateIn = Key(-1000000006) @ExperimentalComposeUiApi actual val NavigateOut = Key(-1000000007) @ExperimentalComposeUiApi actual val SystemNavigationUp = Key(-1000000008) @ExperimentalComposeUiApi actual val SystemNavigationDown = Key(-1000000009) @ExperimentalComposeUiApi actual val SystemNavigationLeft = Key(-1000000010) @ExperimentalComposeUiApi actual val SystemNavigationRight = Key(-1000000011) @ExperimentalComposeUiApi actual val Call = Key(-1000000012) @ExperimentalComposeUiApi actual val EndCall = Key(-1000000013) @ExperimentalComposeUiApi actual val DirectionCenter = Key(-1000000014) @ExperimentalComposeUiApi actual val DirectionUpLeft = Key(-1000000015) @ExperimentalComposeUiApi actual val DirectionDownLeft = Key(-1000000016) @ExperimentalComposeUiApi actual val DirectionUpRight = Key(-1000000017) @ExperimentalComposeUiApi actual val DirectionDownRight = Key(-1000000018) @ExperimentalComposeUiApi actual val VolumeUp = Key(-1000000019) @ExperimentalComposeUiApi actual val VolumeDown = Key(-1000000020) @ExperimentalComposeUiApi actual val Power = Key(-1000000021) @ExperimentalComposeUiApi actual val Camera = Key(-1000000022) @ExperimentalComposeUiApi actual val Clear = Key(-1000000023) @ExperimentalComposeUiApi actual val Symbol = Key(-1000000024) @ExperimentalComposeUiApi actual val Browser = Key(-1000000025) @ExperimentalComposeUiApi actual val Envelope = Key(-1000000026) @ExperimentalComposeUiApi actual val Function = Key(-1000000027) @ExperimentalComposeUiApi actual val Break = Key(-1000000028) @ExperimentalComposeUiApi actual val Number = Key(-1000000031) @ExperimentalComposeUiApi actual val HeadsetHook = Key(-1000000032) @ExperimentalComposeUiApi actual val Focus = Key(-1000000033) @ExperimentalComposeUiApi actual val Menu = Key(-1000000034) @ExperimentalComposeUiApi actual val Notification = Key(-1000000035) @ExperimentalComposeUiApi actual val Search = Key(-1000000036) @ExperimentalComposeUiApi actual val PictureSymbols = Key(-1000000037) @ExperimentalComposeUiApi actual val SwitchCharset = Key(-1000000038) @ExperimentalComposeUiApi actual val ButtonA = Key(-1000000039) @ExperimentalComposeUiApi actual val ButtonB = Key(-1000000040) @ExperimentalComposeUiApi actual val ButtonC = Key(-1000000041) @ExperimentalComposeUiApi actual val ButtonX = Key(-1000000042) @ExperimentalComposeUiApi actual val ButtonY = Key(-1000000043) @ExperimentalComposeUiApi actual val ButtonZ = Key(-1000000044) @ExperimentalComposeUiApi actual val ButtonL1 = Key(-1000000045) @ExperimentalComposeUiApi actual val ButtonR1 = Key(-1000000046) @ExperimentalComposeUiApi actual val ButtonL2 = Key(-1000000047) @ExperimentalComposeUiApi actual val ButtonR2 = Key(-1000000048) @ExperimentalComposeUiApi actual val ButtonThumbLeft = Key(-1000000049) @ExperimentalComposeUiApi actual val ButtonThumbRight = Key(-1000000050) @ExperimentalComposeUiApi actual val ButtonStart = Key(-1000000051) @ExperimentalComposeUiApi actual val ButtonSelect = Key(-1000000052) @ExperimentalComposeUiApi actual val ButtonMode = Key(-1000000053) @ExperimentalComposeUiApi actual val Button1 = Key(-1000000054) @ExperimentalComposeUiApi actual val Button2 = Key(-1000000055) @ExperimentalComposeUiApi actual val Button3 = Key(-1000000056) @ExperimentalComposeUiApi actual val Button4 = Key(-1000000057) @ExperimentalComposeUiApi actual val Button5 = Key(-1000000058) @ExperimentalComposeUiApi actual val Button6 = Key(-1000000059) @ExperimentalComposeUiApi actual val Button7 = Key(-1000000060) @ExperimentalComposeUiApi actual val Button8 = Key(-1000000061) @ExperimentalComposeUiApi actual val Button9 = Key(-1000000062) @ExperimentalComposeUiApi actual val Button10 = Key(-1000000063) @ExperimentalComposeUiApi actual val Button11 = Key(-1000000064) @ExperimentalComposeUiApi actual val Button12 = Key(-1000000065) @ExperimentalComposeUiApi actual val Button13 = Key(-1000000066) @ExperimentalComposeUiApi actual val Button14 = Key(-1000000067) @ExperimentalComposeUiApi actual val Button15 = Key(-1000000068) @ExperimentalComposeUiApi actual val Button16 = Key(-1000000069) @ExperimentalComposeUiApi actual val Forward = Key(-1000000070) @ExperimentalComposeUiApi actual val MediaPlay = Key(-1000000071) @ExperimentalComposeUiApi actual val MediaPause = Key(-1000000072) @ExperimentalComposeUiApi actual val MediaPlayPause = Key(-1000000073) @ExperimentalComposeUiApi actual val MediaStop = Key(-1000000074) @ExperimentalComposeUiApi actual val MediaRecord = Key(-1000000075) @ExperimentalComposeUiApi actual val MediaNext = Key(-1000000076) @ExperimentalComposeUiApi actual val MediaPrevious = Key(-1000000077) @ExperimentalComposeUiApi actual val MediaRewind = Key(-1000000078) @ExperimentalComposeUiApi actual val MediaFastForward = Key(-1000000079) @ExperimentalComposeUiApi actual val MediaClose = Key(-1000000080) @ExperimentalComposeUiApi actual val MediaAudioTrack = Key(-1000000081) @ExperimentalComposeUiApi actual val MediaEject = Key(-1000000082) @ExperimentalComposeUiApi actual val MediaTopMenu = Key(-1000000083) @ExperimentalComposeUiApi actual val MediaSkipForward = Key(-1000000084) @ExperimentalComposeUiApi actual val MediaSkipBackward = Key(-1000000085) @ExperimentalComposeUiApi actual val MediaStepForward = Key(-1000000086) @ExperimentalComposeUiApi actual val MediaStepBackward = Key(-1000000087) @ExperimentalComposeUiApi actual val MicrophoneMute = Key(-1000000088) @ExperimentalComposeUiApi actual val VolumeMute = Key(-1000000089) @ExperimentalComposeUiApi actual val Info = Key(-1000000090) @ExperimentalComposeUiApi actual val ChannelUp = Key(-1000000091) @ExperimentalComposeUiApi actual val ChannelDown = Key(-1000000092) @ExperimentalComposeUiApi actual val ZoomIn = Key(-1000000093) @ExperimentalComposeUiApi actual val ZoomOut = Key(-1000000094) @ExperimentalComposeUiApi actual val Tv = Key(-1000000095) @ExperimentalComposeUiApi actual val Window = Key(-1000000096) @ExperimentalComposeUiApi actual val Guide = Key(-1000000097) @ExperimentalComposeUiApi actual val Dvr = Key(-1000000098) @ExperimentalComposeUiApi actual val Bookmark = Key(-1000000099) @ExperimentalComposeUiApi actual val Captions = Key(-1000000100) @ExperimentalComposeUiApi actual val Settings = Key(-1000000101) @ExperimentalComposeUiApi actual val TvPower = Key(-1000000102) @ExperimentalComposeUiApi actual val TvInput = Key(-1000000103) @ExperimentalComposeUiApi actual val SetTopBoxPower = Key(-1000000104) @ExperimentalComposeUiApi actual val SetTopBoxInput = Key(-1000000105) @ExperimentalComposeUiApi actual val AvReceiverPower = Key(-1000000106) @ExperimentalComposeUiApi actual val AvReceiverInput = Key(-1000000107) @ExperimentalComposeUiApi actual val ProgramRed = Key(-1000000108) @ExperimentalComposeUiApi actual val ProgramGreen = Key(-1000000109) @ExperimentalComposeUiApi actual val ProgramYellow = Key(-1000000110) @ExperimentalComposeUiApi actual val ProgramBlue = Key(-1000000111) @ExperimentalComposeUiApi actual val AppSwitch = Key(-1000000112) @ExperimentalComposeUiApi actual val LanguageSwitch = Key(-1000000113) @ExperimentalComposeUiApi actual val MannerMode = Key(-1000000114) @ExperimentalComposeUiApi actual val Toggle2D3D = Key(-1000000125) @ExperimentalComposeUiApi actual val Contacts = Key(-1000000126) @ExperimentalComposeUiApi actual val Calendar = Key(-1000000127) @ExperimentalComposeUiApi actual val Music = Key(-1000000128) @ExperimentalComposeUiApi actual val Calculator = Key(-1000000129) @ExperimentalComposeUiApi actual val ZenkakuHankaru = Key(-1000000130) @ExperimentalComposeUiApi actual val Eisu = Key(-1000000131) @ExperimentalComposeUiApi actual val Muhenkan = Key(-1000000132) @ExperimentalComposeUiApi actual val Henkan = Key(-1000000133) @ExperimentalComposeUiApi actual val KatakanaHiragana = Key(-1000000134) @ExperimentalComposeUiApi actual val Yen = Key(-1000000135) @ExperimentalComposeUiApi actual val Ro = Key(-1000000136) @ExperimentalComposeUiApi actual val Kana = Key(-1000000137) @ExperimentalComposeUiApi actual val Assist = Key(-1000000138) @ExperimentalComposeUiApi actual val BrightnessDown = Key(-1000000139) @ExperimentalComposeUiApi actual val BrightnessUp = Key(-1000000140) @ExperimentalComposeUiApi actual val Sleep = Key(-1000000141) @ExperimentalComposeUiApi actual val WakeUp = Key(-1000000142) @ExperimentalComposeUiApi actual val SoftSleep = Key(-1000000143) @ExperimentalComposeUiApi actual val Pairing = Key(-1000000144) @ExperimentalComposeUiApi actual val LastChannel = Key(-1000000145) @ExperimentalComposeUiApi actual val TvDataService = Key(-1000000146) @ExperimentalComposeUiApi actual val VoiceAssist = Key(-1000000147) @ExperimentalComposeUiApi actual val TvRadioService = Key(-1000000148) @ExperimentalComposeUiApi actual val TvTeletext = Key(-1000000149) @ExperimentalComposeUiApi actual val TvNumberEntry = Key(-1000000150) @ExperimentalComposeUiApi actual val TvTerrestrialAnalog = Key(-1000000151) @ExperimentalComposeUiApi actual val TvTerrestrialDigital = Key(-1000000152) @ExperimentalComposeUiApi actual val TvSatellite = Key(-1000000153) @ExperimentalComposeUiApi actual val TvSatelliteBs = Key(-1000000154) @ExperimentalComposeUiApi actual val TvSatelliteCs = Key(-1000000155) @ExperimentalComposeUiApi actual val TvSatelliteService = Key(-1000000156) @ExperimentalComposeUiApi actual val TvNetwork = Key(-1000000157) @ExperimentalComposeUiApi actual val TvAntennaCable = Key(-1000000158) @ExperimentalComposeUiApi actual val TvInputHdmi1 = Key(-1000000159) @ExperimentalComposeUiApi actual val TvInputHdmi2 = Key(-1000000160) @ExperimentalComposeUiApi actual val TvInputHdmi3 = Key(-1000000161) @ExperimentalComposeUiApi actual val TvInputHdmi4 = Key(-1000000162) @ExperimentalComposeUiApi actual val TvInputComposite1 = Key(-1000000163) @ExperimentalComposeUiApi actual val TvInputComposite2 = Key(-1000000164) @ExperimentalComposeUiApi actual val TvInputComponent1 = Key(-1000000165) @ExperimentalComposeUiApi actual val TvInputComponent2 = Key(-1000000166) @ExperimentalComposeUiApi actual val TvInputVga1 = Key(-1000000167) @ExperimentalComposeUiApi actual val TvAudioDescription = Key(-1000000168) @ExperimentalComposeUiApi actual val TvAudioDescriptionMixingVolumeUp = Key(-1000000169) @ExperimentalComposeUiApi actual val TvAudioDescriptionMixingVolumeDown = Key(-1000000170) @ExperimentalComposeUiApi actual val TvZoomMode = Key(-1000000171) @ExperimentalComposeUiApi actual val TvContentsMenu = Key(-1000000172) @ExperimentalComposeUiApi actual val TvMediaContextMenu = Key(-1000000173) @ExperimentalComposeUiApi actual val TvTimerProgramming = Key(-1000000174) @ExperimentalComposeUiApi actual val StemPrimary = Key(-1000000175) @ExperimentalComposeUiApi actual val Stem1 = Key(-1000000176) @ExperimentalComposeUiApi actual val Stem2 = Key(-1000000177) @ExperimentalComposeUiApi actual val Stem3 = Key(-1000000178) @ExperimentalComposeUiApi actual val AllApps = Key(-1000000179) @ExperimentalComposeUiApi actual val Refresh = Key(-1000000180) @ExperimentalComposeUiApi actual val ThumbsUp = Key(-1000000181) @ExperimentalComposeUiApi actual val ThumbsDown = Key(-1000000182) @ExperimentalComposeUiApi actual val ProfileSwitch = Key(-1000000183) } actual override fun toString(): String { return "Key: ${KeyEvent.getKeyText(nativeKeyCode)}" } } /** * Creates instance of [Key]. * * @param nativeKeyCode represents this key as defined in [java.awt.event.KeyEvent] * @param nativeKeyLocation represents the location of key as defined in [java.awt.event.KeyEvent] */ fun Key(nativeKeyCode: Int, nativeKeyLocation: Int = KEY_LOCATION_STANDARD): Key { // First 32 bits are for keycode. val keyCode = nativeKeyCode.toLong().shl(32) // Next 3 bits are for location. val location = (nativeKeyLocation.toLong() and 0x7).shl(29) return Key(keyCode or location) } /** * The native keycode corresponding to this [Key]. */ val Key.nativeKeyCode: Int get() = unpackInt1(keyCode) /** * The native location corresponding to this [Key]. */ val Key.nativeKeyLocation: Int get() = (keyCode and 0xFFFFFFFF).shr(29).toInt()
apache-2.0
b1d55d421c73e5c008eac1f3f7cccf4d
33.736324
99
0.634036
5.071725
false
false
false
false
GunoH/intellij-community
java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointIntentionAction.kt
2
7369
// 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.debugger.ui.breakpoints import com.intellij.debugger.InstanceFilter import com.intellij.debugger.JavaDebuggerBundle import com.intellij.debugger.engine.JavaDebugProcess import com.intellij.debugger.engine.JavaStackFrame import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsActions.ActionText import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.classFilter.ClassFilter import com.intellij.util.ArrayUtil import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.breakpoints.XBreakpoint import com.intellij.xdebugger.impl.breakpoints.XBreakpointBase import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperties internal abstract class BreakpointIntentionAction(protected val myBreakpoint: XBreakpoint<*>, @ActionText text : String) : AnAction(text) { override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } internal class AddCallerNotFilter(breakpoint: XBreakpoint<*>, private val myCaller: String) : BreakpointIntentionAction(breakpoint, JavaDebuggerBundle.message( "action.do.not.stop.if.called.from.text", StringUtil.getShortName(StringUtil.substringBefore(myCaller, "(") ?: myCaller))) { override fun update(e: AnActionEvent) { with(myBreakpoint.properties as JavaBreakpointProperties<*>) { e.presentation.setEnabled(!isCALLER_FILTERS_ENABLED || !callerExclusionFilters.contains(ClassFilter(myCaller))) } } override fun actionPerformed(e: AnActionEvent) { with(myBreakpoint.properties as JavaBreakpointProperties<*>) { isCALLER_FILTERS_ENABLED = true val callerFilter = ClassFilter(myCaller) callerFilters = ArrayUtil.remove(callerFilters, callerFilter) callerExclusionFilters = appendIfNeeded(callerExclusionFilters, callerFilter) } (myBreakpoint as XBreakpointBase<*, *, *>).fireBreakpointChanged() } } internal class AddCallerFilter(breakpoint: XBreakpoint<*>, private val myCaller: String) : BreakpointIntentionAction(breakpoint, JavaDebuggerBundle.message("action.stop.only.if.called.from.text", StringUtil.getShortName(StringUtil.substringBefore(myCaller, "(") ?: myCaller))) { override fun update(e: AnActionEvent) { with(myBreakpoint.properties as JavaBreakpointProperties<*>) { e.presentation.setEnabled(!isCALLER_FILTERS_ENABLED || !callerFilters.contains(ClassFilter(myCaller))) } } override fun actionPerformed(e: AnActionEvent) { with(myBreakpoint.properties as JavaBreakpointProperties<*>) { isCALLER_FILTERS_ENABLED = true val callerFilter = ClassFilter(myCaller) callerFilters = appendIfNeeded(callerFilters, callerFilter) callerExclusionFilters = ArrayUtil.remove(callerExclusionFilters, callerFilter) } (myBreakpoint as XBreakpointBase<*, *, *>).fireBreakpointChanged() } } internal class AddInstanceFilter(breakpoint: XBreakpoint<*>, private val myInstance: Long) : BreakpointIntentionAction(breakpoint, JavaDebuggerBundle.message("action.stop.only.in.current.object.text")) { override fun update(e: AnActionEvent) { with(myBreakpoint.properties as JavaBreakpointProperties<*>) { e.presentation.setEnabled(!isINSTANCE_FILTERS_ENABLED || !instanceFilters.contains(InstanceFilter.create(myInstance))) } } override fun actionPerformed(e: AnActionEvent) { with(myBreakpoint.properties as JavaBreakpointProperties<*>) { isINSTANCE_FILTERS_ENABLED = true instanceFilters = appendIfNeeded(instanceFilters, InstanceFilter.create(myInstance)) } (myBreakpoint as XBreakpointBase<*, *, *>).fireBreakpointChanged() } } internal class AddClassFilter(breakpoint: XBreakpoint<*>, private val myClass: String) : BreakpointIntentionAction(breakpoint, JavaDebuggerBundle.message("action.stop.only.in.class.text", StringUtil.getShortName(myClass))) { override fun update(e: AnActionEvent) { with(myBreakpoint.properties as JavaBreakpointProperties<*>) { e.presentation.setEnabled(!isCLASS_FILTERS_ENABLED || !classFilters.contains(ClassFilter(myClass))) } } override fun actionPerformed(e: AnActionEvent) { with(myBreakpoint.properties as JavaBreakpointProperties<*>) { isCLASS_FILTERS_ENABLED = true val classFilter = ClassFilter(myClass) classFilters = appendIfNeeded(classFilters, classFilter) classExclusionFilters = ArrayUtil.remove(classExclusionFilters, classFilter) } (myBreakpoint as XBreakpointBase<*, *, *>).fireBreakpointChanged() } } internal class AddClassNotFilter(breakpoint: XBreakpoint<*>, private val myClass: String) : BreakpointIntentionAction(breakpoint, JavaDebuggerBundle.message("action.do.not.stop.in.class.text", StringUtil.getShortName(myClass))) { override fun update(e: AnActionEvent) { with(myBreakpoint.properties as JavaBreakpointProperties<*>) { e.presentation.setEnabled(!isCLASS_FILTERS_ENABLED || !classExclusionFilters.contains(ClassFilter(myClass))) } } override fun actionPerformed(e: AnActionEvent) { with(myBreakpoint.properties as JavaBreakpointProperties<*>) { isCLASS_FILTERS_ENABLED = true val classFilter = ClassFilter(myClass) classExclusionFilters = appendIfNeeded(classExclusionFilters, classFilter) classFilters = ArrayUtil.remove(classFilters, classFilter) } (myBreakpoint as XBreakpointBase<*, *, *>).fireBreakpointChanged() } } companion object { @JvmField val CALLER_KEY = Key.create<String>("CALLER_KEY") @JvmField val THIS_TYPE_KEY = Key.create<String>("THIS_TYPE_KEY") @JvmField val THIS_ID_KEY = Key.create<Long>("THIS_ID_KEY") @JvmStatic fun getIntentions(breakpoint: XBreakpoint<*>, currentSession: XDebugSession?): List<AnAction> { val process = currentSession?.debugProcess if (process is JavaDebugProcess) { val res = ArrayList<AnAction>() val currentStackFrame = currentSession.currentStackFrame if (currentStackFrame is JavaStackFrame) { val frameDescriptor = currentStackFrame.descriptor frameDescriptor.getUserData(THIS_TYPE_KEY)?.let { res.add(AddClassFilter(breakpoint, it)) res.add(AddClassNotFilter(breakpoint, it)) } frameDescriptor.getUserData(THIS_ID_KEY)?.let { res.add(AddInstanceFilter(breakpoint, it)) } frameDescriptor.getUserData(CALLER_KEY)?.let { res.add(AddCallerFilter(breakpoint, it)) res.add(AddCallerNotFilter(breakpoint, it)) } } return res } return emptyList() } private fun <T> appendIfNeeded(array: Array<T>, element: T): Array<T> { return if (array.contains(element)) { array } else { ArrayUtil.append(array, element) } } } }
apache-2.0
411c4c93954b616b5e0848c9a46fa9a9
40.869318
179
0.723979
5.016338
false
false
false
false
siosio/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/hint/types/GroovyLocalVariableTypeHintsInlayProvider.kt
2
1759
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.codeInsight.hint.types import com.intellij.codeInsight.hints.* import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiFile import com.intellij.ui.layout.* import org.jetbrains.plugins.groovy.GroovyBundle import javax.swing.JPanel class GroovyLocalVariableTypeHintsInlayProvider : InlayHintsProvider<GroovyLocalVariableTypeHintsInlayProvider.Settings> { companion object { private val ourKey: SettingsKey<Settings> = SettingsKey("groovy.variable.type.hints") } override fun getCollectorFor(file: PsiFile, editor: Editor, settings: Settings, sink: InlayHintsSink): InlayHintsCollector = GroovyLocalVariableTypeHintsCollector(editor, settings) override fun createSettings(): Settings = Settings() data class Settings(var insertBeforeIdentifier : Boolean = false) override val name: String = GroovyBundle.message("local.variable.types") override val key: SettingsKey<Settings> = ourKey override val previewText: String = """ def foo() { def x = 1 var y = "abc" } """.trimIndent() override fun createConfigurable(settings: Settings): ImmediateConfigurable = object : ImmediateConfigurable { override val cases: List<ImmediateConfigurable.Case> = listOf( ImmediateConfigurable.Case(GroovyBundle.message("settings.inlay.put.type.hint.before.identifier"), "inferred.parameter.types", settings::insertBeforeIdentifier), ) override fun createComponent(listener: ChangeListener): JPanel = panel {} override val mainCheckboxText: String get() = GroovyBundle.message("settings.inlay.show.variable.type.hints") } }
apache-2.0
90dacbd5aaeaf7e220e7cb75f02c711a
41.926829
182
0.779989
4.678191
false
true
false
false
bjansen/pebble-intellij
src/main/kotlin/com/github/bjansen/intellij/pebble/PebbleBundle.kt
1
905
package com.github.bjansen.intellij.pebble import com.intellij.CommonBundle import com.intellij.reference.SoftReference import org.jetbrains.annotations.PropertyKey import java.lang.ref.Reference import java.util.* /** * I18N messages. */ object PebbleBundle { private var ourBundle: Reference<ResourceBundle>? = null private const val bundleName = "messages.PebbleBundle" fun message(@PropertyKey(resourceBundle = bundleName) key: String, vararg params: Any): String { return CommonBundle.message(bundle, key, *params) } private val bundle: ResourceBundle get() { var resourceBundle = SoftReference.dereference(ourBundle) if (resourceBundle == null) { resourceBundle = ResourceBundle.getBundle(bundleName) ourBundle = java.lang.ref.SoftReference<ResourceBundle>(resourceBundle) } return resourceBundle!! } }
mit
413f0c0193c05b0c563f8283e48549f4
29.166667
100
0.720442
4.713542
false
false
false
false
TimePath/java-vfs
src/main/kotlin/com/timepath/vfs/server/cifs/CIFSWatcher.kt
1
9909
package com.timepath.vfs.server.cifs import com.timepath.vfs.FileChangeListener import java.io.IOException import java.io.InputStream import java.net.InetAddress import java.net.ServerSocket import java.net.Socket import java.nio.ByteBuffer import java.util.Arrays import java.util.LinkedList import java.util.logging.Level import java.util.logging.Logger import kotlin.platform.platformStatic /** * http://www.codefx.com/CIFS_Explained.htm * smbclient --ip-address=localhost --port=8000 -M hi * * @author TimePath */ class CIFSWatcher private constructor(port: Int) { private val listeners = LinkedList<FileChangeListener>() init { try { // On windows, the loopback address does not prompt the firewall // Also good for security in general val sock = ServerSocket(port, 0, InetAddress.getLoopbackAddress()) val realPort = sock.getLocalPort() LOG.log(Level.INFO, "Listening on port {0}", realPort) Runtime.getRuntime().addShutdownHook (Thread { LOG.info("CIFS server shutting down...") }) Thread(object : Runnable { private val data: Socket? = null private val pasv: ServerSocket? = null override fun run() { while (true) { val client: Socket try { LOG.info("Waiting for client...") client = sock.accept() LOG.info("Connected") } catch (ex: IOException) { Logger.getLogger(javaClass<CIFSWatcher>().getName()).log(Level.SEVERE, null, ex) continue } Thread(object : Runnable { override fun run() { try { val input = client.getInputStream() while (!client.isClosed()) { try { val buf = ByteArray(200) while (input.read(buf) != -1) { val text = String(buf).trim() LOG.info(Arrays.toString(text.toByteArray())) LOG.info(text) } // TODO: Packet handling } catch (ex: Exception) { LOG.log(Level.SEVERE, null, ex) client.close() break } } LOG.info("Socket closed") } catch (ex: IOException) { Logger.getLogger(javaClass<CIFSWatcher>().getName()).log(Level.SEVERE, null, ex) } } inner class Packet { private var header: Int = 0 // \0xFF S M B throws(IOException::class) private fun read(`is`: InputStream): Packet { val buf = ByteBuffer.allocate(42) // Average CIFS header size val head = ByteArray(24) `is`.read(head) LOG.info(Arrays.toString(head)) LOG.info(String(head)) buf.put(head) buf.flip() header = buf.getInt() command = buf.get() errorClass = buf.get() buf.get() // == 0 errorCode = buf.getShort() flags = buf.get() flags2 = buf.getShort() secure = buf.getLong() // or padding tid = buf.getShort() // Tree ID pid = buf.getShort() // Process ID uid = buf.getShort() // User ID mid = buf.getShort() // Multiplex ID val wordCount = `is`.read() val words = ByteArray(wordCount * 2) `is`.read(words) val wordBuffer = ByteBuffer.wrap(words) val arr = ShortArray(wordCount) parameterWords = arr for (i in words.indices) { arr[i] = wordBuffer.getShort() } val payloadLength = `is`.read() buffer = ByteArray(payloadLength) `is`.read(buffer) return this } private var command: Byte = 0 /** * ERRDOS (0x01) – * Error is from the * core DOS operating * system * set * ERRSRV (0x02) – * Error is generated * by the server * network * file manager * ERRHRD (0x03) – * Hardware error * ERRCMD (0xFF) – * Command was not * in the “SMB” * format */ private var errorClass: Byte = 0 /** * As specified in * CIFS1.0 draft */ private var errorCode: Short = 0 /** * When bit 3 is set * to ‘1’, all pathnames * in this particular * packet must be * treated as * caseless * When bit 3 is set * to ‘0’, all pathnames * are case sensitive */ private var flags: Byte = 0 /** * Bit 0, if set, * indicates that * the server may * return long * file names in the * response * Bit 6, if set, * indicates that * any pathname in * the request is * a long file name * Bit 16, if set, * indicates strings * in the packet are * encoded * as UNICODE */ private var flags2: Short = 0 /** * Typically zero */ private var secure: Long = 0 private var tid: Short = 0 private var buffer: ByteArray? = null private var parameterWords: ShortArray? = null private var pid: Short = 0 private var uid: Short = 0 private var mid: Short = 0 val bytes: ByteArray? = null } }).start() } } }, "CIFS Server").start() } catch (ex: IOException) { Logger.getLogger(javaClass<CIFSWatcher>().getName()).log(Level.SEVERE, null, ex) } } public fun addFileChangeListener(listener: FileChangeListener) { listeners.add(listener) } companion object { private val LOG = Logger.getLogger(javaClass<CIFSWatcher>().getName()) private var instance: CIFSWatcher? = null public platformStatic fun main(args: Array<String>) { var port = 8000 if (args.size() >= 1) { port = Integer.parseInt(args[0]) } getInstance(port) } private fun getInstance(port: Int): CIFSWatcher { if (instance == null) { instance = CIFSWatcher(port) } return instance!! } } }
artistic-2.0
77a5c21fcb16c0b99918dc5f28d74e5e
43.746606
116
0.339569
6.968992
false
false
false
false
srodrigo/Kotlin-Wars
app/src/main/kotlin/me/srodrigo/kotlinwars/model/people/PeopleListActivity.kt
1
3366
package me.srodrigo.kotlinwars.model.people import android.os.Bundle import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import kotlinx.android.synthetic.main.activity_people_list.* import me.srodrigo.kotlinwars.R import me.srodrigo.kotlinwars.infrastructure.view.DividerItemDecoration import me.srodrigo.kotlinwars.infrastructure.view.ViewStateHandler import me.srodrigo.kotlinwars.infrastructure.view.app import me.srodrigo.kotlinwars.infrastructure.view.showMessage import me.srodrigo.kotlinwars.people.PeopleListPresenter import me.srodrigo.kotlinwars.people.PeopleListView import kotlin.properties.Delegates class PeopleListActivity : AppCompatActivity(), SwipeRefreshLayout.OnRefreshListener, PeopleListView { val peopleListAdapter = PeopleListAdapter() val peopleListStateHolder = ViewStateHandler<PeopleListState>() var peopleListPresenter by Delegates.notNull<PeopleListPresenter>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_people_list) if (savedInstanceState == null) { peopleListPresenter = PeopleListPresenter(app().executor, app().createGetPeopleCommand()) } peopleListPresenter.attachView(this) } override fun onResume() { super.onResume() peopleListPresenter.onRefresh() } override fun onDestroy() { peopleListPresenter.detachView() super.onDestroy() } override fun onRefresh() { peopleListPresenter.onRefresh() } //--- View actions override fun initPeopleListView() { initToolbar() initSwipeLayout() initPeopleList() } private fun initToolbar() { val toolbar = findViewById(R.id.toolbar) as? Toolbar if (toolbar != null) { setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(false) } } private fun initSwipeLayout() { peopleSwipeLayout.setOnRefreshListener(this) peopleSwipeLayout.isEnabled = true } private fun initPeopleList() { peopleListView.layoutManager = LinearLayoutManager(this) peopleListView.adapter = peopleListAdapter peopleListView.itemAnimator = DefaultItemAnimator() peopleListView.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL)) peopleListView.addOnScrollListener(object : RecyclerView.OnScrollListener() { }) peopleListStateHolder.bind(PeopleListState.LOADING, peopleLoadingView) peopleListStateHolder.bind(PeopleListState.EMPTY, peopleEmptyView) peopleListStateHolder.bind(PeopleListState.LIST, peopleListView) } override fun refreshPeopleList(peopleList: List<Person>) { peopleListAdapter.set(peopleList) peopleListStateHolder.show(PeopleListState.LIST) } override fun showLoadingView() { peopleListStateHolder.show(PeopleListState.LOADING) } override fun hideLoadingView() { peopleSwipeLayout.isRefreshing = false } override fun showPeopleEmptyView() { peopleListStateHolder.show(PeopleListState.EMPTY) } override fun showGenericError() { showMessage(R.string.unknown_error) } override fun showNetworkUnavailableError() { showMessage(R.string.network_unavailable) } enum class PeopleListState { LOADING, EMPTY, LIST } }
mit
9895e2ed407ec33c61e6bec2d4a26840
28.526316
102
0.80719
4.371429
false
false
false
false
hitting1024/SvnDiffBrowser
SvnDiffBrowser/src/main/kotlin/jp/hitting/svn_diff_browser/service/RepositoryServiceImpl.kt
1
5608
package jp.hitting.svn_diff_browser.service; import jp.hitting.svn_diff_browser.model.LogInfo import jp.hitting.svn_diff_browser.model.PathInfo import jp.hitting.svn_diff_browser.model.RepositoryModel import jp.hitting.svn_diff_browser.util.DiffUtil import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Service import org.springframework.util.StringUtils import org.tmatesoft.svn.core.* import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl import org.tmatesoft.svn.core.io.SVNRepository import org.tmatesoft.svn.core.io.SVNRepositoryFactory import org.tmatesoft.svn.core.wc.SVNDiffClient import org.tmatesoft.svn.core.wc.SVNLogClient import org.tmatesoft.svn.core.wc.SVNRevision import org.tmatesoft.svn.core.wc.SVNWCUtil import java.io.ByteArrayOutputStream import java.util.* /** * Repository Service Implementation. * Created by hitting on 2016/02/14. */ @Service class RepositoryServiceImpl : RepositoryService { @Value("\${commit-log-chunk}") private val commitLogChunk: Long = 10 /** * constructor. * Repository setup. */ init { DAVRepositoryFactory.setup() SVNRepositoryFactoryImpl.setup() FSRepositoryFactory.setup() } /** * {@inheritDoc} */ override fun existsRepository(repositoryModel: RepositoryModel): Boolean { try { val repository = this.initRepository(repositoryModel) ?: return false val nodeKind = repository.checkPath("", -1) if (SVNNodeKind.NONE == nodeKind) { return false } } catch (e: SVNException) { e.printStackTrace() return false } return true } /** * {@inheritDoc} */ override fun getLogList(repositoryModel: RepositoryModel, path: String, lastRev: Long?): List<LogInfo> { val list = ArrayList<LogInfo>() try { val url = repositoryModel.url if (StringUtils.isEmpty(url)) { return Collections.emptyList() } // val svnUrl = SVNURL.parseURIDecoded(url) // FIXME val auth = SVNWCUtil.createDefaultAuthenticationManager(repositoryModel.userId, repositoryModel.password.toCharArray()) val logClient = SVNLogClient(auth, null) val endRev = if (lastRev == null) SVNRevision.HEAD else SVNRevision.create(lastRev) logClient.doLog(svnUrl, arrayOf(path), endRev, endRev, SVNRevision.create(1), false, false, this.commitLogChunk, { logEntry -> println(logEntry.revision) val l = LogInfo() l.rev = logEntry.revision l.comment = logEntry.message ?: "" list.add(l) }) } catch (e: SVNException) { e.printStackTrace() return Collections.emptyList() } return list } /** * {@inheritDoc} */ override fun getPathList(repositoryModel: RepositoryModel, path: String): List<PathInfo> { val list = ArrayList<PathInfo>() try { val repository = this.initRepository(repositoryModel) ?: return Collections.emptyList() val rev = repository.latestRevision val dirs = repository.getDir(path, rev, null, null as? Collection<*>) as Collection<SVNDirEntry> dirs.forEach { val p = PathInfo() p.path = it.relativePath p.comment = it.commitMessage ?: "" p.isDir = (SVNNodeKind.DIR == it.kind) list.add(p) } } catch (e: SVNException) { e.printStackTrace() return Collections.emptyList() } return list } /** * {@inheritDoc} */ override fun getDiffList(repositoryModel: RepositoryModel, rev: Long): String { try { val url = repositoryModel.url if (StringUtils.isEmpty(url)) { return "" } // val svnUrl = SVNURL.parseURIDecoded(url) // FIXME val auth = SVNWCUtil.createDefaultAuthenticationManager(repositoryModel.userId, repositoryModel.password.toCharArray()) val diffClient = SVNDiffClient(auth, null) val outputStream = ByteArrayOutputStream() diffClient.doDiff(svnUrl, SVNRevision.create(rev - 1), svnUrl, SVNRevision.create(rev), SVNDepth.INFINITY, false, outputStream) return DiffUtil.formatDiff(outputStream.toByteArray()) } catch (e: SVNException) { e.printStackTrace() return "" } } /** * init repository. * * @param repositoryModel repository information * @return svn repository with auth info * @throws SVNException throw it when svnkit can't connect repository */ @Throws(SVNException::class) private fun initRepository(repositoryModel: RepositoryModel): SVNRepository? { val url = repositoryModel.url if (StringUtils.isEmpty(url)) { return null } val svnUrl = SVNURL.parseURIDecoded(url) // FIXME val auth = SVNWCUtil.createDefaultAuthenticationManager(repositoryModel.userId, repositoryModel.password.toCharArray()) val repository = SVNRepositoryFactory.create(svnUrl) repository.authenticationManager = auth return repository } }
mit
c34d2cee9fb4c0f1d7ea6c70e2f69ee0
33.195122
139
0.632846
4.685046
false
false
false
false
hazuki0x0/YuzuBrowser
module/core/src/main/java/jp/hazuki/yuzubrowser/core/Constants.kt
1
913
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.core const val MIME_TYPE_UNKNOWN = "application/octet-stream" const val MIME_TYPE_MHTML = "multipart/related" const val MIME_TYPE_HTML = "text/html" const val READER_FONT_NAME = "reader_font.bin" const val THEME_DIR = "theme" const val USER_AGENT_PC = "yuzu://useragent/type/pc"
apache-2.0
2135929d875513d5aca183996fe58672
32.814815
75
0.738226
3.681452
false
false
false
false