repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
GeoffreyMetais/vlc-android
application/mediadb/src/main/java/org/videolan/vlc/mediadb/Migrations.kt
1
8966
/******************************************************************************* * Migrations.kt * **************************************************************************** * Copyright © 2018 VLC authors and VideoLAN * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. ******************************************************************************/ package org.videolan.vlc.database import android.content.Context import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.videolan.resources.AndroidDevices import org.videolan.resources.AppContextProvider import org.videolan.resources.TYPE_LOCAL_FAV import org.videolan.tools.Settings private const val DIR_TABLE_NAME = "directories_table" private const val MEDIA_TABLE_NAME = "media_table" private const val PLAYLIST_TABLE_NAME = "playlist_table" private const val PLAYLIST_MEDIA_TABLE_NAME = "playlist_media_table" private const val SEARCHHISTORY_TABLE_NAME = "searchhistory_table" private const val MRL_TABLE_NAME = "mrl_table" private const val HISTORY_TABLE_NAME = "history_table" private const val EXTERNAL_SUBTITLES_TABLE_NAME = "external_subtitles_table" private const val SLAVES_TABLE_NAME = "SLAVES_table" private const val FAV_TABLE_NAME = "fav_table" private const val CUSTOM_DIRECTORY_TABLE_NAME = "CustomDirectory" fun dropUnnecessaryTables(database: SupportSQLiteDatabase) { database.execSQL("DROP TABLE IF EXISTS $DIR_TABLE_NAME;") database.execSQL("DROP TABLE IF EXISTS $MEDIA_TABLE_NAME;") database.execSQL("DROP TABLE IF EXISTS $PLAYLIST_MEDIA_TABLE_NAME;") database.execSQL("DROP TABLE IF EXISTS $PLAYLIST_TABLE_NAME;") database.execSQL("DROP TABLE IF EXISTS $SEARCHHISTORY_TABLE_NAME;") database.execSQL("DROP TABLE IF EXISTS $MRL_TABLE_NAME;") database.execSQL("DROP TABLE IF EXISTS $HISTORY_TABLE_NAME;") } val migration_1_2 = object:Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) {} } val migration_2_3 = object:Migration(2, 3) { override fun migrate(database: SupportSQLiteDatabase) {} } val migration_3_4 = object:Migration(3, 4) { override fun migrate(database: SupportSQLiteDatabase) {} } val migration_4_5 = object:Migration(4, 5) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_5_6 = object:Migration(5, 6) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_6_7 = object:Migration(6, 7) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_7_8 = object:Migration(7, 8) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_8_9 = object:Migration(8, 9) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_9_10 = object:Migration(9, 10) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_10_11 = object:Migration(10, 11) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_11_12 = object:Migration(11, 12) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_12_13 = object:Migration(12, 13) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_13_14 = object:Migration(13, 14) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_14_15 = object:Migration(14, 15) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_15_16 = object:Migration(15, 16) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_16_17 = object:Migration(16, 17) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_17_18 = object:Migration(17, 18) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_18_19 = object:Migration(18, 19) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_19_20 = object:Migration(19, 20) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_20_21 = object:Migration(20, 21) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_21_22 = object:Migration(21, 22) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_22_23 = object:Migration(22, 23) { override fun migrate(database: SupportSQLiteDatabase) { } } val migration_23_24 = object:Migration(23, 24) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("DROP TABLE IF EXISTS $FAV_TABLE_NAME;") database.execSQL("CREATE TABLE IF NOT EXISTS $FAV_TABLE_NAME ( uri TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL, icon_url TEXT);") } } val migration_24_25 = object:Migration(24, 25) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("CREATE TABLE IF NOT EXISTS $EXTERNAL_SUBTITLES_TABLE_NAME ( uri TEXT PRIMARY KEY NOT NULL, media_name TEXT NOT NULL);") } } val migration_25_26 = object:Migration(25, 26) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("CREATE TABLE IF NOT EXISTS $SLAVES_TABLE_NAME ( slave_media_mrl TEXT PRIMARY KEY NOT NULL, slave_type INTEGER NOT NULL, slave_priority INTEGER, slave_uri TEXT NOT NULL);") } } val migration_26_27 = object:Migration(26, 27) { override fun migrate(database: SupportSQLiteDatabase) { dropUnnecessaryTables(database) val slavesTableNameTemp = "${SLAVES_TABLE_NAME}_TEMP" database.execSQL("UPDATE $SLAVES_TABLE_NAME SET slave_priority=2 WHERE slave_priority IS NULL;") database.execSQL("CREATE TABLE IF NOT EXISTS $slavesTableNameTemp ( slave_media_mrl TEXT PRIMARY KEY NOT NULL, slave_type INTEGER NOT NULL, slave_priority INTEGER NOT NULL, slave_uri TEXT NOT NULL);") database.execSQL("INSERT INTO $slavesTableNameTemp(slave_media_mrl, slave_type, slave_priority, slave_uri) SELECT slave_media_mrl, slave_type, slave_priority, slave_uri FROM $SLAVES_TABLE_NAME") database.execSQL("DROP TABLE $SLAVES_TABLE_NAME") database.execSQL("ALTER TABLE $slavesTableNameTemp RENAME TO $SLAVES_TABLE_NAME") // Add a type column and set its value to 0 (till this version all favs were network favs) database.execSQL("ALTER TABLE $FAV_TABLE_NAME ADD COLUMN type INTEGER NOT NULL DEFAULT 0;") } } val migration_27_28 = object:Migration(27, 28) { override fun migrate(database: SupportSQLiteDatabase) { val preferences = Settings.getInstance(AppContextProvider.appContext) val customPaths = preferences.getString("custom_paths", "") var oldPaths : List<String>? = null if (!customPaths.isNullOrEmpty()) oldPaths = customPaths.split(":") database.execSQL("CREATE TABLE IF NOT EXISTS $CUSTOM_DIRECTORY_TABLE_NAME(path TEXT PRIMARY KEY NOT NULL);") oldPaths?.forEach { database.execSQL("INSERT INTO $CUSTOM_DIRECTORY_TABLE_NAME(path) VALUES (\"$it\")") } } } val migration_28_29 = object:Migration(28, 29) { override fun migrate(database: SupportSQLiteDatabase) { // Drop old External Subtitle Table database.execSQL("DROP TABLE IF EXISTS $EXTERNAL_SUBTITLES_TABLE_NAME;") database.execSQL("CREATE TABLE IF NOT EXISTS `${EXTERNAL_SUBTITLES_TABLE_NAME}` (`idSubtitle` TEXT NOT NULL, `subtitlePath` TEXT NOT NULL, `mediaPath` TEXT NOT NULL, `subLanguageID` TEXT NOT NULL, `movieReleaseName` TEXT NOT NULL, PRIMARY KEY(`mediaPath`, `idSubtitle`))") } } fun populateDB(context: Context) = GlobalScope.launch(Dispatchers.IO) { val uris = listOf(AndroidDevices.MediaFolders.EXTERNAL_PUBLIC_MOVIES_DIRECTORY_URI, AndroidDevices.MediaFolders.EXTERNAL_PUBLIC_MUSIC_DIRECTORY_URI, AndroidDevices.MediaFolders.EXTERNAL_PUBLIC_PODCAST_DIRECTORY_URI, AndroidDevices.MediaFolders.EXTERNAL_PUBLIC_DOWNLOAD_DIRECTORY_URI, AndroidDevices.MediaFolders.WHATSAPP_VIDEOS_FILE_URI) val browserFavDao = MediaDatabase.getInstance(context).browserFavDao() for (uri in uris) browserFavDao.insert(org.videolan.vlc.mediadb.models.BrowserFav(uri, TYPE_LOCAL_FAV, uri.lastPathSegment ?: "", null)) }
gpl-2.0
85e244e5aedcfc5d7c0be46c18e36563
40.702326
280
0.713107
3.979139
false
false
false
false
gotev/android-upload-service
uploadservice/src/main/java/net/gotev/uploadservice/data/UploadTaskParameters.kt
2
2053
package net.gotev.uploadservice.data import android.os.Parcelable import kotlinx.parcelize.Parcelize import net.gotev.uploadservice.persistence.Persistable import net.gotev.uploadservice.persistence.PersistableData @Parcelize data class UploadTaskParameters( val taskClass: String, val id: String, val serverUrl: String, val maxRetries: Int, val autoDeleteSuccessfullyUploadedFiles: Boolean, val files: ArrayList<UploadFile>, val additionalParameters: PersistableData ) : Parcelable, Persistable { override fun toPersistableData() = PersistableData().apply { putString(CodingKeys.taskClass, taskClass) putString(CodingKeys.id, id) putString(CodingKeys.serverUrl, serverUrl) putInt(CodingKeys.maxRetries, maxRetries) putBoolean(CodingKeys.autoDeleteFiles, autoDeleteSuccessfullyUploadedFiles) putArrayData(CodingKeys.files, files.map { it.toPersistableData() }) putData(CodingKeys.params, additionalParameters) } companion object : Persistable.Creator<UploadTaskParameters> { private object CodingKeys { const val taskClass = "taskClass" const val id = "id" const val serverUrl = "serverUrl" const val maxRetries = "maxRetries" const val autoDeleteFiles = "autoDeleteFiles" const val files = "files" const val params = "params" } override fun createFromPersistableData(data: PersistableData) = UploadTaskParameters( taskClass = data.getString(CodingKeys.taskClass), id = data.getString(CodingKeys.id), serverUrl = data.getString(CodingKeys.serverUrl), maxRetries = data.getInt(CodingKeys.maxRetries), autoDeleteSuccessfullyUploadedFiles = data.getBoolean(CodingKeys.autoDeleteFiles), files = ArrayList(data.getArrayData(CodingKeys.files).map { UploadFile.createFromPersistableData(it) }), additionalParameters = data.getData(CodingKeys.params) ) } }
apache-2.0
65281ab3c05b0b8d8d41cc35186c6165
40.897959
116
0.703361
4.763341
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/data/push/PushRepositoryImpl.kt
1
1983
package com.quickblox.sample.conference.kotlin.data.push import android.content.Context import android.util.Log import com.quickblox.messages.services.QBPushManager import com.quickblox.messages.services.QBPushManager.QBSubscribeListener import com.quickblox.messages.services.SubscribeService import com.quickblox.sample.conference.kotlin.domain.repositories.push.PushRepository private val TAG: String = PushRepositoryImpl::class.java.simpleName /* * Created by Injoit in 2021-09-30. * Copyright © 2021 Quickblox. All rights reserved. */ class PushRepositoryImpl(private val context: Context) : PushRepository { override fun unsubscribe(unsubscribeCallback: () -> Unit) { QBPushManager.getInstance().addListener(SubscribeListenerImpl(TAG, unsubscribeCallback)) SubscribeService.unSubscribeFromPushes(context) } override fun isSubscribed(): Boolean { return QBPushManager.getInstance().isSubscribedToPushes } private inner class SubscribeListenerImpl(val tag: String, val unsubscribeCallback: () -> Unit) : QBSubscribeListener { override fun onSubscriptionCreated() { Log.d(TAG, "Subscription Created") } override fun onSubscriptionError(exception: Exception, i: Int) { Log.d(TAG, "Subscription Error - " + exception.message) } override fun onSubscriptionDeleted(deleted: Boolean) { unsubscribeCallback.invoke() QBPushManager.getInstance().removeListener(this) Log.d(TAG, "Subscription Deleted") } override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other !is SubscribeListenerImpl) { return false } return tag == other.tag } override fun hashCode(): Int { var hash = 1 hash = 31 * hash + tag.hashCode() return hash } } }
bsd-3-clause
4bad9fbf898b3474b8d83205e54bf3eb
33.789474
123
0.665489
4.822384
false
false
false
false
KenVanHoeylandt/KIP-8
src/main/kotlin/com/bytewelder/kip8/ui/ScreenBuffer.kt
1
1216
package com.bytewelder.kip8.ui /** * Thread-safe screen buffer that holds pixel on/off values */ class ScreenBuffer( val columns: Int, val rows: Int, val pixelBuffer: BooleanArray) { constructor(columns: Int, rows: Int) : this(columns, rows, BooleanArray(columns * rows)) init { resetBuffer() } fun resetBuffer() { synchronized(this) { for (i in 0..pixelBuffer.lastIndex) { pixelBuffer[i] = false } } } fun set(x: Int, y: Int, isOn: Boolean) { // Don't draw out of bounds if (x < 0 || x >= columns || y < 0 || y >= rows) { return } synchronized(this) { val index = getIndex(x, y) pixelBuffer[index] = isOn } } fun get(x: Int, y: Int): Boolean { if (x < 0 || x >= columns || y < 0 || y >= rows) { return false } val index = getIndex(x, y) return pixelBuffer[index] } fun getIndex(column: Int, row: Int): Int { return column + (row * columns) } fun forEachPixel(closure: (Int, Int, Boolean) -> Unit) { synchronized (this) { for (row in 0..(rows - 1)) { for (column in 0..(columns - 1)) { val index = getIndex(column, row) val isOn = pixelBuffer[index] closure.invoke(column, row, isOn) } } } } }
apache-2.0
7e856ba885b4baed301909a473e882e0
17.723077
59
0.59375
2.841121
false
false
false
false
arturbosch/detekt
detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/UnusedImportsSpec.kt
1
18924
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment import io.gitlab.arturbosch.detekt.test.lintWithContext import org.assertj.core.api.Assertions.assertThat import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class UnusedImportsSpec : Spek({ setupKotlinEnvironment() val env: KotlinCoreEnvironment by memoized() val subject by memoized { UnusedImports(Config.empty) } describe("UnusedImports rule") { it("does not report infix operators") { val main = """ import tasks.success fun task(f: () -> Unit) = 1 fun main() { task { } success { } } """ val additional = """ package tasks infix fun Int.success(f: () -> Unit) {} """ assertThat(subject.lintWithContext(env, main, additional)).isEmpty() } it("does not report imports in documentation") { val main = """ import tasks.success import tasks.failure import tasks.undefined fun task(f: () -> Unit) = 1 /** * Reference to [failure] */ class Test { /** Reference to [undefined]*/ fun main() { task { } success { } } } """ val additional = """ package tasks infix fun Int.success(f: () -> Unit) {} infix fun Int.failure(f: () -> Unit) {} infix fun Int.undefined(f: () -> Unit) {} """ assertThat(subject.lintWithContext(env, main, additional)).isEmpty() } it("should ignore import for link") { val main = """ import tasks.success import tasks.failure import tasks.undefined fun task(f: () -> Unit) = 1 /** * Reference [undefined][failure] */ fun main() { task { } success { } } """ val additional = """ package tasks infix fun Int.success(f: () -> Unit) {} infix fun Int.failure(f: () -> Unit) {} infix fun Int.undefined(f: () -> Unit) {} """ val lint = subject.lintWithContext(env, main, additional) with(lint) { assertThat(this).hasSize(1) assertThat(this[0].entity.signature).endsWith("import tasks.undefined") } } it("reports imports from the current package") { val main = """ package test import test.SomeClass val a: SomeClass? = null """ val additional = """ package test class SomeClass """ val lint = subject.lintWithContext(env, main, additional) with(lint) { assertThat(this).hasSize(1) assertThat(this[0].entity.signature).endsWith("import test.SomeClass") } } it("does not report KDoc references with method calls") { val main = """ package com.example import android.text.TextWatcher class Test { /** * [TextWatcher.beforeTextChanged] */ fun test() { TODO() } } """ val additional = """ package android.text class TextWatcher { fun beforeTextChanged() {} } """ assertThat(subject.lintWithContext(env, main, additional)).isEmpty() } it("reports imports with different cases") { val main = """ import p.a import p.B6 // positive import p.B as B12 // positive import p2.B as B2 import p.C import escaped.`when` import escaped.`foo` // positive import p.D /** reference to [D] */ fun main() { println(a()) C.call() fn(B2.NAME) `when`() } fun fn(s: String) {} """ val p = """ package p fun a() {} class B6 class B object C { fun call() {} } class D """ val p2 = """ package p2 object B { const val NAME = "" } """ val escaped = """ package escaped fun `when`() {} fun `foo`() {} """ val lint = subject.lintWithContext(env, main, p, p2, escaped) with(lint) { assertThat(this).hasSize(3) assertThat(this[0].entity.signature).contains("import p.B6") assertThat(this[1].entity.signature).contains("import p.B as B12") assertThat(this[2].entity.signature).contains("import escaped.`foo`") } } it("does not report imports in same package when inner") { val main = """ package test import test.Outer.Inner open class Something<T> class Foo : Something<Inner>() """ val additional = """ package test class Outer { class Inner } """ val lint = subject.lintWithContext(env, main, additional) with(lint) { assertThat(this).isEmpty() } } it("does not report KDoc @see annotation linking to class") { val main = """ import tasks.success /** * Do something. * @see success */ fun doSomething() """ val additional = """ package tasks fun success() {} """ assertThat(subject.lintWithContext(env, main, additional)).isEmpty() } it("does not report KDoc @see annotation linking to class with description") { val main = """ import tasks.success /** * Do something. * @see success something */ fun doSomething() {} """ val additional = """ package tasks fun success() {} """ assertThat(subject.lintWithContext(env, main, additional)).isEmpty() } it("reports KDoc @see annotation that does not link to class") { val main = """ import tasks.success /** * Do something. * @see something */ fun doSomething() {} """ val additional = """ package tasks fun success() {} """ assertThat(subject.lintWithContext(env, main, additional)).hasSize(1) } it("reports KDoc @see annotation that links after description") { val main = """ import tasks.success /** * Do something. * @see something success */ fun doSomething() {} """ val additional = """ package tasks fun success() {} """ assertThat(subject.lintWithContext(env, main, additional)).hasSize(1) } it("does not report imports in KDoc") { val main = """ import tasks.success // here import tasks.undefined // and here /** * Do something. * @throws success when ... * @exception success when ... * @see undefined * @sample success when ... */ fun doSomething() {} """ val additional = """ package tasks fun success() {} fun undefined() {} """ assertThat(subject.lintWithContext(env, main, additional)).isEmpty() } it("should not report import alias as unused when the alias is used") { val main = """ import test.forEach as foreach fun foo() = listOf().iterator().foreach {} """ val additional = """ package test fun Iterator<Int>.forEach(f: () -> Unit) {} """ assertThat(subject.lintWithContext(env, main, additional)).isEmpty() } it("should not report used alias even when import is from same package") { val main = """ package com.example import com.example.foo as myFoo // from same package but with alias, check alias usage import com.example.other.foo as otherFoo // not from package with used alias fun f(): Boolean { return myFoo() == otherFoo() } """ val additional1 = """ package com.example fun foo() = 1 """ val additional2 = """ package com.example.other fun foo() = 1 """ assertThat(subject.lintWithContext(env, main, additional1, additional2)).isEmpty() } it("should not report import of provideDelegate operator overload - #1608") { val main = """ import org.gradle.kotlin.dsl.Foo import org.gradle.kotlin.dsl.provideDelegate // this line specifically should not be reported class DumpVersionProperties { private val dumpVersionProperties by Foo() } """ val additional = """ package org.gradle.kotlin.dsl import kotlin.reflect.KProperty class Foo operator fun <T> Foo.provideDelegate( thisRef: T, prop: KProperty<*> ) = lazy { "" } """ assertThat(subject.lintWithContext(env, main, additional)).isEmpty() } it("should not report import of componentN operator") { val main = """ import com.example.MyClass.component1 import com.example.MyClass.component2 import com.example.MyClass.component543 fun test() { val (a, b) = MyClass(1, 2) } """ val additional = """ package com.example data class MyClass(val a: Int, val b: Int) """ assertThat(subject.lintWithContext(env, main, additional)).isEmpty() } it("should report import of identifiers with component in the name") { val main = """ import com.example.TestComponent import com.example.component1.Unused import com.example.components import com.example.component1AndSomethingElse fun test() { println("Testing") } """ val additional1 = """ package com.example class TestComponent fun components() {} fun component1AndSomethingElse() {} """ val additional2 = """ package com.example.component1 class Unused """ val lint = subject.lintWithContext(env, main, additional1, additional2) with(lint) { assertThat(this).hasSize(4) assertThat(this[0].entity.signature).endsWith("import com.example.TestComponent") assertThat(this[1].entity.signature).endsWith("import com.example.component1.Unused") assertThat(this[2].entity.signature).endsWith("import com.example.components") assertThat(this[3].entity.signature).endsWith("import com.example.component1AndSomethingElse") } } it("reports when same name identifiers are imported and used") { val mainFile = """ import foo.test import bar.test fun main() { test(1) } """ val additionalFile1 = """ package foo fun test(i: Int) {} """ val additionalFile2 = """ package bar fun test(s: String) {} """ val findings = subject.lintWithContext(env, mainFile, additionalFile1, additionalFile2) assertThat(findings).hasSize(1) assertThat(findings[0].entity.signature).endsWith("import bar.test") } it("does not report when used as a type") { val code = """ import java.util.HashMap fun doesNothing(thing: HashMap<String, String>) { } """ val findings = subject.lintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when used in a class literal expression") { val code = """ import java.util.HashMap import kotlin.reflect.KClass annotation class Ann(val value: KClass<*>) @Ann(HashMap::class) fun foo() {} """ val findings = subject.lintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when used as a constructor call") { val mainFile = """ import x.y.z.Foo val foo = Foo() """ val additionalFile = """ package x.y.z class Foo """ val findings = subject.lintWithContext(env, mainFile, additionalFile) assertThat(findings).isEmpty() } it("does not report when used as a annotation") { val mainFile = """ import x.y.z.Ann @Ann fun foo() {} """ val additionalFile = """ package x.y.z annotation class Ann """ val findings = subject.lintWithContext(env, mainFile, additionalFile) assertThat(findings).isEmpty() } it("does not report companion object") { val mainFile = """ import x.y.z.Foo val x = Foo """ val additionalFile = """ package x.y.z class Foo { companion object } """ val findings = subject.lintWithContext(env, mainFile, additionalFile) assertThat(findings).isEmpty() } it("does not report companion object that calls function") { val mainFile = """ import x.y.z.Foo val x = Foo.create() """ val additionalFile = """ package x.y.z class Foo { companion object { fun create(): Foo = Foo() } } """ val findings = subject.lintWithContext(env, mainFile, additionalFile) assertThat(findings).isEmpty() } it("does not report companion object that references variable") { val mainFile = """ import x.y.z.Foo val x = Foo.BAR """ val additionalFile = """ package x.y.z class Foo { companion object { const val BAR = 1 } } """ val findings = subject.lintWithContext(env, mainFile, additionalFile) assertThat(findings).isEmpty() } it("does not report static import") { val mainFile = """ import x.y.z.FetchType val x = FetchType.LAZY """ val additionalFile = """ package x.y.z enum class FetchType { LAZY } """ assertThat(subject.lintWithContext(env, mainFile, additionalFile)).isEmpty() } it("does not report annotations used as attributes - #3246") { val mainFile = """ import x.y.z.AnnotationA import x.y.z.AnnotationB class SomeClass { @AnnotationB(attribute = AnnotationA()) val someProp: Int = 42 } """ val additionalFile = """ package x.y.z annotation class AnnotationA annotation class AnnotationB(val attribute: AnnotationA) """ assertThat(subject.lintWithContext(env, mainFile, additionalFile)).isEmpty() } } })
apache-2.0
f3ec86dc01538cb06b97e7402d627915
31.020305
110
0.431621
5.810255
false
false
false
false
rcgroot/open-gpstracker-ng
studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/databinding/CommonBindingAdapters.kt
1
4753
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) 2016 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker 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. * * OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.ng.features.databinding import androidx.databinding.BindingAdapter import android.graphics.Bitmap import android.graphics.Rect import android.graphics.drawable.Drawable import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat import androidx.core.content.res.ResourcesCompat import android.view.TouchDelegate import android.view.View import android.webkit.WebView import android.widget.Button import android.widget.ImageView import nl.sogeti.android.opengpstrack.ng.features.R open class CommonBindingAdapters { @BindingAdapter("hitPadding") fun setHitRectPadding(view: View, padding: Float) { val parent = view.parent if (parent is View) { parent.post { val delta = padding.toInt() val hitRect = Rect() view.getHitRect(hitRect) hitRect.set(hitRect.left - delta, hitRect.top - delta, hitRect.right + delta, hitRect.bottom + delta) parent.touchDelegate = TouchDelegate(hitRect, view) } } } @BindingAdapter("bitmap") fun setBitmap(view: ImageView, bitmap: Bitmap?) { view.setImageBitmap(bitmap) } @BindingAdapter("leftDrawable") fun setLeftDrawable(button: Button, drawable: Drawable?) { val top = button.compoundDrawables[1] val right = button.compoundDrawables[2] val bottom = button.compoundDrawables[3] drawable?.setTint(ResourcesCompat.getColor(button.resources, R.color.icons, button.context.theme)) button.setCompoundDrawablesWithIntrinsicBounds(drawable, top, right, bottom) } @BindingAdapter("srcCompat") fun setImageSource(imageView: ImageView, attributeValue: Int?) { val resource = attributeValue ?: return val tint = (imageView.tag as? Map<*, *>)?.get("tint") as? Int if (tint != null) { val drawable = VectorDrawableCompat.create(imageView.resources, resource, imageView.context.theme) ?: return drawable.setTint(tint) imageView.setImageDrawable(drawable) } else { imageView.setImageResource(resource) } } @BindingAdapter("url") fun setUrl(webView: WebView, url: String) { webView.loadUrl(url) } // @BindingAdapter("bind:selection", "bind:selectionAttrChanged", requireAll = false) // fun setSelected(spinner: AppCompatSpinner, selection: Int, selectionAttrChanged: InverseBindingListener) { // if (spinner.selectedItemPosition != selection) { // spinner.setSelection(selection) // } // spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { // override fun onNothingSelected(p0: AdapterView<*>?) { // selectionAttrChanged.onChange() // } // // override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { // selectionAttrChanged.onChange() // } // } // } // // @InverseBindingAdapter(attribute = "bind:selection", event = "bind:selectionAttrChanged") // fun getSelectedValue(spinner: AppCompatSpinner): Int { // return spinner.selectedItemPosition // } }
gpl-3.0
fd486f592c74ce85aa9c971b1da566d6
41.061947
117
0.633915
4.692004
false
false
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/editor/EditorResults.kt
1
6652
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.tools.editor import javafx.beans.property.SimpleBooleanProperty import javafx.scene.control.ToolBar import javafx.scene.input.DataFormat import javafx.scene.input.TransferMode import javafx.scene.layout.BorderPane import javafx.scene.layout.VBox import uk.co.nickthecoder.paratask.ParaTaskApp import uk.co.nickthecoder.paratask.gui.CompoundDropHelper import uk.co.nickthecoder.paratask.gui.DropFiles import uk.co.nickthecoder.paratask.gui.ShortcutHelper import uk.co.nickthecoder.paratask.gui.SimpleDropHelper import uk.co.nickthecoder.paratask.project.AbstractResults import uk.co.nickthecoder.paratask.project.ParataskActions import uk.co.nickthecoder.paratask.project.ResultsTab import uk.co.nickthecoder.paratask.project.ToolPane import uk.co.nickthecoder.tedi.BetterUndoRedo import uk.co.nickthecoder.tedi.TediArea import uk.co.nickthecoder.tedi.ui.FindBar import uk.co.nickthecoder.tedi.ui.RemoveHiddenChildren import uk.co.nickthecoder.tedi.ui.ReplaceBar import uk.co.nickthecoder.tedi.ui.TextInputControlMatcher import java.io.File class EditorResults( override val tool: EditorTool, val file: File?) : AbstractResults(tool, file?.name ?: "New File", canClose = true) { val toolBar = ToolBar() val tediArea = TediArea() private val matcher = TextInputControlMatcher(tediArea) private val findBar = FindBar(matcher) private val replaceBar = ReplaceBar(matcher) private val borderPane = BorderPane() private val searchAndReplace = VBox() private val toggleFind = findBar.createToggleButton() private val toggleReplace = replaceBar.createToggleButton() override val node = borderPane val dirtyProperty = SimpleBooleanProperty() var dirty: Boolean get() = dirtyProperty.get() set(value) { dirtyProperty.set(value) label = (if (value) "*" else "") + (file?.name ?: "New File") } val textDropHelper = SimpleDropHelper<String>(DataFormat.PLAIN_TEXT, arrayOf(TransferMode.COPY)) { _, text -> insertText(text) } val filesDropHelper = DropFiles(arrayOf(TransferMode.COPY)) { _, files -> val text = files.map { it.path }.joinToString(separator = "\n") insertText(text) } val compoundDropHelper = CompoundDropHelper(filesDropHelper, textDropHelper) init { RemoveHiddenChildren(searchAndReplace.children) with(searchAndReplace) { children.addAll(findBar.toolBar, replaceBar.toolBar) } matcher.inUse = false with(borderPane) { center = tediArea top = searchAndReplace } with(tediArea) { undoRedo = BetterUndoRedo(tediArea) displayLineNumbers = true styleClass.add("code") } compoundDropHelper.applyTo(tediArea) val shortcuts = ShortcutHelper("EditorTool", node) shortcuts.add(ParataskActions.EDIT_CUT) { onCut() } shortcuts.add(ParataskActions.EDIT_COPY) { onCopy() } shortcuts.add(ParataskActions.EDIT_PASTE) { onPaste() } shortcuts.add(ParataskActions.EDIT_FIND) { matcher.inUse = true } shortcuts.add(ParataskActions.EDIT_REPLACE) { onReplace() } shortcuts.add(ParataskActions.ESCAPE) { onEscape() } toolBar.styleClass.add("bottom") with(toolBar.items) { val save = ParataskActions.FILE_SAVE.createButton(shortcuts) { onSave() } val undo = ParataskActions.EDIT_UNDO.createButton(shortcuts) { onUndo() } val redo = ParataskActions.EDIT_REDO.createButton(shortcuts) { onRedo() } undo.disableProperty().bind(tediArea.undoRedo.undoableProperty().not()) redo.disableProperty().bind(tediArea.undoRedo.redoableProperty().not()) save.disableProperty().bind(dirtyProperty.not()) addAll(save, undo, redo, toggleFind, toggleReplace) } file?.let { load(it) } tediArea.textProperty().addListener { _, _, _ -> dirty = true } } constructor(tool: EditorTool, text: String) : this(tool, null) { load(text) } override fun selected() { super.selected() tool.toolPane?.halfTab?.toolBars?.left = toolBar file?.path?.let { tool.longTitle = "Editor $it" } } override fun focus() { ParaTaskApp.logFocus("EditorResults.focus. tediArea.requestFocus()") tediArea.requestFocus() } override fun attached(resultsTab: ResultsTab, toolPane: ToolPane) { super.attached(resultsTab, toolPane) tool.goToLineP.value?.let { tediArea.positionCaret(tediArea.positionOfLine(it)) } if (tool.findTextP.value != "") { matcher.find = tool.findTextP.value matcher.matchCase = tool.matchCaseP.value == true matcher.matchRegex = tool.useRegexP.value == true matcher.inUse = true matcher.startFind() } } override fun closed() { super.closed() tool.filesP.remove(file) } fun load(text: String) { tediArea.text = text } fun load(file: File) { load(file.readText()) tediArea.undoRedo.clear() dirty = false } fun onSave() { dirty = false file?.writeText(tediArea.text) } fun onUndo() { tediArea.undoRedo.undo() } fun onRedo() { tediArea.undoRedo.redo() } fun onCopy() { tediArea.copy() } fun onPaste() { tediArea.paste() } fun onCut() { tediArea.cut() } fun onReplace() { val wasInUse = matcher.inUse replaceBar.toolBar.isVisible = true if (wasInUse) { replaceBar.requestFocus() } } fun onEscape() { matcher.inUse = false } fun insertText(text: String) { tediArea.insertText(tediArea.caretPosition, text) } }
gpl-3.0
d56b8608f6a3a0fa26b1e0d0ed70f853
28.696429
113
0.663109
4.118885
false
false
false
false
06needhamt/Neuroph-Intellij-Plugin
neuroph-plugin/src/com/thomas/needham/neurophidea/forms/weights/SaveNetworkWeightsButtonActionListener.kt
1
3467
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham 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.thomas.needham.neurophidea.forms.weights import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.ui.Messages import com.thomas.needham.neurophidea.actions.InitialisationAction import org.neuroph.core.NeuralNetwork import java.awt.event.ActionEvent import java.awt.event.ActionListener import java.io.* /** * Created by thoma on 14/06/2016. */ class SaveNetworkWeightsButtonActionListener : ActionListener { var formInstance: NetworkWeightsForm? = null var network: NeuralNetwork? = null companion object Data { val properties = PropertiesComponent.getInstance() var path = "" val getNetwork: (String) -> NeuralNetwork? = { path -> try { val file = File(path) val fis = FileInputStream(file) val ois = ObjectInputStream(fis) ois.readObject() as NeuralNetwork? } catch (ioe: IOException) { ioe.printStackTrace(System.err) Messages.showErrorDialog(InitialisationAction.project, "Error Loading Network From File: ${path}", "Error") null } catch (fnfe: FileNotFoundException) { fnfe.printStackTrace(System.err) Messages.showErrorDialog(InitialisationAction.project, "No Network found in: ${path}", "Error") null } } } override fun actionPerformed(e: ActionEvent?) { path = formInstance?.path!! network = formInstance?.network if (network == null) network = getNetwork(path) val setWeights: () -> Boolean = { try { for (i in 0..formInstance?.weights?.size!! - 1) { for (j in 0..formInstance?.weights!![i].size - 1) { formInstance?.weights!![i][j] = formInstance?.fields!![i][j].text.toDouble() } } for (i in 0..formInstance?.network?.layers?.size!! - 1) { for (j in 0..formInstance?.network?.layers!![i]?.neurons?.size!! - 1) { formInstance?.network?.layers!![i]?.neurons!![j]?.weightsVector!![0].setValue(formInstance?.weights!![i][j]) } } network?.save(path) Messages.showErrorDialog(InitialisationAction.project, "Network Weights Successfully Updated", "Success") true } catch (nfe: NumberFormatException) { nfe.printStackTrace(System.err) Messages.showErrorDialog(InitialisationAction.project, "Invalid Network Weight Specified", "Error") false } } if (!setWeights()) { Messages.showErrorDialog(InitialisationAction.project, "Error Updating Network Weights", "Error") } } }
mit
f4afadde6cf073ea358f5b3f01b405ec
36.290323
114
0.732333
3.989643
false
false
false
false
akihyro/orika-spring-boot-starter
examples/simple-kotlin/src/main/kotlin/example/Application.kt
1
875
package example import ma.glasnost.orika.MapperFacade import org.springframework.boot.ApplicationArguments import org.springframework.boot.ApplicationRunner import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class Application(private val orikaMapperFacade: MapperFacade) : ApplicationRunner { override fun run(args: ApplicationArguments) { // Maps from PersonSource to PersonDestination val src = PersonSource("John", "Smith", 23) println(src) // => "PersonSource(firstName=John, lastName=Smith, age=23)" val dest = orikaMapperFacade.map(src, PersonDestination::class.java) println(dest) // => "PersonDestination(givenName=John, sirName=Smith, age=23)" } } fun main(vararg args: String) { runApplication<Application>(*args) }
apache-2.0
fe206cd69c59b17c2a5eab35b2e83806
32.653846
87
0.756571
4.247573
false
false
false
false
candalo/rss-reader
app/src/main/java/com/github/rssreader/base/data/di/BaseModule.kt
1
834
package com.github.rssreader.base.data.di import com.github.rssreader.base.domain.Thread import dagger.Module import dagger.Provides import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Named @Module class BaseModule { companion object { const val MAIN_THREAD_INJECTION_ID = "mainThread" const val NEW_THREAD_INJECTION_ID = "newThread" } @Provides @Named(MAIN_THREAD_INJECTION_ID) fun provideMainThread(): Thread = ThreadImpl(AndroidSchedulers.mainThread()) @Provides @Named(NEW_THREAD_INJECTION_ID) fun provideNewThread(): Thread = ThreadImpl(Schedulers.newThread()) inner class ThreadImpl(val thread: Scheduler) : Thread { override fun get(): Scheduler = thread } }
mit
dd3f7e823b47dcd0e6e66df9bdf83b5d
26.8
80
0.741007
4.212121
false
false
false
false
ArdentDiscord/ArdentKotlin
src/main/kotlin/commands/fun/FunCommands.kt
1
8593
package commands.`fun` import com.mb3364.twitch.api.Twitch import com.mb3364.twitch.api.handlers.ChannelResponseHandler import com.mb3364.twitch.api.handlers.StreamResponseHandler import com.mb3364.twitch.api.models.Channel import com.mb3364.twitch.api.models.Stream import events.Category import events.Command import main.config import net.dv8tion.jda.api.events.message.MessageReceivedEvent import org.json.JSONObject import org.jsoup.Jsoup import translation.tr import utils.discord.embed import utils.discord.send import utils.functionality.* import utils.web.EightBallResult import utils.web.UrbanDictionarySearch import java.awt.Color import java.net.URLEncoder class Meme : Command(Category.FUN, "gif", "get a random meme from giphy", "meme", ratelimit = 5) { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { event.channel.send(JSONObject(Jsoup.connect("https://api.giphy.com/v1/gifs/random").data("api_key", config.getValue("giphy")) .ignoreContentType(true).get().body().text()).getJSONObject("data").getString("image_url")) } } class UrbanDictionary : Command(Category.FUN, "urban", "get search results for your favorite words from urban dictionary", "ud") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { if (arguments.size == 0) event.channel.send("${Emoji.HEAVY_MULTIPLICATION_X} " + "You gotta include a search term".tr(event)) else { val term = arguments.concat() val search = gson.fromJson(Jsoup.connect("http://api.urbandictionary.com/v0/define?term=${URLEncoder.encode(term)}").ignoreContentType(true).get() .body().text(), UrbanDictionarySearch::class.java) if (search.list.isEmpty()) event.channel.send("There were no results for this term :(".tr(event)) else { val result = search.list[0] event.channel.send(event.member!!.embed("Urban Dictionary Definition for {0}".tr(event, term), event.textChannel) .setThumbnail("https://i.gyazo.com/6a40e32928743e68e9006396ee7c2a14.jpg") .setColor(Color.decode("#00B7BE")) .addField("Definition".tr(event), result.definition.shortenIf(1024), true) .addField("Example".tr(event), result.example.shortenIf(1024), true) .addField("Thumbs Up".tr(event), result.thumbs_up.toString(), true) .addField("Thumbs Down".tr(event), result.thumbs_down.toString(), true) .addField("Author".tr(event), result.author, true) .addField("Permalink".tr(event), result.permalink, true) ) } } } } class UnixFortune : Command(Category.FUN, "unixfortune", "in the mood for a unix fortune? us too", "fortune") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { event.channel.send(Jsoup.connect("http://motd.ambians.com/quotes.php/name/linux_fortunes_random/toc_id/1-1-1") .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6") .get().getElementsByTag("pre")[0].text()) } } class EightBall : Command(Category.FUN, "8ball", "ask the magical 8 ball your future... or something, idfk") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { if (arguments.size == 0) event.channel.send("${Emoji.HEAVY_MULTIPLICATION_X} " + "How dare you try to ask the 8-ball an empty question??!!".tr(event)) else { try { event.channel.send(gson.fromJson(Jsoup.connect("https://8ball.delegator.com/magic/JSON/${arguments.concat().encode()}") .ignoreContentType(true) .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6") .get().body().text(), EightBallResult::class.java).magic.answer) } catch (e: Exception) { event.channel.send("Type a valid question, you must!".tr(event.guild)) } } } } class FML : Command(Category.FUN, "fml", "someone else has had a bad day.") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { event.channel.send(Jsoup.connect("http://www.fmylife.com/random") .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6") .ignoreContentType(true).get() .getElementsByTag("p")[0].getElementsByTag("a")[0].allElements[0].text()) } } class IsStreaming : Command(Category.FUN, "streaming", "check whether someone is streaming on Twitch and see basic information") { val twitch = Twitch() init { twitch.clientId = config.getValue("twitch") } override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { if (arguments.size == 0) event.channel.send("Please include the name of a channel - **Example**: `/streaming ardentdiscord`".tr(event)) else { val ch = arguments.concat() twitch.channels().get(ch, object : ChannelResponseHandler { override fun onSuccess(twitchChannel: Channel) { twitch.streams().get(twitchChannel.name, object : StreamResponseHandler { override fun onSuccess(stream: Stream?) { val embed = event.member!!.embed("{0} on Twitch".tr(event, twitchChannel.name), event.textChannel) .addField("Display Name".tr(event), twitchChannel.displayName, true) .addField("Twitch Link".tr(event), "[Click Here]({0})".tr(event, twitchChannel.url), true) if (stream != null && stream.isOnline) { embed.setColor(Color.GREEN) .addField("Currently Streaming".tr(event), "yes".tr(event), true) .addField("Streaming Game".tr(event), stream.game, true) .addField("Viewers".tr(event), stream.viewers.format(), true) .addField("Average FPS".tr(event), stream.averageFps.toString(), true) embed.setImage(stream.preview.medium) } else { embed.setColor(Color.RED) .addField("Currently Streaming".tr(event), "no".tr(event), true) if (twitchChannel.videoBanner == null) embed.setThumbnail(twitchChannel.logo) else embed.setThumbnail(twitchChannel.videoBanner) } embed.addField("Views".tr(event), twitchChannel.views.format(), true) .addField("Followers".tr(event), twitchChannel.followers.format(), true) .addField("Creation Date".tr(event), twitchChannel.createdAt.toGMTString(), true) .addField("Is Partnered?".tr(event), twitchChannel.isPartner.toString(), true) .addField("Mature Content?".tr(event), twitchChannel.isMature.toString(), true) .addField("Language".tr(event), twitchChannel.language, true) event.channel.send(embed) } override fun onFailure(failure: Throwable) { event.channel.send("Unable to retrieve channel data. **Reason**: {0}".tr(event, failure.localizedMessage)) } override fun onFailure(p0: Int, p1: String?, p2: String?) { onFailure(Exception("Unknown API Error".tr(event))) } }) } override fun onFailure(failure: Throwable) { event.channel.send("Unable to retrieve channel data. **Reason**: {0}".tr(event, failure.localizedMessage)) } override fun onFailure(p0: Int, p1: String?, p2: String?) { onFailure(Exception("Unknown API Error".tr(event))) } }) } } }
apache-2.0
fa46ffb24ad5ec3f96c2286e09a5872f
56.293333
158
0.584778
4.315922
false
false
false
false
karollewandowski/aem-intellij-plugin
src/test/kotlin/co/nums/intellij/aem/htl/editor/comments/HtlLineUncommentTest.kt
1
5350
package co.nums.intellij.aem.htl.editor.comments import co.nums.intellij.aem.htl.DOLLAR import com.intellij.openapi.actionSystem.IdeActions class HtlLineUncommentTest : HtlCommenterTestBase() { override val commentType = IdeActions.ACTION_COMMENT_LINE fun testSingleLineUncommentAtBeginningOfLine() = doCommenterTest(""" <h2> <caret> <!--/*$DOLLAR{properties.jcr:title @ context='text'}*/--> </h2> """, """ <h2> $DOLLAR{properties.jcr:title @ context='text'} </h2> """) fun testSingleLineUncommentInMiddleOfLine() = doCommenterTest(""" <h2> <!--/*$DOLLAR{properties.jcr:title<caret> @ context='text'}*/--> </h2> """, """ <h2> $DOLLAR{properties.jcr:title @ context='text'} </h2> """) fun testSingleLineUncommentAtEndOfLine() = doCommenterTest(""" <h2> <!--/*$DOLLAR{properties.jcr:title @ context='text'}*/--><caret> </h2> """, """ <h2> $DOLLAR{properties.jcr:title @ context='text'} </h2> """) fun testSingleLineUncommentContainingSingleLineComment() = doCommenterTest(""" <h2> $DOLLAR{properties.jcr:title @ context='text'} </h2> <div> <div class="heading"> <!--/*&lt;!&ndash;/*<span>$DOLLAR{'test'}<caret></span>*/&ndash;&gt;$DOLLAR{properties.heading @ context='html'}*/--> </div> <div class="content">$DOLLAR{properties.content @ context='html'}</div> </div> """, """ <h2> $DOLLAR{properties.jcr:title @ context='text'} </h2> <div> <div class="heading"> <!--/*<span>$DOLLAR{'test'}</span>*/-->$DOLLAR{properties.heading @ context='html'} </div> <div class="content">$DOLLAR{properties.content @ context='html'}</div> </div> """) fun testMultiLineUncommentAtBeginningOfFile() = doCommenterTest(""" <selection><!--/*<h2>*/--> <!--/*$DOLLAR{properties.jcr:title @ context='text'}*/--> <!--/*</h2>*/--></selection> <div> <div class="heading">$DOLLAR{properties.heading @ context='html'}</div> <div class="content">$DOLLAR{properties.content @ context='html'}</div> </div> """, """ <h2> $DOLLAR{properties.jcr:title @ context='text'} </h2> <div> <div class="heading">$DOLLAR{properties.heading @ context='html'}</div> <div class="content">$DOLLAR{properties.content @ context='html'}</div> </div> """) fun testMultiLineUncommentInMiddleOfFile() = doCommenterTest(""" <h2> $DOLLAR{properties.jcr:title @ context='text'} </h2> <div> <selection><!--/*<div class="heading">$DOLLAR{properties.heading @ context='html'}</div>*/--> <!--/*<div class="content">$DOLLAR{properties.content @ context='html'}</div>*/--></selection> </div> """, """ <h2> $DOLLAR{properties.jcr:title @ context='text'} </h2> <div> <div class="heading">$DOLLAR{properties.heading @ context='html'}</div> <div class="content">$DOLLAR{properties.content @ context='html'}</div> </div> """) fun testMultiLineUncommentAtEndOfFile() = doCommenterTest(""" <h2> $DOLLAR{properties.jcr:title @ context='text'} </h2> <selection><!--/*<div>*/--> <!--/*<div class="heading">$DOLLAR{properties.heading @ context='html'}</div>*/--> <!--/*<div class="content">$DOLLAR{properties.content @ context='html'}</div>*/--> <!--/*</div>*/--></selection> """, """ <h2> $DOLLAR{properties.jcr:title @ context='text'} </h2> <div> <div class="heading">$DOLLAR{properties.heading @ context='html'}</div> <div class="content">$DOLLAR{properties.content @ context='html'}</div> </div> """) fun testMultiLineUncommentForEntireFile() = doCommenterTest(""" <selection><!--/*<h2>*/--> <!--/*$DOLLAR{properties.jcr:title @ context='text'}*/--> <!--/*</h2>*/--> <!--/*<div>*/--> <!--/*<div class="heading">$DOLLAR{properties.heading @ context='html'}</div>*/--> <!--/*<div class="content">$DOLLAR{properties.content @ context='html'}</div>*/--> <!--/*</div>*/--></selection> """, """ <h2> $DOLLAR{properties.jcr:title @ context='text'} </h2> <div> <div class="heading">$DOLLAR{properties.heading @ context='html'}</div> <div class="content">$DOLLAR{properties.content @ context='html'}</div> </div> """) }
gpl-3.0
0d0421f7e41922e0aee134782d310bd9
38.925373
137
0.472336
4.290297
false
true
false
false
SapuSeven/BetterUntis
app/src/main/java/com/sapuseven/untis/models/untis/masterdata/AbsenceReason.kt
1
1380
package com.sapuseven.untis.models.untis.masterdata import android.content.ContentValues import android.database.Cursor import com.sapuseven.untis.annotations.Table import com.sapuseven.untis.annotations.TableColumn import com.sapuseven.untis.data.databases.TABLE_NAME_ABSENCE_REASONS import com.sapuseven.untis.interfaces.TableModel import kotlinx.serialization.Serializable @Serializable @Table(TABLE_NAME_ABSENCE_REASONS) data class AbsenceReason( @field:TableColumn("INTEGER NOT NULL") val id: Int, @field:TableColumn("VARCHAR(255) NOT NULL") val name: String, @field:TableColumn("VARCHAR(255) NOT NULL") val longName: String, @field:TableColumn("BOOLEAN NOT NULL") val active: Boolean ) : TableModel { companion object { const val TABLE_NAME = TABLE_NAME_ABSENCE_REASONS } override val tableName = TABLE_NAME override val elementId = id override fun generateValues(): ContentValues { val values = ContentValues() values.put("id", id) values.put("name", name) values.put("longName", longName) values.put("active", active) return values } override fun parseCursor(cursor: Cursor): TableModel { return AbsenceReason( cursor.getInt(cursor.getColumnIndex("id")), cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("longName")), cursor.getInt(cursor.getColumnIndex("active")) != 0 ) } }
gpl-3.0
f894421a46945cad7945e4824c7e8545
29.666667
68
0.763043
3.739837
false
false
false
false
eugeis/ee-email
ee-email_des/src/main/kotlin/ee/email/EmailDesign.kt
1
727
package ee.email import ee.lang.Basic import ee.design.Comp import ee.design.Module import ee.lang.GT import ee.lang.n object Email : Comp({ artifact("ee-email").namespace("ee.email") }) { object Shared : Module() { object EmailAddress : Basic() { val address = prop { replaceable(false) } } object Forwarding : Basic() { val from = prop { type(EmailAddress) } val to = prop { type(n.List.GT(EmailAddress)) } } object EmailDomain : Basic() { val name = prop { replaceable(false) } val accounts = prop { type(n.List.GT(EmailAddress)) } val forwardings = prop { type(n.List.GT(Forwarding)) } } } }
apache-2.0
ba89c466012052f94e451cdb35c1301e
27
69
0.576341
3.887701
false
false
false
false
peterLaurence/TrekAdvisor
app/src/main/java/com/peterlaurence/trekme/ui/mapview/LandmarkLayer.kt
1
10318
package com.peterlaurence.trekme.ui.mapview import android.content.Context import android.graphics.drawable.Animatable2 import android.graphics.drawable.Drawable import android.view.View import com.peterlaurence.mapview.MapView import com.peterlaurence.mapview.ReferentialData import com.peterlaurence.mapview.ReferentialOwner import com.peterlaurence.mapview.api.* import com.peterlaurence.mapview.markers.* import com.peterlaurence.trekme.core.map.Map import com.peterlaurence.trekme.core.map.gson.Landmark import com.peterlaurence.trekme.core.map.maploader.MapLoader import com.peterlaurence.trekme.core.map.maploader.MapLoader.getLandmarksForMap import com.peterlaurence.trekme.ui.mapview.components.LandmarkCallout import com.peterlaurence.trekme.ui.mapview.components.LineView import com.peterlaurence.trekme.ui.mapview.components.MarkerGrab import com.peterlaurence.trekme.ui.mapview.components.MovableLandmark import com.peterlaurence.trekme.ui.tools.TouchMoveListener import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch class LandmarkLayer(val context: Context, private val coroutineScope: CoroutineScope) : MarkerTapListener, ReferentialOwner, CoroutineScope by coroutineScope { private lateinit var map: Map private lateinit var mapView: MapView private var visible = false private var lastKnownPosition: Pair<Double, Double> = Pair(0.0, 0.0) private val movableLandmarkList: MutableList<MovableLandmark> = mutableListOf() private var touchMoveListener: TouchMoveListener? = null override var referentialData = ReferentialData(false, 0f, 1f, 0.0, 0.0) set(value) { field = value movableLandmarkList.forEach { it.getLineView().referentialData = value touchMoveListener?.referentialData = value } } fun init(map: Map, mapView: MapView) { this.map = map setMapView(mapView) mapView.addReferentialOwner(this) if (map.areLandmarksDefined()) { drawLandmarks() } else { acquireThenDrawLandmarks() } } fun destroy() { mapView.removeReferentialOwner(this) } private fun CoroutineScope.acquireThenDrawLandmarks() = launch { getLandmarksForMap(map) drawLandmarks() } private fun drawLandmarks() { val landmarks = map.landmarkGson.landmarks for (landmark in landmarks) { val movableLandmark = MovableLandmark(context, true, landmark, newLineView()) if (map.projection == null) { movableLandmark.relativeX = landmark.lon movableLandmark.relativeY = landmark.lat } else { /* Take proj values, and fallback to lat-lon if they are null */ movableLandmark.relativeX = if (landmark.proj_x != null) landmark.proj_x else landmark.lon movableLandmark.relativeY = if (landmark.proj_y != null) landmark.proj_y else landmark.lat } movableLandmark.initStatic() /* Keep a reference on it */ movableLandmarkList.add(movableLandmark) mapView.addMarker(movableLandmark, movableLandmark.relativeX!!, movableLandmark.relativeY!!, -0.5f, -0.5f) } } fun addNewLandmark() { /* Calculate the relative coordinates of the center of the screen */ val x = mapView.scrollX + mapView.width / 2 - mapView.offsetX val y = mapView.scrollY + mapView.height / 2 - mapView.offsetY val coordinateTranslater = mapView.coordinateTranslater val relativeX = coordinateTranslater.translateAndScaleAbsoluteToRelativeX(x, mapView.scale) val relativeY = coordinateTranslater.translateAndScaleAbsoluteToRelativeY(y, mapView.scale) val movableLandmark: MovableLandmark /* Create a new landmark and add it to the map */ val newLandmark = Landmark("", 0.0, 0.0, 0.0, 0.0, "").newCoords(relativeX, relativeY) /* Create the corresponding view */ movableLandmark = MovableLandmark(context, false, newLandmark, newLineView()) movableLandmark.relativeX = relativeX movableLandmark.relativeY = relativeY movableLandmark.initRounded() /* Keep a reference on it */ movableLandmarkList.add(movableLandmark) map.addLandmark(newLandmark) /* Easily move the marker */ attachMarkerGrab(movableLandmark, mapView, map, context) mapView.addMarker(movableLandmark, relativeX, relativeY, -0.5f, -0.5f) } private fun attachMarkerGrab(movableLandmark: MovableLandmark, mapView: MapView, map: Map, context: Context) { /* Add a view as background, to move easily the marker */ val landmarkMoveCallback = TouchMoveListener.MoveCallback { mapView, view, x, y -> mapView.moveMarker(view, x, y) mapView.moveMarker(movableLandmark, x, y) movableLandmark.relativeX = x movableLandmark.relativeY = y movableLandmark.updateLine() } val markerGrab = MarkerGrab(context) val landmarkClickCallback = TouchMoveListener.ClickCallback { movableLandmark.morphToStaticForm() /* After the morph, remove the MarkerGrab */ markerGrab.morphOut(object : Animatable2.AnimationCallback() { override fun onAnimationEnd(drawable: Drawable) { super.onAnimationEnd(drawable) [email protected](markerGrab) } }) /* The view has been moved, update the associated model object */ val landmark = movableLandmark.getLandmark() if (movableLandmark.relativeX != null && movableLandmark.relativeY != null) { landmark.newCoords(movableLandmark.relativeX!!, movableLandmark.relativeY!!) } /* Save the changes on the markers.json file */ MapLoader.saveLandmarks(map) } touchMoveListener = TouchMoveListener(this.mapView, landmarkMoveCallback, landmarkClickCallback) touchMoveListener?.referentialData = referentialData markerGrab.setOnTouchListener(touchMoveListener) if (movableLandmark.relativeX != null && movableLandmark.relativeY != null) { this.mapView.addMarker(markerGrab, movableLandmark.relativeX!!, movableLandmark.relativeY!!, -0.5f, -0.5f) markerGrab.morphIn() } } /** * Return a copy of the private [visible] flag. */ fun isVisible() = visible private fun setMapView(mapView: MapView) { this.mapView = mapView } override fun onMarkerTap(view: View, x: Int, y: Int) { if (view is MovableLandmark && view.relativeX != null && view.relativeY != null) { /* Prepare the callout */ val landmarkCallout = LandmarkCallout(context) landmarkCallout.setMoveAction { view.morphToDynamicForm() /* Easily move the landmark */ attachMarkerGrab(view, mapView, map, context) /* Use a trick to bring the landmark to the foreground */ mapView.removeMarker(view) mapView.addMarker(view, view.relativeX!!, view.relativeY!!, -0.5f, -0.5f) /* Remove the callout */ mapView.removeCallout(landmarkCallout) } landmarkCallout.setDeleteAction { /* Remove the callout */ mapView.removeCallout(landmarkCallout) /* Delete the landmark */ mapView.removeMarker(view) movableLandmarkList.remove(view) view.deleteLine() val landmark = view.getLandmark() MapLoader.deleteLandmark(map, landmark) } val landmark = view.getLandmark() landmarkCallout.setSubTitle(landmark.lat, landmark.lon) mapView.addCallout(landmarkCallout, view.relativeX!!, view.relativeY!!, -0.5f, -1.2f) landmarkCallout.transitionIn() } } private fun Landmark.newCoords(relativeX: Double, relativeY: Double): Landmark = apply { if (map.projection == null) { lat = relativeY lon = relativeX } else { val wgs84Coords: DoubleArray? = map.projection!!.undoProjection(relativeX, relativeY) lat = wgs84Coords?.get(1) ?: 0.0 lon = wgs84Coords?.get(0) ?: 0.0 proj_x = relativeX proj_y = relativeY } } /** * Remove the associated [LineView] */ private fun MovableLandmark.deleteLine() { val lineView = getLineView() mapView.removeView(lineView) } private fun newLineView(): LineView { val lineView = LineView(context, referentialData, -0x3363d850) /* The index 1 is due to how MapView is designed and how we want landmarks to render (which * is above the map but beneath markers) */ mapView.addView(lineView, 1) return lineView } private fun MovableLandmark.updateLine() { val lineView = getLineView() if (relativeX != null && relativeY != null) { val coordinateTranslater = mapView.coordinateTranslater lineView.updateLine( coordinateTranslater.translateX(lastKnownPosition.first).toFloat(), coordinateTranslater.translateY(lastKnownPosition.second).toFloat(), coordinateTranslater.translateX(relativeX!!).toFloat(), coordinateTranslater.translateY(relativeY!!).toFloat()) } } /** * Called by the parent view ([MapViewFragment]). * All [LineView]s need to be updated. * * @param x the projected X coordinate, or longitude if there is no [Projection] * @param y the projected Y coordinate, or latitude if there is no [Projection] */ fun onPositionUpdate(x: Double, y: Double) { lastKnownPosition = Pair(x, y) updateAllLines() } private fun updateAllLines() { movableLandmarkList.forEach { it.updateLine() } } }
gpl-3.0
db23895b70c00047048c723fe9f966d1
37.793233
118
0.644408
4.583741
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/kotlin/types/EnumTypeConverter.kt
2
2959
package abi44_0_0.expo.modules.kotlin.types import abi44_0_0.com.facebook.react.bridge.Dynamic import abi44_0_0.expo.modules.kotlin.exception.IncompatibleArgTypeException import abi44_0_0.expo.modules.kotlin.toKType import kotlin.reflect.KClass import kotlin.reflect.full.createType import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.full.primaryConstructor class EnumTypeConverter( private val enumClass: KClass<Enum<*>>, isOptional: Boolean ) : TypeConverter<Enum<*>>(isOptional) { override fun convertNonOptional(value: Dynamic): Enum<*> { @Suppress("UNCHECKED_CAST") val enumConstants = requireNotNull(enumClass.java.enumConstants) { "Passed type is not an enum type." } require(enumConstants.isNotEmpty()) { "Passed enum type is empty." } val primaryConstructor = requireNotNull(enumClass.primaryConstructor) { "Cannot convert js value to enum without the primary constructor." } if (primaryConstructor.parameters.isEmpty()) { return convertEnumWithoutParameter(value, enumConstants) } else if (primaryConstructor.parameters.size == 1) { return convertEnumWithParameter( value, enumConstants, primaryConstructor.parameters.first().name!! ) } throw IncompatibleArgTypeException(value.type.toKType(), enumClass.createType()) } /** * If the primary constructor doesn't take any parameters, we treat the name of each enum as a value. * So the jsValue has to contain string. */ private fun convertEnumWithoutParameter( jsValue: Dynamic, enumConstants: Array<out Enum<*>> ): Enum<*> { val unwrappedJsValue = jsValue.asString() return requireNotNull( enumConstants.find { it.name == unwrappedJsValue } ) { "Couldn't convert ${jsValue.asString()} to ${enumClass.simpleName}." } } /** * If the primary constructor take one parameter, we treat this parameter as a enum value. * In that case, we handles two different types: Int and String. */ private fun convertEnumWithParameter( jsValue: Dynamic, enumConstants: Array<out Enum<*>>, parameterName: String ): Enum<*> { // To obtain the value of parameter, we have to find a property that is connected with this parameter. @Suppress("UNCHECKED_CAST") val parameterProperty = enumClass .declaredMemberProperties .find { it.name == parameterName } requireNotNull(parameterProperty) { "Cannot find a property for $parameterName parameter." } val parameterType = parameterProperty.returnType.classifier val jsUnwrapValue = if (parameterType == String::class) { jsValue.asString() } else { jsValue.asInt() } return requireNotNull( enumConstants.find { parameterProperty.get(it) == jsUnwrapValue } ) { "Couldn't convert ${jsValue.asString()} to ${enumClass.simpleName} where $parameterName is the enum parameter. " } } }
bsd-3-clause
05a77b8ae2c46ecd37d242de9790d38c
34.22619
122
0.709361
4.49696
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/intentions/FlattenUseStatementsIntention.kt
2
6759
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* /** * Flatten imports 1 depth * * ``` * use a::{ * b::foo, * b::bar * } * ``` * * to this: * * ``` * use a::b::foo; * use a::b::bar; * ``` */ class FlattenUseStatementsIntention : RsElementBaseIntentionAction<FlattenUseStatementsIntention.Context>() { override fun getText() = "Flatten use statements" override fun getFamilyName() = text interface Context { val useSpecks: List<RsUseSpeck> val root: PsiElement val firstOldElement: PsiElement fun createElements(paths: List<String>, project: Project): List<PsiElement> val oldElements: List<PsiElement> val cursorOffset: Int val basePath: String } override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? { val useGroupOnCursor = element.ancestorStrict<RsUseGroup>() ?: return null val isNested = useGroupOnCursor.ancestorStrict<RsUseGroup>() != null val useSpeckOnCursor = when (element) { is RsUseSpeck -> element else -> { val sibling = (element.leftSiblings + element.rightSiblings).firstOrNull { it is RsUseSpeck } sibling ?: element.ancestorStrict<RsUseSpeck>() ?: return null } } as RsUseSpeck val useSpeckList = mutableListOf<RsUseSpeck>() val basePath = useGroupOnCursor.parentUseSpeck.path?.text ?: return null useSpeckList += useSpeckOnCursor.leftSiblings.filterIsInstance<RsUseSpeck>() useSpeckList += useSpeckOnCursor useSpeckList += useSpeckOnCursor.rightSiblings.filterIsInstance<RsUseSpeck>() if (useSpeckList.size == 1) return null return if (isNested) { PathInNestedGroup(useGroupOnCursor, useSpeckList, basePath) } else { PathInGroup(useGroupOnCursor, useSpeckList, basePath) } } override fun invoke(project: Project, editor: Editor, ctx: Context) { val paths = makeSeparatedPath(ctx.basePath, ctx.useSpecks).let { ctx.createElements(it, project) }.map { ctx.root.addBefore(it, ctx.firstOldElement) } for (elem in ctx.oldElements) { elem.delete() } val nextUseSpeckExists = (paths.lastOrNull()?.rightSiblings?.filterIsInstance<RsUseSpeck>()?.count() ?: 0) > 0 if (!nextUseSpeckExists) { paths.last().rightSiblings.find { it.text == "\n" }?.delete() } editor.caretModel.moveToOffset((paths.firstOrNull()?.startOffset ?: 0) + ctx.cursorOffset) } private fun makeSeparatedPath(basePath: String, useSpecks: List<RsUseSpeck>): List<String> = useSpecks.flatMap { val useSpeckList = it.useGroup?.useSpeckList val path = it.path if (useSpeckList != null && path != null) { makeSeparatedPath("$basePath::${path.text}", useSpeckList) } else { listOf(addBasePath(it.text, basePath)) } } private fun addBasePath(localPath: String, basePath: String): String = when (localPath) { "self" -> basePath else -> "$basePath::$localPath" } class PathInNestedGroup( useGroup: RsUseGroup, override val useSpecks: List<RsUseSpeck>, override val basePath: String ) : Context { override fun createElements(paths: List<String>, project: Project): List<PsiElement> = RsPsiFactory(project).let { psiFactory -> paths.map { psiFactory.createUseSpeck(it).also { useSpeck -> useSpeck.add(psiFactory.createComma()) useSpeck.add(psiFactory.createNewline()) } } } override val firstOldElement: PsiElement = useGroup.parent override val oldElements: List<PsiElement> = listOf(firstOldElement).flatMap { if (it.nextSibling?.elementType == RsElementTypes.COMMA) { listOf(it, it.nextSibling) } else { listOf(it) } } override val root = useGroup.parent?.parent ?: throw IllegalStateException() override val cursorOffset: Int = 0 } class PathInGroup( useGroup: RsUseGroup, override val useSpecks: List<RsUseSpeck>, override val basePath: String ) : Context { override fun createElements(paths: List<String>, project: Project): List<PsiElement> = RsPsiFactory(project).let { psiFactory -> // Visibility modifier and attributes are check for only here because it is invalid to have a visibility // modifier inside a use group, same with attributes. For e.g. this is invalid: // use std::{ // pub io, // #[cfg(test)] error // } paths.map { // In case the group `use` had a visibility modifier remember to add it back. // E.g.: pub use x::{y, z} -> pub use x::y; pub use x::z; val item = psiFactory.createUseItem(it, visibility ?: "") // In case the group `use` had attributes remember to add them back. // E.g. #[a] #[b] use x::{y, z} -> #[a] #[b] use x::y; #[a] #[b] use x::z; attrs.reversed().forEach { attr -> // reversed() makes it so that the attributes are in the same order, otherwise they would've // been in reverse val attrPsi = psiFactory.createOuterAttr(attr.metaItem.text) item.addBefore(attrPsi, item.firstChild) } item } } override val firstOldElement: PsiElement = useGroup.parent?.parent ?: throw IllegalStateException() private val attrs: Collection<RsAttr> = firstOldElement.descendantsOfType() private val visibility: String? = (firstOldElement as? RsUseItem)?.vis?.text override val oldElements: List<PsiElement> = listOf(firstOldElement) override val root = useGroup.parent?.parent?.parent ?: throw IllegalStateException() override val cursorOffset: Int = "use ".length + (if (visibility != null) visibility.length + 1 else 0) + (attrs.sumOf { it.textLength }) } }
mit
886100e8d563f73967316db9f0c8ccfe
36.342541
120
0.596538
4.814103
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/types/infer/PatternMatching.kt
2
8837
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.types.infer import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.psi.ext.RsBindingModeKind.BindByReference import org.rust.lang.core.psi.ext.RsBindingModeKind.BindByValue import org.rust.lang.core.types.consts.Const import org.rust.lang.core.types.consts.CtUnknown import org.rust.lang.core.types.normType import org.rust.lang.core.types.ty.* import org.rust.lang.core.types.ty.Mutability.IMMUTABLE import org.rust.lang.utils.evaluation.ConstExpr import org.rust.lang.utils.evaluation.toConst import org.rust.openapiext.Testmark fun RsPat.extractBindings(fcx: RsTypeInferenceWalker, type: Ty, defBm: RsBindingModeKind = BindByValue(IMMUTABLE)) { when (this) { is RsPatWild -> fcx.writePatTy(this, type) is RsPatConst -> { val expr = expr if (expr is RsPathExpr) { val inferred = fcx.inferType(expr) val expected = when (fcx.getResolvedPath(expr).singleOrNull()?.element) { is RsConstant -> type else -> type.stripReferences(defBm).first } fcx.coerce(expr, inferred, expected) fcx.writePatTy(this, expected) } else { val expected = when { expr is RsLitExpr && expr.kind is RsLiteralKind.String -> type else -> type.stripReferences(defBm).first } fcx.writePatTy(this, expected) fcx.inferTypeCoercableTo(expr, expected) } } is RsPatRef -> { pat.extractBindings(fcx, (type as? TyReference)?.referenced ?: TyUnknown) fcx.writePatTy(this, type) } is RsPatRange -> { val (expected, _) = type.stripReferences(defBm) fcx.writePatTy(this, expected) patConstList.forEach { fcx.inferTypeCoercableTo(it.expr, expected) } } is RsPatIdent -> { val patBinding = patBinding val resolved = patBinding.reference.resolve() val bindingType = if (resolved is RsEnumVariant) { type.stripReferences(defBm).first } else { patBinding.inferType(type, defBm) } fcx.writePatTy(this, bindingType) pat?.extractBindings(fcx, type) } is RsPatTup -> { val (expected, bm) = type.stripReferences(defBm) fcx.writePatTy(this, expected) val types = (expected as? TyTuple)?.types.orEmpty() inferTupleFieldsTypes(fcx, patList, bm, types.size) { types.getOrElse(it) { TyUnknown } } } is RsPatTupleStruct -> { val (expected, bm) = type.stripReferences(defBm) fcx.writePatTy(this, expected) val item = path.reference?.resolve() as? RsFieldsOwner ?: ((expected as? TyAdt)?.item as? RsStructItem) ?: return val tupleFields = item.positionalFields inferTupleFieldsTypes(fcx, patList, bm, tupleFields.size) { idx -> tupleFields .getOrNull(idx) ?.typeReference ?.normType(fcx.ctx) ?.substituteOrUnknown(expected.typeParameterValues) ?: TyUnknown } } is RsPatStruct -> { val (expected, mut) = type.stripReferences(defBm) fcx.writePatTy(this, expected) val item = path.reference?.resolve() as? RsFieldsOwner ?: ((expected as? TyAdt)?.item as? RsStructItem) ?: return val structFields = item.fields.associateBy { it.name } for (patField in patFieldList) { val kind = patField.kind val fieldType = structFields[kind.fieldName] ?.typeReference ?.normType(fcx.ctx) ?.substituteOrUnknown(expected.typeParameterValues) ?: TyUnknown when (kind) { is RsPatFieldKind.Full -> { kind.pat.extractBindings(fcx, fieldType, mut) fcx.writePatFieldTy(patField, fieldType) } is RsPatFieldKind.Shorthand -> { val bindingType = if (fieldType is TyAdt && kind.isBox) { fieldType.typeArguments.firstOrNull() ?: return } else { fieldType } fcx.writePatFieldTy(patField, kind.binding.inferType(bindingType, mut)) } } } } is RsPatSlice -> { val (expected, bm) = type.stripReferences(defBm) fcx.writePatTy(this, expected) inferSlicePatsTypes(fcx, patList, bm, expected) } is RsPatBox -> { val (expected, bm) = type.stripReferences(defBm) fcx.writePatTy(this, expected) if (expected is TyAdt && expected.isBox) { val boxed = expected.typeArguments.firstOrNull() ?: return pat.extractBindings(fcx, boxed, bm) } } is RsOrPat -> { for (pat in patList) { pat.extractBindings(fcx, type, defBm) } fcx.writePatTy(this, type) } else -> { // not yet handled } } } private val RsPat.isRest: Boolean get() = this is RsPatRest || this is RsPatIdent && pat is RsPatRest private fun inferSlicePatsTypes( fcx: RsTypeInferenceWalker, patList: List<RsPat>, bm: RsBindingModeKind, sliceType: Ty ) { fun calcRestSize(arrayTy: TyArray): Const { val arraySize = arrayTy.size ?: return CtUnknown val patRestCount = patList.count { it.isRest } if (patRestCount != 1) { PatternMatchingTestMarks.MultipleRestPats.hit() return CtUnknown } val restSize = arraySize - patList.size.toLong() + 1 if (restSize < 0) { PatternMatchingTestMarks.NegativeRestSize.hit() return CtUnknown } return ConstExpr.Value.Integer(restSize, TyInteger.USize.INSTANCE).toConst() } val (elementType, restType) = when (sliceType) { is TyArray -> sliceType.base to sliceType.copy(const = calcRestSize(sliceType)) is TySlice -> sliceType.elementType to sliceType else -> TyUnknown to TyUnknown } for (pat in patList) { val patType = if (pat.isRest) restType else elementType pat.extractBindings(fcx, patType, bm) } } private fun inferTupleFieldsTypes( fcx: RsTypeInferenceWalker, patList: List<RsPat>, bm: RsBindingModeKind, tupleSize: Int, type: (Int) -> Ty ) { // In correct code, tuple or tuple struct patterns contain only one `..` pattern. // But it's pretty simple to support type inference for cases with multiple `..` patterns like `let (x, .., y, .., z) = tuple` // just ignoring all binding between first and last `..` patterns var firstPatRestIndex = Int.MAX_VALUE var lastPatRestIndex = -1 for ((index, pat) in patList.withIndex()) { if (pat.isRest) { firstPatRestIndex = minOf(firstPatRestIndex, index) lastPatRestIndex = maxOf(lastPatRestIndex, index) } } for ((idx, p) in patList.withIndex()) { val fieldType = when { idx < firstPatRestIndex -> type(idx) idx > lastPatRestIndex -> type(tupleSize - (patList.size - idx)) else -> TyUnknown } p.extractBindings(fcx, fieldType, bm) } } private fun RsPatBinding.inferType(expected: Ty, defBm: RsBindingModeKind): Ty { val bm = run { val bm = kind if (bm is BindByValue && bm.mutability == IMMUTABLE) { defBm } else { bm } } return if (bm is BindByReference) TyReference(expected, bm.mutability) else expected } private fun Ty.stripReferences(defBm: RsBindingModeKind): Pair<Ty, RsBindingModeKind> { var bm = defBm var ty = this while (ty is TyReference) { bm = when (bm) { is BindByValue -> BindByReference(ty.mutability) is BindByReference -> BindByReference( if (bm.mutability == IMMUTABLE) IMMUTABLE else ty.mutability ) } ty = ty.referenced } return ty to bm } object PatternMatchingTestMarks { object MultipleRestPats : Testmark() object NegativeRestSize : Testmark() }
mit
522283dda64f3f68e0673e7e80d4d9eb
35.66805
130
0.571461
4.194115
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/macros/decl/FragmentKind.kt
3
2917
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.macros.decl import com.intellij.lang.PsiBuilder import com.intellij.lang.parser.GeneratedParserUtilBase import com.intellij.psi.tree.TokenSet import org.rust.lang.core.parser.RustParser import org.rust.lang.core.parser.RustParserUtil import org.rust.lang.core.parser.clearFrame import org.rust.lang.core.psi.RS_IDENTIFIER_TOKENS import org.rust.lang.core.psi.RsElementTypes.QUOTE_IDENTIFIER import org.rust.lang.core.psi.RsElementTypes.TT enum class FragmentKind(private val kind: String) { Ident("ident"), Path("path"), Expr("expr"), Ty("ty"), Pat("pat"), PatParam("pat_param"), Stmt("stmt"), Block("block"), Item("item"), Meta("meta"), Tt("tt"), Vis("vis"), Literal("literal"), Lifetime("lifetime"); fun parse(builder: PsiBuilder): Boolean { builder.clearFrame() return when (this) { Ident -> parseIdentifier(builder) Path -> RustParser.TypePathGenericArgsNoTypeQual(builder, 0) Expr -> RustParser.Expr(builder, 0, -1) Ty -> RustParser.TypeReference(builder, 0) Pat -> RustParserUtil.parseSimplePat(builder) // TODO `RustParser.Pat(builder, 0)` on 2021 edition PatParam -> RustParserUtil.parseSimplePat(builder) Stmt -> parseStatement(builder) Block -> RustParserUtil.parseCodeBlockLazy(builder, 0) Item -> RustParser.Item(builder, 0) Meta -> RustParser.MetaItemWithoutTT(builder, 0) Vis -> parseVis(builder) Tt -> parseTT(builder) Lifetime -> GeneratedParserUtilBase.consumeTokenFast(builder, QUOTE_IDENTIFIER) Literal -> parseLiteral(builder) } } private fun parseIdentifier(b: PsiBuilder): Boolean = b.consumeToken(RS_IDENTIFIER_TOKENS) private fun parseStatement(b: PsiBuilder): Boolean = RustParser.LetDecl(b, 0) || RustParser.Expr(b, 0, -1) private fun parseVis(b: PsiBuilder): Boolean { RustParser.Vis(b, 0) return true // Vis can be empty } private fun parseTT(b: PsiBuilder): Boolean { return RustParserUtil.unpairedToken(b, 0) || RustParserUtil.parseTokenTreeLazy(b, 0, TT) } private fun parseLiteral(b: PsiBuilder): Boolean { return RustParser.LitExprWithoutAttrs(b, 0) } private fun PsiBuilder.consumeToken(tokenSet: TokenSet): Boolean { return if (tokenType in tokenSet) { advanceLexer() true } else { false } } companion object { private val fragmentKinds: Map<String, FragmentKind> = values().associateBy { it.kind } val kinds: Set<String> = fragmentKinds.keys fun fromString(s: String): FragmentKind? = fragmentKinds[s] } }
mit
2b316233267a0100c992319f09c1d343
32.147727
110
0.650668
4.057024
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/test/java/androidx/compose/ui/text/font/FontFamilyTest.kt
3
2627
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.font import androidx.compose.ui.text.ExperimentalTextApi import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) @OptIn(ExperimentalTextApi::class) class FontFamilyTest { private val resourceId1 = 1 private val resourceId2 = 2 @Test(expected = IllegalStateException::class) fun `cannot be instantiated with empty font list`() { FontFamily(listOf()) } @Test fun `two equal family declarations are equal`() { val fontFamily = FontFamily( Font( resId = resourceId1, weight = FontWeight.W900, style = FontStyle.Italic ) ) val otherFontFamily = FontFamily( Font( resId = resourceId1, weight = FontWeight.W900, style = FontStyle.Italic ) ) assertThat(fontFamily).isEqualTo(otherFontFamily) } @Test fun `two non equal family declarations are not equal`() { val fontFamily = FontFamily( Font( resId = resourceId1, weight = FontWeight.W900, style = FontStyle.Italic ) ) val otherFontFamily = FontFamily( Font( resId = resourceId1, weight = FontWeight.W800, style = FontStyle.Italic ) ) assertThat(fontFamily).isNotEqualTo(otherFontFamily) } @Test fun `can add fallback font at same weight and style`() { FontFamily( Font( resId = resourceId1, weight = FontWeight.W900, style = FontStyle.Italic ), Font( resId = resourceId1, weight = FontWeight.W900, style = FontStyle.Italic ) ) } }
apache-2.0
812682c31dc8123867d088d1c5b9c025
27.258065
75
0.588885
4.91028
false
true
false
false
androidx/androidx
compose/material/material/src/commonMain/kotlin/androidx/compose/material/Snackbar.kt
3
14849
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.paddingFromBaseline import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.compositeOver import androidx.compose.ui.layout.AlignmentLine import androidx.compose.ui.layout.FirstBaseline import androidx.compose.ui.layout.LastBaseline import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.layoutId import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import kotlin.math.max /** * <a href="https://material.io/components/snackbars" class="external" target="_blank">Material Design snackbar</a>. * * Snackbars provide brief messages about app processes at the bottom of the screen. * * Snackbars inform users of a process that an app has performed or will perform. They appear * temporarily, towards the bottom of the screen. They shouldn’t interrupt the user experience, * and they don’t require user input to disappear. * * A Snackbar can contain a single action. Because Snackbar disappears automatically, the action * shouldn't be "Dismiss" or "Cancel". * * ![Snackbars image](https://developer.android.com/images/reference/androidx/compose/material/snackbars.png) * * This components provides only the visuals of the [Snackbar]. If you need to show a [Snackbar] * with defaults on the screen, use [ScaffoldState.snackbarHostState] and * [SnackbarHostState.showSnackbar]: * * @sample androidx.compose.material.samples.ScaffoldWithSimpleSnackbar * * If you want to customize appearance of the [Snackbar], you can pass your own version as a child * of the [SnackbarHost] to the [Scaffold]: * @sample androidx.compose.material.samples.ScaffoldWithCustomSnackbar * * @param modifier modifiers for the Snackbar layout * @param action action / button component to add as an action to the snackbar. Consider using * [SnackbarDefaults.primaryActionColor] as the color for the action, if you do not * have a predefined color you wish to use instead. * @param actionOnNewLine whether or not action should be put on the separate line. Recommended * for action with long action text * @param shape Defines the Snackbar's shape as well as its shadow * @param backgroundColor background color of the Snackbar * @param contentColor color of the content to use inside the snackbar. Defaults to * either the matching content color for [backgroundColor], or, if it is not a color from * the theme, this will keep the same value set above this Surface. * @param elevation The z-coordinate at which to place the SnackBar. This controls the size * of the shadow below the SnackBar * @param content content to show information about a process that an app has performed or will * perform */ @Composable fun Snackbar( modifier: Modifier = Modifier, action: @Composable (() -> Unit)? = null, actionOnNewLine: Boolean = false, shape: Shape = MaterialTheme.shapes.small, backgroundColor: Color = SnackbarDefaults.backgroundColor, contentColor: Color = MaterialTheme.colors.surface, elevation: Dp = 6.dp, content: @Composable () -> Unit ) { Surface( modifier = modifier, shape = shape, elevation = elevation, color = backgroundColor, contentColor = contentColor ) { CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.high) { val textStyle = MaterialTheme.typography.body2 ProvideTextStyle(value = textStyle) { when { action == null -> TextOnlySnackbar(content) actionOnNewLine -> NewLineButtonSnackbar(content, action) else -> OneRowSnackbar(content, action) } } } } } /** * <a href="https://material.io/components/snackbars" class="external" target="_blank">Material Design snackbar</a>. * * Snackbars provide brief messages about app processes at the bottom of the screen. * * Snackbars inform users of a process that an app has performed or will perform. They appear * temporarily, towards the bottom of the screen. They shouldn’t interrupt the user experience, * and they don’t require user input to disappear. * * A Snackbar can contain a single action. Because they disappear automatically, the action * shouldn't be "Dismiss" or "Cancel". * * ![Snackbars image](https://developer.android.com/images/reference/androidx/compose/material/snackbars.png) * * This version of snackbar is designed to work with [SnackbarData] provided by the * [SnackbarHost], which is usually used inside of the [Scaffold]. * * This components provides only the visuals of the [Snackbar]. If you need to show a [Snackbar] * with defaults on the screen, use [ScaffoldState.snackbarHostState] and * [SnackbarHostState.showSnackbar]: * * @sample androidx.compose.material.samples.ScaffoldWithSimpleSnackbar * * If you want to customize appearance of the [Snackbar], you can pass your own version as a child * of the [SnackbarHost] to the [Scaffold]: * @sample androidx.compose.material.samples.ScaffoldWithCustomSnackbar * * @param snackbarData data about the current snackbar showing via [SnackbarHostState] * @param modifier modifiers for the Snackbar layout * @param actionOnNewLine whether or not action should be put on the separate line. Recommended * for action with long action text * @param shape Defines the Snackbar's shape as well as its shadow * @param backgroundColor background color of the Snackbar * @param contentColor color of the content to use inside the snackbar. Defaults to * either the matching content color for [backgroundColor], or, if it is not a color from * the theme, this will keep the same value set above this Surface. * @param actionColor color of the action * @param elevation The z-coordinate at which to place the SnackBar. This controls the size * of the shadow below the SnackBar */ @Composable fun Snackbar( snackbarData: SnackbarData, modifier: Modifier = Modifier, actionOnNewLine: Boolean = false, shape: Shape = MaterialTheme.shapes.small, backgroundColor: Color = SnackbarDefaults.backgroundColor, contentColor: Color = MaterialTheme.colors.surface, actionColor: Color = SnackbarDefaults.primaryActionColor, elevation: Dp = 6.dp ) { val actionLabel = snackbarData.actionLabel val actionComposable: (@Composable () -> Unit)? = if (actionLabel != null) { @Composable { TextButton( colors = ButtonDefaults.textButtonColors(contentColor = actionColor), onClick = { snackbarData.performAction() }, content = { Text(actionLabel) } ) } } else { null } Snackbar( modifier = modifier.padding(12.dp), content = { Text(snackbarData.message) }, action = actionComposable, actionOnNewLine = actionOnNewLine, shape = shape, backgroundColor = backgroundColor, contentColor = contentColor, elevation = elevation ) } /** * Object to hold defaults used by [Snackbar] */ object SnackbarDefaults { /** * Default alpha of the overlay applied to the [backgroundColor] */ private const val SnackbarOverlayAlpha = 0.8f /** * Default background color of the [Snackbar] */ val backgroundColor: Color @Composable get() = MaterialTheme.colors.onSurface .copy(alpha = SnackbarOverlayAlpha) .compositeOver(MaterialTheme.colors.surface) /** * Provides a best-effort 'primary' color to be used as the primary color inside a [Snackbar]. * Given that [Snackbar]s have an 'inverted' theme, i.e. in a light theme they appear dark, and * in a dark theme they appear light, just using [Colors.primary] will not work, and has * incorrect contrast. * * If your light theme has a corresponding dark theme, you should instead directly use * [Colors.primary] from the dark theme when in a light theme, and use * [Colors.primaryVariant] from the dark theme when in a dark theme. * * When in a light theme, this function applies a color overlay to [Colors.primary] from * [MaterialTheme.colors] to attempt to reduce the contrast, and when in a dark theme this * function uses [Colors.primaryVariant]. */ val primaryActionColor: Color @Composable get() { val colors = MaterialTheme.colors return if (colors.isLight) { val primary = colors.primary val overlayColor = colors.surface.copy(alpha = 0.6f) overlayColor.compositeOver(primary) } else { colors.primaryVariant } } } @Composable private fun TextOnlySnackbar(content: @Composable () -> Unit) { Layout({ Box( modifier = Modifier.padding( horizontal = HorizontalSpacing, vertical = SnackbarVerticalPadding ) ) { content() } }) { measurables, constraints -> require(measurables.size == 1) { "text for Snackbar expected to have exactly only one child" } val textPlaceable = measurables.first().measure(constraints) val firstBaseline = textPlaceable[FirstBaseline] val lastBaseline = textPlaceable[LastBaseline] require(firstBaseline != AlignmentLine.Unspecified) { "No baselines for text" } require(lastBaseline != AlignmentLine.Unspecified) { "No baselines for text" } val minHeight = if (firstBaseline == lastBaseline) { SnackbarMinHeightOneLine } else { SnackbarMinHeightTwoLines } val containerHeight = max(minHeight.roundToPx(), textPlaceable.height) layout(constraints.maxWidth, containerHeight) { val textPlaceY = (containerHeight - textPlaceable.height) / 2 textPlaceable.placeRelative(0, textPlaceY) } } } @Composable private fun NewLineButtonSnackbar( text: @Composable () -> Unit, action: @Composable () -> Unit ) { Column( modifier = Modifier.fillMaxWidth() .padding( start = HorizontalSpacing, end = HorizontalSpacingButtonSide, bottom = SeparateButtonExtraY ) ) { Box( Modifier.paddingFromBaseline(HeightToFirstLine, LongButtonVerticalOffset) .padding(end = HorizontalSpacingButtonSide) ) { text() } Box(Modifier.align(Alignment.End)) { action() } } } @Composable private fun OneRowSnackbar( text: @Composable () -> Unit, action: @Composable () -> Unit ) { val textTag = "text" val actionTag = "action" Layout( { Box(Modifier.layoutId(textTag).padding(vertical = SnackbarVerticalPadding)) { text() } Box(Modifier.layoutId(actionTag)) { action() } }, modifier = Modifier.padding( start = HorizontalSpacing, end = HorizontalSpacingButtonSide ) ) { measurables, constraints -> val buttonPlaceable = measurables.first { it.layoutId == actionTag }.measure(constraints) val textMaxWidth = (constraints.maxWidth - buttonPlaceable.width - TextEndExtraSpacing.roundToPx()) .coerceAtLeast(constraints.minWidth) val textPlaceable = measurables.first { it.layoutId == textTag }.measure( constraints.copy(minHeight = 0, maxWidth = textMaxWidth) ) val firstTextBaseline = textPlaceable[FirstBaseline] require(firstTextBaseline != AlignmentLine.Unspecified) { "No baselines for text" } val lastTextBaseline = textPlaceable[LastBaseline] require(lastTextBaseline != AlignmentLine.Unspecified) { "No baselines for text" } val isOneLine = firstTextBaseline == lastTextBaseline val buttonPlaceX = constraints.maxWidth - buttonPlaceable.width val textPlaceY: Int val containerHeight: Int val buttonPlaceY: Int if (isOneLine) { val minContainerHeight = SnackbarMinHeightOneLine.roundToPx() val contentHeight = buttonPlaceable.height containerHeight = max(minContainerHeight, contentHeight) textPlaceY = (containerHeight - textPlaceable.height) / 2 val buttonBaseline = buttonPlaceable[FirstBaseline] buttonPlaceY = buttonBaseline.let { if (it != AlignmentLine.Unspecified) { textPlaceY + firstTextBaseline - it } else { 0 } } } else { val baselineOffset = HeightToFirstLine.roundToPx() textPlaceY = baselineOffset - firstTextBaseline val minContainerHeight = SnackbarMinHeightTwoLines.roundToPx() val contentHeight = textPlaceY + textPlaceable.height containerHeight = max(minContainerHeight, contentHeight) buttonPlaceY = (containerHeight - buttonPlaceable.height) / 2 } layout(constraints.maxWidth, containerHeight) { textPlaceable.placeRelative(0, textPlaceY) buttonPlaceable.placeRelative(buttonPlaceX, buttonPlaceY) } } } private val HeightToFirstLine = 30.dp private val HorizontalSpacing = 16.dp private val HorizontalSpacingButtonSide = 8.dp private val SeparateButtonExtraY = 2.dp private val SnackbarVerticalPadding = 6.dp private val TextEndExtraSpacing = 8.dp private val LongButtonVerticalOffset = 12.dp private val SnackbarMinHeightOneLine = 48.dp private val SnackbarMinHeightTwoLines = 68.dp
apache-2.0
93883e1dec8ce9adcf948931bd31d912
39.884298
116
0.687487
4.708439
false
false
false
false
solkin/drawa-android
app/src/main/java/com/tomclaw/drawa/draw/ImageProvider.kt
1
2453
package com.tomclaw.drawa.draw import android.graphics.Bitmap import android.graphics.BitmapFactory import com.tomclaw.drawa.core.Journal import com.tomclaw.drawa.dto.Record import com.tomclaw.drawa.util.imageFile import com.tomclaw.drawa.util.safeClose import io.reactivex.Single import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.InputStream import java.io.OutputStream interface ImageProvider { fun readImage(recordId: Int): Single<Bitmap> fun saveImage(recordId: Int, bitmap: Bitmap): Single<Record> fun duplicateImage(sourceRecordId: Int, targetRecordId: Int): Single<Unit> } class ImageProviderImpl( private val filesDir: File, private val journal: Journal ) : ImageProvider { override fun readImage(recordId: Int): Single<Bitmap> = Single.create { emitter -> var stream: InputStream? = null try { val imageFile = journal.get(recordId).imageFile(filesDir) stream = FileInputStream(imageFile) emitter.onSuccess(BitmapFactory.decodeStream(stream)) } catch (ex: Throwable) { emitter.onError(ex) } finally { stream.safeClose() } } override fun saveImage(recordId: Int, bitmap: Bitmap): Single<Record> = Single .create<Unit> { journal.get(recordId) .imageFile(filesDir) .delete() it.onSuccess(Unit) } .flatMap { journal.touch(recordId) } .map { record -> var stream: OutputStream? = null try { val imageFile = record.imageFile(filesDir) stream = FileOutputStream(imageFile) bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream) } finally { stream.safeClose() } record } override fun duplicateImage(sourceRecordId: Int, targetRecordId: Int): Single<Unit> = Single .create { journal .get(sourceRecordId) .imageFile(filesDir) .copyTo( target = journal.get(targetRecordId).imageFile(filesDir), overwrite = true ) it.onSuccess(Unit) } }
apache-2.0
d8ea91597b5c4926716f93b1bc5ea49a
31.276316
96
0.572768
4.935614
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/utils/dto/UtilsStatsExtended.kt
1
2046
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.utils.dto import com.google.gson.annotations.SerializedName import kotlin.Int import kotlin.collections.List /** * @param cities * @param countries * @param sexAge * @param timestamp - Start time * @param views - Total views number */ data class UtilsStatsExtended( @SerializedName("cities") val cities: List<UtilsStatsCity>? = null, @SerializedName("countries") val countries: List<UtilsStatsCountry>? = null, @SerializedName("sex_age") val sexAge: List<UtilsStatsSexAge>? = null, @SerializedName("timestamp") val timestamp: Int? = null, @SerializedName("views") val views: Int? = null )
mit
f755cd1d35c5adb2ac1e216a17e7cbec
38.346154
81
0.683773
4.467249
false
false
false
false
cy6erGn0m/kotlinx.concurrent.poc
src/main/kotlin/conc-classes.kt
1
2303
package kotlinx.concurrent import java.util.concurrent.Future import java.util.concurrent.TimeUnit import java.util.concurrent.ExecutionException import java.util.concurrent.CountDownLatch import java.util.concurrent.CancellationException import java.util.concurrent.TimeoutException import java.util.concurrent.atomic.AtomicReference /** * @author Sergey Mashkov */ class CompletedFuture<T>(val value : T) : Future<T> { override fun cancel(mayInterruptIfRunning: Boolean) = false override fun isCancelled() = false override fun isDone() = true override fun get() = value override fun get(timeout: Long, unit: TimeUnit): T = get() } class FailedFuture<T>(val error : Throwable) : Future<T> { override fun cancel(mayInterruptIfRunning: Boolean) = false override fun isCancelled() = false override fun isDone() = true override fun get(): T = throw ExecutionException(error) override fun get(timeout: Long, unit: TimeUnit): T = get() } class ExternalFuture<T>(val onCancel : () -> Unit = {}) : Future<T> { private val initializedLatch = CountDownLatch(1) private var value : AtomicReference<Maybe<T>> = AtomicReference(Missing()) override fun cancel(mayInterruptIfRunning: Boolean): Boolean { initializedLatch.countDown() if (isCancelled()) { onCancel() return true } return false } override fun isCancelled() = initializedLatch.getCount() == 0L && value.get() is Missing override fun isDone() = initializedLatch.getCount() == 0L && value.get() is Present override fun get(): T { initializedLatch.await() val v = value.get() return if (v is Present<T>) v.value else throw CancellationException() } override fun get(timeout: Long, unit: TimeUnit): T { if (!initializedLatch.await(timeout, unit)) { throw TimeoutException() } return get() } tailRecursive fun populate(finalValue : T) { val v = value.get() if (v is Present) { throw IllegalStateException("Value is already present") } if (!value.compareAndSet(v, Present(finalValue))) { populate(finalValue) } else { initializedLatch.countDown() } } }
apache-2.0
80adb481f759cefbdd23b6a4dceee64b
29.315789
92
0.657838
4.480545
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/studyroom/model/StudyRoom.kt
1
1843
package de.tum.`in`.tumcampusapp.component.ui.studyroom.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.RoomWarnings import com.google.gson.annotations.SerializedName import org.joda.time.DateTime /** * Representation of a study room. */ @Entity(tableName = "study_rooms") @SuppressWarnings(RoomWarnings.DEFAULT_CONSTRUCTOR) data class StudyRoom( @PrimaryKey @SerializedName("room_id") var id: Int = -1, @SerializedName("room_code") var code: String = "", @SerializedName("room_name") var name: String = "", @ColumnInfo(name = "building_name") @SerializedName("building_name") var buildingName: String = "", @ColumnInfo(name = "group_id") @SerializedName("group_id") var studyRoomGroup: Int = -1, @ColumnInfo(name = "occupied_until") @SerializedName("occupied_until") var occupiedUntil: DateTime? = null, @ColumnInfo(name = "free_until") @SerializedName("free_until") var freeUntil: DateTime? = null ) : Comparable<StudyRoom> { override fun compareTo(other: StudyRoom): Int { // We use the following sorting order: // 1. Rooms that are currently free and don't have a reservation coming up (freeUntil == null) // 2. Rooms that are currently free but have a reservation coming up (sorted descending by // the amount of free time remaining) // 3. Rooms that are currently occupied but will be free soon (sorted ascending by the // amount of occupied time remaining) // 4. The remaining rooms return compareBy<StudyRoom> { it.freeUntil?.millis?.times(-1) } .thenBy { it.occupiedUntil } .thenBy { it.name } .compare(this, other) } override fun toString() = code }
gpl-3.0
d1111315d7447e85f6bbbe4a1e654598
34.442308
102
0.666848
4.141573
false
false
false
false
neworld/random-decision
mobile/src/main/java/lt/neworld/randomdecision2/MainActivity.kt
1
5071
package lt.neworld.randomdecision2 import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView import com.dropbox.core.android.Auth import kotlinx.android.synthetic.main.activity_main.* import lt.neworld.randomdecision2.choices.Builder import lt.neworld.randomdecision2.choices.Choice import lt.neworld.randomdecision2.choices.RandomPicker import lt.neworld.randomdecision2.dropbox.DropBoxHelper import lt.neworld.randomdecision2.extensions.ignoreOnComplete import lt.neworld.randomdecision2.extensions.showToast import rx.Single import rx.Subscriber import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.functions.Func2 import rx.subjects.PublishSubject import java.io.InputStream import java.io.InputStreamReader class MainActivity : Activity() { private val dropBoxHelper by lazy { DropBoxHelper(this) { onTokenReady() } } private val adapter by lazy { ChoiceAdapter() } private val choicesListUpdates = PublishSubject.create<List<Choice>>() private val cache = Cache(this) private lateinit var loaderFromCache: Subscription override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) list.adapter = adapter list.setOnItemClickListener { adapterView, view, index, id -> pick(adapter.getItem(index)) } choicesListUpdates .observeOn(AndroidSchedulers.mainThread()) .subscribe(object : Subscriber<List<Choice>>() { override fun onCompleted() { } override fun onError(e: Throwable) { Log.d(TAG, "Failed load", e) showToast(e.message ?: "Something bad happened") } override fun onNext(t: List<Choice>) { adapter.clear() adapter.addAll(t) } }) loaderFromCache = cache.loadFromCache().subscribe(choicesListUpdates.ignoreOnComplete()) } private fun pick(choice: Choice) { val path = RandomPicker(choice).pick() status.text = path.map { it.title }.joinToString(" -> ") } override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) menuInflater.inflate(R.menu.main, menu) return true } override fun onResume() { super.onResume() dropBoxHelper.onResume() } override fun onDestroy() { super.onDestroy() cache.release() } private fun onTokenReady() { dropBoxHelper.listFiles(dropBoxHelper.path) .map { it.entries.filter { it.name.endsWith(Choice.FILE_EXT) } } .toObservable() .flatMapIterable { it } .flatMap { dropBoxHelper .openFile(it.pathLower) .zipWith(Single.just(it.pathDisplay.split("/").last()), { t1: () -> InputStream, t2: String -> t2 to t1 }).toObservable() } .doOnNext { cache.saveToCache(it.first, it.second()) } .map { val title = Choice.getName(it.first) Builder(title, InputStreamReader(it.second())).build() } .toSortedList(Choice::compareTo) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { progressBar.visibility = View.VISIBLE } .doOnTerminate { progressBar.visibility = View.GONE } .doOnNext { loaderFromCache.unsubscribe() } .subscribe(choicesListUpdates) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_main_settings -> openSettings().let { true } else -> super.onOptionsItemSelected(item) } } private fun openSettings() { if (dropBoxHelper.accessToken == null) { Auth.startOAuth2Authentication(this, getString(R.string.dropbox_apy_key)) } else { val intent = Intent(this, FolderChooserActivity::class.java) startActivity(intent) } } inner class ChoiceAdapter() : ArrayAdapter<Choice>(this, android.R.layout.simple_list_item_1) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? { val item = getItem(position) return super.getView(position, convertView, parent).let { it as TextView }.apply { text = item.title } } } companion object { private const val TAG = "MainActivity" } }
apache-2.0
a212a100a9793513c39713432e6b1065
32.582781
99
0.609939
4.78848
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/dashboard/mine/widget/AnnouncementWarningFragment.kt
1
7745
package com.intfocus.template.dashboard.mine.widget import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.intfocus.template.R import com.intfocus.template.constant.Params.USER_BEAN import com.intfocus.template.constant.Params.USER_NUM import com.intfocus.template.dashboard.mine.activity.NoticeContentActivity import com.intfocus.template.dashboard.mine.adapter.NoticeListAdapter import com.intfocus.template.dashboard.mine.adapter.NoticeMenuAdapter import com.intfocus.template.dashboard.mine.bean.NoticeMenuBean import com.intfocus.template.general.net.ApiException import com.intfocus.template.general.net.CodeHandledSubscriber import com.intfocus.template.general.net.RetrofitUtil import com.intfocus.template.model.response.notice.Notice import com.intfocus.template.model.response.notice.NoticesResult import com.intfocus.template.ui.RefreshFragment import com.intfocus.template.util.ActionLogUtil import com.intfocus.template.util.ErrorUtils import com.intfocus.template.util.HttpUtil import com.intfocus.template.util.ToastUtils import com.lcodecore.tkrefreshlayout.footer.LoadingView import com.lcodecore.tkrefreshlayout.header.SinaRefreshView import org.xutils.x /** * Created by liuruilin on 2017/6/7. */ class AnnouncementWarningFragment : RefreshFragment(), NoticeListAdapter.NoticeItemListener, NoticeMenuAdapter.NoticeItemListener { private lateinit var userId: String private var datas: MutableList<Notice>? = null // var id = "" private lateinit var adapter: NoticeListAdapter private lateinit var queryMap: MutableMap<String, String> /** *菜单 */ private lateinit var menuRecyclerView: RecyclerView private lateinit var noticeMenuAdapter: NoticeMenuAdapter //筛选适配器 private var noticeMenuDatas: MutableList<NoticeMenuBean>? = null//筛选数据 private var typeStr: String? = null //筛选条件 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { mView = inflater.inflate(R.layout.fragment_notice, container, false) x.view().inject(this, mView) setRefreshLayout() userId = mActivity.getSharedPreferences(USER_BEAN, Context.MODE_PRIVATE).getString(USER_NUM, "") initView() getData(true) return mView } fun initView() { if (TextUtils.isEmpty(typeStr)) { typeStr = "0,1,2,3" } queryMap = mutableMapOf() val mLayoutManager = LinearLayoutManager(mActivity) mLayoutManager.orientation = LinearLayoutManager.VERTICAL recyclerView.layoutManager = mLayoutManager adapter = NoticeListAdapter(mActivity, null, this) recyclerView.adapter = adapter val headerView = SinaRefreshView(mActivity) headerView.setArrowResource(R.drawable.loading_up) val bottomView = LoadingView(mActivity) refreshLayout.setHeaderView(headerView) refreshLayout.setBottomView(bottomView) //数据为空(即第一次打开此界面)才初始化Menu数据),默认全部选中 if (noticeMenuDatas == null || noticeMenuDatas!!.size == 0) { val noticeMenuBean = NoticeMenuBean(0, true) val noticeMenuBean1 = NoticeMenuBean(1, true) val noticeMenuBean2 = NoticeMenuBean(2, true) val noticeMenuBean3 = NoticeMenuBean(3, true) noticeMenuDatas = ArrayList() noticeMenuDatas!!.add(noticeMenuBean) noticeMenuDatas!!.add(noticeMenuBean1) noticeMenuDatas!!.add(noticeMenuBean2) noticeMenuDatas!!.add(noticeMenuBean3) } menuRecyclerView = mView!!.findViewById(R.id.menu_recycler_view) val mMenuLayoutManager = LinearLayoutManager(mActivity) mMenuLayoutManager.orientation = LinearLayoutManager.HORIZONTAL menuRecyclerView.layoutManager = mMenuLayoutManager noticeMenuAdapter = NoticeMenuAdapter(mActivity, noticeMenuDatas, this) menuRecyclerView.adapter = noticeMenuAdapter } override fun getData(isShowDialog: Boolean) { if (!HttpUtil.isConnected(mActivity)) { ToastUtils.show(mActivity, "请检查网络链接") finishRequest() isEmpty = datas == null || datas!!.size == 0 ErrorUtils.viewProcessing(refreshLayout, llError, llRetry, "无更多公告", tvErrorMsg, ivError, isEmpty!!, false, R.drawable.pic_3, { getData(true) }) return } if (isShowDialog) { if (loadingDialog == null || !loadingDialog!!.isShowing) { showLoading() } } queryMap.put("user_num", userId) queryMap.put("type", typeStr.toString()) queryMap.put("page", page.toString()) queryMap.put("limit", pagesize.toString()) RetrofitUtil.getHttpService(context).getNoticeList(queryMap) .compose(RetrofitUtil.CommonOptions<NoticesResult>()) .subscribe(object : CodeHandledSubscriber<NoticesResult>() { override fun onCompleted() { finishRequest() } override fun onError(apiException: ApiException?) { finishRequest() ToastUtils.show(mActivity, apiException!!.displayMessage) } override fun onBusinessNext(data: NoticesResult) { finishRequest() total = data.total_page isLasePage = page == total if (datas == null) { datas = ArrayList() } if (isRefresh!!) { datas!!.clear() } datas!!.addAll(data.data) adapter.setData(datas) isEmpty = datas == null || datas!!.size == 0 ErrorUtils.viewProcessing(refreshLayout, llError, llRetry, "无更多文章了", tvErrorMsg, ivError, isEmpty!!, true, R.drawable.pic_3, null) } }) } fun finishRequest() { refreshLayout.finishRefreshing() refreshLayout.finishLoadmore() dismissLoading() } /** * 进入详情 */ override fun itemClick(position: Int) { val intent = Intent(mActivity, NoticeContentActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP intent.putExtra("notice_id", position.toString()) startActivity(intent) ActionLogUtil.actionLog("点击/公告预警") } /** *点击筛选 */ override fun menuClick(noticeMenuBean: NoticeMenuBean) { typeStr = "" if (noticeMenuDatas != null) { for (data in noticeMenuDatas!!.iterator()) { if (data == noticeMenuBean) { data.isSelected = !data.isSelected } if (data.isSelected) { typeStr = if (!TextUtils.isEmpty(typeStr)) { typeStr + "," + data.code } else { "" + data.code } } } noticeMenuAdapter.setData(noticeMenuDatas) } getData(true) } }
gpl-3.0
17b5c95e5003a3e5d64e024605515172
38.578125
131
0.628899
4.711097
false
false
false
false
heinika/MyGankio
app/src/main/java/lijin/heinika/cn/mygankio/dateview/DateViewFragment.kt
1
4168
package lijin.heinika.cn.mygankio.dateview import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v4.app.Fragment import android.support.v4.view.ViewCompat import android.support.v4.view.animation.FastOutSlowInInterpolator import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import lijin.heinika.cn.mygankio.AppDatabase import lijin.heinika.cn.mygankio.R import lijin.heinika.cn.mygankio.dao.GirlsDao import lijin.heinika.cn.mygankio.entiy.GirlsBean import lijin.heinika.cn.mygankio.schedulers.SchedulerProvider import lijin.heinika.cn.mygankio.utils.ColorUtils class DateViewFragment : Fragment(), DateContract.View { private var mRecyclerViewDate: RecyclerView? = null private var mDateAdapter: DateAdapter? = null private var mPresenter: DateContract.Presenter? = null private var mRefreshLayout: SwipeRefreshLayout? = null private var mPage = 1 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { mPresenter = DatePresenter(this, SchedulerProvider.instance) val view = inflater.inflate(R.layout.fragment_date, container, false) (mPresenter as DatePresenter).setGirlsDao(AppDatabase.getDatabase(context!!).getGirlsDao()) initView(view) return view } private fun initView(view: View) { mRecyclerViewDate = view.findViewById(R.id.recyclerView_date) mRefreshLayout = view.findViewById(R.id.swipeRefreshLayout_girl) val fab = view.findViewById<FloatingActionButton>(R.id.fab_to_top_girls) mDateAdapter = DateAdapter(activity!!) mRecyclerViewDate!!.adapter = mDateAdapter val layoutManager = mRecyclerViewDate!!.layoutManager as GridLayoutManager mRecyclerViewDate!!.setOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) { val totalCount = mDateAdapter!!.itemCount val lastItem = layoutManager.findLastCompletelyVisibleItemPosition() if (lastItem > totalCount - 4) { mPage += 1 (mPresenter as DatePresenter).loadGirls(mPage) } } override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (dy >= 0) { animateOut(fab) } else { animateIn(fab) } } }) fab.setOnClickListener { mRecyclerViewDate!!.scrollToPosition(0) } mRefreshLayout!!.setOnRefreshListener { mRefreshLayout!!.setColorSchemeColors(ColorUtils.randomColor, ColorUtils.randomColor) (mPresenter as DatePresenter).loadGirls(1) } } override fun onResume() { super.onResume() mPresenter!!.subscribe() } override fun showGirls(girlsBeen: MutableList<GirlsBean>) { mDateAdapter!!.setDateBeanList(girlsBeen) mRefreshLayout!!.isRefreshing = false } override fun setPresenter(presenter: DateContract.Presenter) { mPresenter = presenter } override fun onPause() { super.onPause() mPresenter!!.unsubscribe() } private fun animateOut(button: FloatingActionButton) { button.visibility = View.GONE ViewCompat.animate(button).scaleX(0.0f).scaleY(0.0f).alpha(0.0f) .setInterpolator(INTERPOLATOR).withLayer() .start() } private fun animateIn(button: FloatingActionButton) { button.visibility = View.VISIBLE ViewCompat.animate(button).scaleX(1.0f).scaleY(1.0f).alpha(1.0f) .setInterpolator(INTERPOLATOR).withLayer() .start() } companion object { private val INTERPOLATOR = FastOutSlowInInterpolator() } }
apache-2.0
40a13783ec6488328e9daf66ec35250e
34.931034
116
0.680662
4.869159
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/ApplicationModule.kt
1
1366
package de.westnordost.streetcomplete import android.app.Application import android.content.Context import android.content.SharedPreferences import android.content.res.AssetManager import android.content.res.Resources import androidx.preference.PreferenceManager import dagger.Module import dagger.Provides import de.westnordost.streetcomplete.location.LocationRequestFragment import de.westnordost.streetcomplete.util.CrashReportExceptionHandler import de.westnordost.streetcomplete.util.SoundFx import javax.inject.Singleton @Module class ApplicationModule(private val application: Application) { @Provides fun appContext(): Context = application @Provides fun application(): Application = application @Provides fun preferences(): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(application) @Provides fun assetManager(): AssetManager = application.assets @Provides fun resources(): Resources = application.resources @Provides fun locationRequestComponent(): LocationRequestFragment = LocationRequestFragment() @Provides @Singleton fun soundFx(): SoundFx = SoundFx(appContext()) @Provides @Singleton fun exceptionHandler(ctx: Context): CrashReportExceptionHandler = CrashReportExceptionHandler( ctx, "[email protected]", "crashreport.txt" ) }
gpl-3.0
39adf4692024409f68e20a8fa1e57eac
33.175
97
0.784773
5.552846
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/profile/interactor/ProfileInteractor.kt
2
1307
package org.stepik.android.domain.profile.interactor import io.reactivex.Maybe import io.reactivex.Observable import io.reactivex.Single import io.reactivex.subjects.BehaviorSubject import org.stepic.droid.preferences.UserPreferences import org.stepik.android.domain.base.DataSourceType import org.stepik.android.domain.profile.model.ProfileData import org.stepik.android.domain.user.repository.UserRepository import javax.inject.Inject class ProfileInteractor @Inject constructor( private val userRepository: UserRepository, private val userPreferences: UserPreferences, private val userSubject: BehaviorSubject<ProfileData> ) { fun getUser(userId: Long): Observable<ProfileData> = Single .fromCallable { userId.takeIf { it > 0 } ?: userPreferences.userId } .flatMapObservable { user -> Maybe .concat( userRepository.getUser(user, primarySourceType = DataSourceType.CACHE), userRepository.getUser(user, primarySourceType = DataSourceType.REMOTE) ) .toObservable() } .map { user -> ProfileData(user, user.id == userPreferences.userId) } .doOnNext(userSubject::onNext) }
apache-2.0
604d935894922030d173223165ecf47e
36.371429
95
0.673298
5.186508
false
false
false
false
Cognifide/APM
app/aem/core/src/main/kotlin/com/cognifide/apm/core/grammar/argument/StringLiteral.kt
1
1249
/* * ========================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.grammar.argument import org.antlr.v4.runtime.tree.TerminalNode /** * Returns string literal without leading and trailing quotation marks. */ fun TerminalNode.toPlainString(): String { val value = toString() if (value.startsWith("\"")) { return value.trim('"') } if (value.startsWith("\'")) { return value.trim('\'') } return value }
apache-2.0
181d6573d24a4a4a6b299f23a6d2f8a1
31.810811
75
0.613291
4.625926
false
false
false
false
shiraji/databinding-support
src/main/kotlin/com/github/shiraji/databindinglayout/linemaker/LayoutNavigationLineMarkerProvider.kt
1
1305
package com.github.shiraji.databindinglayout.linemaker import com.github.shiraji.databindinglayout.collectLayoutVariableTypesOf import com.intellij.codeHighlighting.Pass import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProvider import com.intellij.icons.AllIcons import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement class LayoutNavigationLineMarkerProvider : LineMarkerProvider { override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? { val psiClass = element as? PsiClass ?: return null val qualifiedName = psiClass.qualifiedName ?: return null val layoutVariableTypes = collectLayoutVariableTypesOf(psiClass.project, qualifiedName) if (layoutVariableTypes == null || layoutVariableTypes.isEmpty()) return null return LineMarkerInfo<PsiElement>(psiClass, psiClass.nameIdentifier!!.textRange, AllIcons.FileTypes.Xml, Pass.UPDATE_ALL, null, LayoutIconNavigationHandler(qualifiedName), GutterIconRenderer.Alignment.LEFT) } override fun collectSlowLineMarkers(elements: MutableList<PsiElement>, result: MutableCollection<LineMarkerInfo<PsiElement>>) { // not sure what I need to do here... } }
apache-2.0
96ff4ee5e03e7e4d2e3bff55a37c662f
51.24
214
0.800766
5.097656
false
false
false
false
da1z/intellij-community
java/java-impl/src/com/intellij/lang/java/request/CreateFieldFromJavaUsageRequest.kt
5
2023
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.lang.java.request import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.getTargetSubstitutor import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.guessExpectedTypes import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.CreateFieldRequest import com.intellij.lang.jvm.actions.ExpectedTypes import com.intellij.lang.jvm.types.JvmSubstitutor import com.intellij.psi.PsiElement import com.intellij.psi.PsiJvmSubstitutor import com.intellij.psi.PsiReferenceExpression import com.intellij.psi.util.createSmartPointer internal class CreateFieldFromJavaUsageRequest( reference: PsiReferenceExpression, override val modifiers: Collection<JvmModifier>, override val constant: Boolean, private val useAnchor: Boolean ) : CreateFieldRequest { private val myReference = reference.createSmartPointer() override val isValid: Boolean get() = myReference.element?.referenceName != null val reference: PsiReferenceExpression get() = myReference.element!! val anchor: PsiElement? get() = if (useAnchor) reference else null override val fieldName: String get() = reference.referenceName!! override val fieldType: ExpectedTypes get() = guessExpectedTypes(reference, false).map(::ExpectedJavaType) override val targetSubstitutor: JvmSubstitutor get() = PsiJvmSubstitutor(reference.project, getTargetSubstitutor(reference)) }
apache-2.0
27c1ea77c5f3eddc28a2bd01663fce66
40.285714
126
0.800297
4.597727
false
false
false
false
GKZX-HN/MyGithub
app/src/main/java/com/gkzxhn/mygithub/api/AuthorRetrofitClient.kt
1
1869
package com.gkzxhn.mygithub.api import android.util.Base64 import okhttp3.Interceptor import okhttp3.Response /** * Created by 方 on 2017/10/23. */ class AuthorRetrofitClient private constructor(baseUrl:String) : BaseRetrofitClient(baseUrl){ override fun createInterceptor(vararg properties: String): Interceptor { //创建interceptor return AuthorInterceptor("${properties[0]}:${properties[1]}") } companion object{ @Volatile var mInstance: AuthorRetrofitClient? = null fun getInstance(baseUrl: String) : AuthorRetrofitClient { if (mInstance == null) { synchronized(AuthorRetrofitClient::class) { if (mInstance == null) { mInstance = AuthorRetrofitClient(baseUrl) } } } return mInstance!! } } fun <T> create(service: Class<T>?): T? { if (service == null) { throw RuntimeException("Api service is null!") } return retrofit?.create(service) } class AuthorInterceptor constructor(val userCredentials: String) : Interceptor{ override fun intercept(chain: Interceptor.Chain?): Response { // https://developer.github.com/v3/auth/#basic-authentication // https://developer.github.com/v3/oauth/#non-web-application-flow // val userCredentials = "${properties[0]} : ${properties[1]}" val basicAuth = "Basic " + String(Base64.encode(userCredentials.toByteArray(), Base64.DEFAULT)) val original = chain!!.request() val requestBuilder = original.newBuilder() .header("Authorization", basicAuth.trim { it <= ' ' }) val request = requestBuilder.build() return chain.proceed(request) } } }
gpl-3.0
882f26a7c3dc886a1aac80d9a1da58d1
30.59322
107
0.599034
4.813953
false
false
false
false
Heiner1/AndroidAPS
openhumans/src/main/java/info/nightscout/androidaps/plugin/general/openhumans/delegates/OHStateDelegate.kt
1
2114
package info.nightscout.androidaps.plugin.general.openhumans.delegates import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import info.nightscout.androidaps.plugin.general.openhumans.OpenHumansState import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton import kotlin.reflect.KProperty @Singleton internal class OHStateDelegate @Inject internal constructor( private val sp: SP ) { private var _value = MutableLiveData(loadState()) val value = _value as LiveData<OpenHumansState?> private fun loadState(): OpenHumansState? { return OpenHumansState( accessToken = sp.getStringOrNull("openhumans_access_token", null) ?: return null, refreshToken = sp.getStringOrNull("openhumans_refresh_token", null) ?: return null, expiresAt = if (sp.contains("openhumans_expires_at")) sp.getLong("openhumans_expires_at", 0) else return null, projectMemberId = sp.getStringOrNull("openhumans_project_member_id", null) ?: return null, uploadOffset = sp.getLong("openhumans_upload_offset", 0) ) } operator fun getValue(thisRef: Any?, property: KProperty<*>): OpenHumansState? = _value.value operator fun setValue(thisRef: Any?, property: KProperty<*>, value: OpenHumansState?) { this._value.value = value if (value == null) { sp.remove("openhumans_access_token") sp.remove("openhumans_refresh_token") sp.remove("openhumans_expires_at") sp.remove("openhumans_project_member_id") sp.remove("openhumans_upload_offset") } else { sp.putString("openhumans_access_token", value.accessToken) sp.putString("openhumans_refresh_token", value.refreshToken) sp.putLong("openhumans_expires_at", value.expiresAt) sp.putString("openhumans_project_member_id", value.projectMemberId) sp.putLong("openhumans_upload_offset", value.uploadOffset) } } }
agpl-3.0
866fb7991c2e2bbf43d86297f728a421
40.470588
97
0.671712
4.536481
false
false
false
false
Adventech/sabbath-school-android-2
features/media/src/main/kotlin/app/ss/media/playback/model/MediaId.kt
1
2571
/* * Copyright (c) 2021. 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 app.ss.media.playback.model import timber.log.Timber const val MEDIA_TYPE_AUDIO = "Media.Audio" const val MEDIA_TYPE_ARTIST = "Media.Artist" const val MEDIA_TYPE_ALBUM = "Media.Album" const val MEDIA_TYPE_AUDIO_QUERY = "Media.AudioQuery" const val MEDIA_TYPE_AUDIO_MINERVA_QUERY = "Media.AudioMinervaQuery" const val MEDIA_TYPE_AUDIO_FLACS_QUERY = "Media.AudioFlacsQuery" private const val MEDIA_ID_SEPARATOR = " | " data class MediaId( val type: String = MEDIA_TYPE_AUDIO, val value: String = "0", val index: Int = 0, val caller: String = CALLER_SELF ) { companion object { const val CALLER_SELF = "self" const val CALLER_OTHER = "other" } override fun toString(): String { return type + MEDIA_ID_SEPARATOR + value + MEDIA_ID_SEPARATOR + index + MEDIA_ID_SEPARATOR + caller } } fun String.toMediaId(): MediaId { val parts = split(MEDIA_ID_SEPARATOR) val type = parts[0] val knownTypes = listOf( MEDIA_TYPE_AUDIO, MEDIA_TYPE_ARTIST, MEDIA_TYPE_ALBUM, MEDIA_TYPE_AUDIO_QUERY, MEDIA_TYPE_AUDIO_MINERVA_QUERY, MEDIA_TYPE_AUDIO_FLACS_QUERY ) if (type !in knownTypes) { Timber.e("Unknown media type: $type") return MediaId() } return if (parts.size > 1) { MediaId(type, parts[1], parts[2].toInt(), parts[3]) } else MediaId() }
mit
426183063cbafd9211855814246a546f
32.828947
80
0.68767
3.837313
false
false
false
false
Maccimo/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebServer.kt
2
14503
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet") package org.jetbrains.builtInWebServer import com.github.benmanes.caffeine.cache.Caffeine import com.google.common.net.InetAddresses import com.intellij.ide.SpecialConfigFiles.USER_WEB_TOKEN import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationType import com.intellij.notification.SingletonNotificationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.endsWithName import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.util.text.Strings import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.io.* import com.intellij.util.io.DigestUtil.randomToken import com.intellij.util.net.NetUtils import io.netty.channel.Channel import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.http.* import io.netty.handler.codec.http.cookie.DefaultCookie import io.netty.handler.codec.http.cookie.ServerCookieDecoder import io.netty.handler.codec.http.cookie.ServerCookieEncoder import org.jetbrains.ide.BuiltInServerBundle import org.jetbrains.ide.BuiltInServerManagerImpl import org.jetbrains.ide.HttpRequestHandler import org.jetbrains.ide.orInSafeMode import org.jetbrains.io.send import java.awt.datatransfer.StringSelection import java.io.IOException import java.net.InetAddress import java.net.URI import java.nio.file.Files import java.nio.file.Path import java.nio.file.attribute.PosixFileAttributeView import java.nio.file.attribute.PosixFilePermission import java.util.* import java.util.concurrent.TimeUnit import javax.swing.SwingUtilities internal val LOG = logger<BuiltInWebServer>() private val notificationManager by lazy { SingletonNotificationManager(BuiltInServerManagerImpl.NOTIFICATION_GROUP, NotificationType.INFORMATION) } private val WEB_SERVER_PATH_HANDLER_EP_NAME = ExtensionPointName.create<WebServerPathHandler>("org.jetbrains.webServerPathHandler") class BuiltInWebServer : HttpRequestHandler() { override fun isAccessible(request: HttpRequest): Boolean { return BuiltInServerOptions.getInstance().builtInServerAvailableExternally || request.isLocalOrigin(onlyAnyOrLoopback = false, hostsOnly = true) } override fun isSupported(request: FullHttpRequest): Boolean = super.isSupported(request) || request.method() == HttpMethod.POST override fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean { var hostName = getHostName(request) ?: return false val projectName: String? val isIpv6 = hostName[0] == '[' && hostName.length > 2 && hostName[hostName.length - 1] == ']' if (isIpv6) { hostName = hostName.substring(1, hostName.length - 1) } if (isIpv6 || InetAddresses.isInetAddress(hostName) || isOwnHostName(hostName) || hostName.endsWith(".ngrok.io")) { if (urlDecoder.path().length < 2) { return false } projectName = null } else { if (hostName.endsWith(".localhost")) { projectName = hostName.substring(0, hostName.lastIndexOf('.')) } else { projectName = hostName } } return doProcess(urlDecoder, request, context, projectName) } } internal fun isActivatable() = Registry.`is`("ide.built.in.web.server.activatable", false) const val TOKEN_PARAM_NAME = "_ijt" const val TOKEN_HEADER_NAME = "x-ijt" private val STANDARD_COOKIE by lazy { val productName = ApplicationNamesInfo.getInstance().lowercaseProductName val configPath = PathManager.getConfigPath() val file = Path.of(configPath, USER_WEB_TOKEN) var token: String? = null if (file.exists()) { try { token = UUID.fromString(file.readText()).toString() } catch (e: Exception) { LOG.warn(e) } } if (token == null) { token = UUID.randomUUID().toString() file.write(token!!) Files.getFileAttributeView(file, PosixFileAttributeView::class.java) ?.setPermissions(EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)) } // explicit setting domain cookie on localhost doesn't work for chrome // http://stackoverflow.com/questions/8134384/chrome-doesnt-create-cookie-for-domain-localhost-in-broken-https val cookie = DefaultCookie(productName + "-" + Integer.toHexString(configPath.hashCode()), token!!) cookie.isHttpOnly = true cookie.setMaxAge(TimeUnit.DAYS.toSeconds(365 * 10)) cookie.setPath("/") cookie } // expire after access because we reuse tokens private val tokens = Caffeine.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build<String, Boolean>() fun acquireToken(): String { var token = tokens.asMap().keys.firstOrNull() if (token == null) { token = randomToken() tokens.put(token, java.lang.Boolean.TRUE) } return token } private fun doProcess(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext, projectNameAsHost: String?): Boolean { val decodedPath = urlDecoder.path() var offset: Int var isEmptyPath: Boolean val isCustomHost = projectNameAsHost != null var projectName: String if (isCustomHost) { projectName = projectNameAsHost!! // host mapped to us offset = 0 isEmptyPath = decodedPath.isEmpty() } else { offset = decodedPath.indexOf('/', 1) projectName = decodedPath.substring(1, if (offset == -1) decodedPath.length else offset) isEmptyPath = offset == -1 } val referer = request.headers().get(HttpHeaderNames.REFERER) val projectNameFromReferer = if (!isCustomHost && referer != null) { try { val uri = URI.create(referer) val refererPath = uri.path if (refererPath != null && refererPath.startsWith('/')) { val secondSlashOffset = refererPath.indexOf('/', 1) if (secondSlashOffset > 1) refererPath.substring(1, secondSlashOffset) else null } else null } catch (t: Throwable) { null } } else null var candidateByDirectoryName: Project? = null var isCandidateFromReferer = false val project = ProjectManager.getInstance().openProjects.firstOrNull(fun(project: Project): Boolean { if (project.isDisposed) { return false } val name = project.name if (isCustomHost) { // domain name is case-insensitive if (projectName.equals(name, ignoreCase = true)) { if (!SystemInfo.isFileSystemCaseSensitive) { // may be passed path is not correct projectName = name } return true } } else { // WEB-17839 Internal web server reports 404 when serving files from project with slashes in name if (decodedPath.regionMatches(1, name, 0, name.length, !SystemInfo.isFileSystemCaseSensitive)) { val isEmptyPathCandidate = decodedPath.length == (name.length + 1) if (isEmptyPathCandidate || decodedPath[name.length + 1] == '/') { projectName = name offset = name.length + 1 isEmptyPath = isEmptyPathCandidate return true } } } if (candidateByDirectoryName == null && compareNameAndProjectBasePath(projectName, project)) { candidateByDirectoryName = project } if (candidateByDirectoryName == null && projectNameFromReferer != null && (projectNameFromReferer == name || compareNameAndProjectBasePath(projectNameFromReferer, project))) { candidateByDirectoryName = project isCandidateFromReferer = true } return false }) ?: candidateByDirectoryName ?: return false if (isActivatable() && !PropertiesComponent.getInstance().getBoolean("ide.built.in.web.server.active")) { notificationManager.notify("", BuiltInServerBundle.message("notification.content.built.in.web.server.is.deactivated"), project) return false } if (isCandidateFromReferer) { projectName = projectNameFromReferer!! offset = 0 isEmptyPath = false } if (isEmptyPath) { // we must redirect "jsdebug" to "jsdebug/" as nginx does, otherwise browser will treat it as a file instead of a directory, so, relative path will not work redirectToDirectory(request, context.channel(), projectName, null) return true } val path = toIdeaPath(decodedPath, offset) if (path == null) { HttpResponseStatus.BAD_REQUEST.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(context.channel(), request) return true } for (pathHandler in WEB_SERVER_PATH_HANDLER_EP_NAME.extensionList) { LOG.runAndLogException { if (pathHandler.process(path, project, request, context, projectName, decodedPath, isCustomHost)) { return true } } } return false } fun HttpRequest.isSignedRequest(): Boolean { if (BuiltInServerOptions.getInstance().allowUnsignedRequests) { return true } // we must check referrer - if html cached, browser will send request without query val token = headers().get(TOKEN_HEADER_NAME) ?: QueryStringDecoder(uri()).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull() ?: referrer?.let { QueryStringDecoder(it).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull() } // we don't invalidate token - allow making subsequent requests using it (it is required for our javadoc DocumentationComponent) return token != null && tokens.getIfPresent(token) != null } fun validateToken(request: HttpRequest, channel: Channel, isSignedRequest: Boolean): HttpHeaders? { if (BuiltInServerOptions.getInstance().allowUnsignedRequests) { return EmptyHttpHeaders.INSTANCE } request.headers().get(HttpHeaderNames.COOKIE)?.let { for (cookie in ServerCookieDecoder.STRICT.decode(it)) { if (cookie.name() == STANDARD_COOKIE.name()) { if (cookie.value() == STANDARD_COOKIE.value()) { return EmptyHttpHeaders.INSTANCE } break } } } if (isSignedRequest) { return DefaultHttpHeaders().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(STANDARD_COOKIE) + "; SameSite=strict") } val urlDecoder = QueryStringDecoder(request.uri()) if (!urlDecoder.path().endsWith("/favicon.ico")) { val url = "${channel.uriScheme}://${request.host!!}${urlDecoder.path()}" SwingUtilities.invokeAndWait { ProjectUtil.focusProjectWindow(null, true) if (MessageDialogBuilder // escape - see https://youtrack.jetbrains.com/issue/IDEA-287428 .yesNo("", Strings.escapeXmlEntities(BuiltInServerBundle.message("dialog.message.page", StringUtil.trimMiddle(url, 50)))) .icon(Messages.getWarningIcon()) .yesText(BuiltInServerBundle.message("dialog.button.copy.authorization.url.to.clipboard")) .guessWindowAndAsk()) { CopyPasteManager.getInstance().setContents(StringSelection(url + "?" + TOKEN_PARAM_NAME + "=" + acquireToken())) } } } HttpResponseStatus.UNAUTHORIZED.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request) return null } private fun toIdeaPath(decodedPath: String, offset: Int): String? { // must be absolute path (relative to DOCUMENT_ROOT, i.e. scheme://authority/) to properly canonicalize val path = decodedPath.substring(offset) if (!path.startsWith('/')) { return null } return FileUtil.toCanonicalPath(path, '/').substring(1) } fun compareNameAndProjectBasePath(projectName: String, project: Project): Boolean { val basePath = project.basePath return basePath != null && endsWithName(basePath, projectName) } fun findIndexFile(basedir: VirtualFile): VirtualFile? { val children = basedir.children if (children.isNullOrEmpty()) { return null } for (indexNamePrefix in arrayOf("index.", "default.")) { var index: VirtualFile? = null val preferredName = indexNamePrefix + "html" for (child in children) { if (!child.isDirectory) { val name = child.name //noinspection IfStatementWithIdenticalBranches if (name == preferredName) { return child } else if (index == null && name.startsWith(indexNamePrefix)) { index = child } } } if (index != null) { return index } } return null } fun findIndexFile(basedir: Path): Path? { val children = basedir.directoryStreamIfExists({ val name = it.fileName.toString() name.startsWith("index.") || name.startsWith("default.") }) { it.toList() } ?: return null for (indexNamePrefix in arrayOf("index.", "default.")) { var index: Path? = null val preferredName = "${indexNamePrefix}html" for (child in children) { if (!child.isDirectory()) { val name = child.fileName.toString() if (name == preferredName) { return child } else if (index == null && name.startsWith(indexNamePrefix)) { index = child } } } if (index != null) { return index } } return null } // is host loopback/any or network interface address (i.e. not custom domain) // must be not used to check is host on local machine internal fun isOwnHostName(host: String): Boolean { if (NetUtils.isLocalhost(host)) { return true } try { val address = InetAddress.getByName(host) if (host == address.hostAddress || host.equals(address.canonicalHostName, ignoreCase = true)) { return true } val localHostName = InetAddress.getLocalHost().hostName // WEB-8889 // develar.local is own host name: develar. equals to "develar.labs.intellij.net" (canonical host name) return localHostName.equals(host, ignoreCase = true) || (host.endsWith(".local") && localHostName.regionMatches(0, host, 0, host.length - ".local".length, true)) } catch (ignored: IOException) { return false } }
apache-2.0
31f41ddf6fc5244fe00b78ead3deadf3
35.077114
165
0.711646
4.593918
false
false
false
false
k9mail/k-9
app/ui/legacy/src/main/java/com/fsck/k9/view/MessageCryptoDisplayStatus.kt
2
14674
package com.fsck.k9.view import androidx.annotation.AttrRes import androidx.annotation.DrawableRes import androidx.annotation.StringRes import com.fsck.k9.mailstore.CryptoResultAnnotation import com.fsck.k9.mailstore.CryptoResultAnnotation.CryptoError import com.fsck.k9.ui.R import org.openintents.openpgp.OpenPgpDecryptionResult.RESULT_ENCRYPTED import org.openintents.openpgp.OpenPgpDecryptionResult.RESULT_INSECURE import org.openintents.openpgp.OpenPgpDecryptionResult.RESULT_NOT_ENCRYPTED import org.openintents.openpgp.OpenPgpSignatureResult import org.openintents.openpgp.OpenPgpSignatureResult.RESULT_INVALID_KEY_EXPIRED import org.openintents.openpgp.OpenPgpSignatureResult.RESULT_INVALID_KEY_INSECURE import org.openintents.openpgp.OpenPgpSignatureResult.RESULT_INVALID_KEY_REVOKED import org.openintents.openpgp.OpenPgpSignatureResult.RESULT_INVALID_SIGNATURE import org.openintents.openpgp.OpenPgpSignatureResult.RESULT_KEY_MISSING import org.openintents.openpgp.OpenPgpSignatureResult.RESULT_NO_SIGNATURE import org.openintents.openpgp.OpenPgpSignatureResult.RESULT_VALID_KEY_CONFIRMED import org.openintents.openpgp.OpenPgpSignatureResult.RESULT_VALID_KEY_UNCONFIRMED import org.openintents.openpgp.OpenPgpSignatureResult.SenderStatusResult.UNKNOWN import org.openintents.openpgp.OpenPgpSignatureResult.SenderStatusResult.USER_ID_CONFIRMED import org.openintents.openpgp.OpenPgpSignatureResult.SenderStatusResult.USER_ID_MISSING import org.openintents.openpgp.OpenPgpSignatureResult.SenderStatusResult.USER_ID_UNCONFIRMED enum class MessageCryptoDisplayStatus( val isEnabled: Boolean = true, @AttrRes val colorAttr: Int, @DrawableRes val statusIconRes: Int, @StringRes val titleTextRes: Int? = null, @StringRes val descriptionTextRes: Int? = null ) { LOADING( isEnabled = false, colorAttr = R.attr.openpgp_grey, statusIconRes = R.drawable.status_lock_disabled ), CANCELLED( colorAttr = R.attr.openpgp_black, statusIconRes = R.drawable.status_lock_unknown, titleTextRes = R.string.crypto_msg_title_encrypted_unknown, descriptionTextRes = R.string.crypto_msg_cancelled ), DISABLED( isEnabled = false, colorAttr = R.attr.openpgp_grey, statusIconRes = R.drawable.status_lock_disabled, titleTextRes = R.string.crypto_msg_title_plaintext ), UNENCRYPTED_SIGN_ERROR( colorAttr = R.attr.openpgp_grey, statusIconRes = R.drawable.status_signature_unknown, titleTextRes = R.string.crypto_msg_title_plaintext, descriptionTextRes = R.string.crypto_msg_unencrypted_sign_error ), INCOMPLETE_SIGNED( colorAttr = R.attr.openpgp_black, statusIconRes = R.drawable.status_signature_unknown, titleTextRes = R.string.crypto_msg_title_plaintext, descriptionTextRes = R.string.crypto_msg_incomplete_signed ), UNENCRYPTED_SIGN_VERIFIED( colorAttr = R.attr.openpgp_blue, statusIconRes = R.drawable.status_signature_dots_3, titleTextRes = R.string.crypto_msg_title_unencrypted_signed_e2e, descriptionTextRes = R.string.crypto_msg_unencrypted_sign_verified ), UNENCRYPTED_SIGN_UNVERIFIED( colorAttr = R.attr.openpgp_blue, statusIconRes = R.drawable.status_signature, titleTextRes = R.string.crypto_msg_title_unencrypted_signed_e2e ), UNENCRYPTED_SIGN_UNKNOWN( colorAttr = R.attr.openpgp_orange, statusIconRes = R.drawable.status_signature_unknown, titleTextRes = R.string.crypto_msg_title_unencrypted_signed, descriptionTextRes = R.string.crypto_msg_unencrypted_sign_unknown ), UNENCRYPTED_SIGN_MISMATCH( colorAttr = R.attr.openpgp_grey, statusIconRes = R.drawable.status_signature_unknown, titleTextRes = R.string.crypto_msg_title_unencrypted_signed, descriptionTextRes = R.string.crypto_msg_unencrypted_sign_mismatch ), UNENCRYPTED_SIGN_EXPIRED( colorAttr = R.attr.openpgp_grey, statusIconRes = R.drawable.status_signature_unknown, titleTextRes = R.string.crypto_msg_title_unencrypted_signed, descriptionTextRes = R.string.crypto_msg_unencrypted_sign_expired ), UNENCRYPTED_SIGN_REVOKED( colorAttr = R.attr.openpgp_grey, statusIconRes = R.drawable.status_signature_unknown, titleTextRes = R.string.crypto_msg_title_unencrypted_signed, descriptionTextRes = R.string.crypto_msg_unencrypted_sign_revoked ), UNENCRYPTED_SIGN_INSECURE( colorAttr = R.attr.openpgp_grey, statusIconRes = R.drawable.status_signature_unknown, titleTextRes = R.string.crypto_msg_title_unencrypted_signed, descriptionTextRes = R.string.crypto_msg_unencrypted_sign_insecure ), ENCRYPTED_SIGN_VERIFIED( colorAttr = R.attr.openpgp_green, statusIconRes = R.drawable.status_lock_dots_3, titleTextRes = R.string.crypto_msg_title_encrypted_signed_e2e, descriptionTextRes = R.string.crypto_msg_encrypted_sign_verified ), ENCRYPTED_SIGN_UNVERIFIED( colorAttr = R.attr.openpgp_green, statusIconRes = R.drawable.status_lock, titleTextRes = R.string.crypto_msg_title_encrypted_signed_e2e ), ENCRYPTED_SIGN_UNKNOWN( colorAttr = R.attr.openpgp_orange, statusIconRes = R.drawable.status_lock_unknown, titleTextRes = R.string.crypto_msg_title_encrypted_signed, descriptionTextRes = R.string.crypto_msg_encrypted_sign_unknown ), ENCRYPTED_SIGN_MISMATCH( colorAttr = R.attr.openpgp_grey, statusIconRes = R.drawable.status_lock_error, titleTextRes = R.string.crypto_msg_title_encrypted_signed, descriptionTextRes = R.string.crypto_msg_encrypted_sign_mismatch ), ENCRYPTED_SIGN_EXPIRED( colorAttr = R.attr.openpgp_grey, statusIconRes = R.drawable.status_lock_error, titleTextRes = R.string.crypto_msg_title_encrypted_signed, descriptionTextRes = R.string.crypto_msg_encrypted_sign_expired ), ENCRYPTED_SIGN_REVOKED( colorAttr = R.attr.openpgp_grey, statusIconRes = R.drawable.status_lock_error, titleTextRes = R.string.crypto_msg_title_encrypted_signed, descriptionTextRes = R.string.crypto_msg_encrypted_sign_revoked ), ENCRYPTED_SIGN_INSECURE( colorAttr = R.attr.openpgp_grey, statusIconRes = R.drawable.status_lock_error, titleTextRes = R.string.crypto_msg_title_encrypted_signed, descriptionTextRes = R.string.crypto_msg_encrypted_sign_insecure ), ENCRYPTED_SIGN_ERROR( colorAttr = R.attr.openpgp_grey, statusIconRes = R.drawable.status_lock_error, titleTextRes = R.string.crypto_msg_title_encrypted_signed, descriptionTextRes = R.string.crypto_msg_encrypted_sign_error ), ENCRYPTED_INSECURE( colorAttr = R.attr.openpgp_red, statusIconRes = R.drawable.status_lock_error, titleTextRes = R.string.crypto_msg_title_encrypted_signed, descriptionTextRes = R.string.crypto_msg_encrypted_insecure ), ENCRYPTED_UNSIGNED( colorAttr = R.attr.openpgp_grey, statusIconRes = R.drawable.status_lock_error, titleTextRes = R.string.crypto_msg_title_encrypted_unsigned, descriptionTextRes = R.string.crypto_msg_encrypted_unsigned ), ENCRYPTED_ERROR( colorAttr = R.attr.openpgp_red, statusIconRes = R.drawable.status_lock_error, titleTextRes = R.string.crypto_msg_title_encrypted_unknown, descriptionTextRes = R.string.crypto_msg_encrypted_error ), INCOMPLETE_ENCRYPTED( colorAttr = R.attr.openpgp_black, statusIconRes = R.drawable.status_lock_unknown, titleTextRes = R.string.crypto_msg_title_encrypted_unknown, descriptionTextRes = R.string.crypto_msg_encrypted_incomplete ), ENCRYPTED_NO_PROVIDER( colorAttr = R.attr.openpgp_red, statusIconRes = R.drawable.status_lock_error, titleTextRes = R.string.crypto_msg_title_encrypted_unknown, descriptionTextRes = R.string.crypto_msg_encrypted_no_provider ), UNSUPPORTED_ENCRYPTED( colorAttr = R.attr.openpgp_red, statusIconRes = R.drawable.status_lock_error, titleTextRes = R.string.crypto_msg_title_encrypted_unknown, descriptionTextRes = R.string.crypto_msg_unsupported_encrypted ), UNSUPPORTED_SIGNED( colorAttr = R.attr.openpgp_grey, statusIconRes = R.drawable.status_lock_disabled, titleTextRes = R.string.crypto_msg_title_encrypted_unknown, descriptionTextRes = R.string.crypto_msg_unsupported_signed ); fun hasAssociatedKey(): Boolean { return when (this) { ENCRYPTED_SIGN_VERIFIED, ENCRYPTED_SIGN_UNVERIFIED, ENCRYPTED_SIGN_MISMATCH, ENCRYPTED_SIGN_EXPIRED, ENCRYPTED_SIGN_REVOKED, ENCRYPTED_SIGN_INSECURE, UNENCRYPTED_SIGN_VERIFIED, UNENCRYPTED_SIGN_UNVERIFIED, UNENCRYPTED_SIGN_MISMATCH, UNENCRYPTED_SIGN_EXPIRED, UNENCRYPTED_SIGN_REVOKED, UNENCRYPTED_SIGN_INSECURE -> true else -> false } } val isUnencryptedSigned: Boolean get() = when (this) { UNENCRYPTED_SIGN_ERROR, UNENCRYPTED_SIGN_UNKNOWN, UNENCRYPTED_SIGN_VERIFIED, UNENCRYPTED_SIGN_UNVERIFIED, UNENCRYPTED_SIGN_MISMATCH, UNENCRYPTED_SIGN_EXPIRED, UNENCRYPTED_SIGN_REVOKED, UNENCRYPTED_SIGN_INSECURE -> true else -> false } val isUnknownKey: Boolean get() = when (this) { ENCRYPTED_SIGN_UNKNOWN, UNENCRYPTED_SIGN_UNKNOWN -> true else -> false } companion object { @JvmStatic fun fromResultAnnotation(cryptoResult: CryptoResultAnnotation?): MessageCryptoDisplayStatus { return when (cryptoResult?.errorType) { null -> DISABLED CryptoError.OPENPGP_OK -> getDisplayStatusForPgpResult(cryptoResult) CryptoError.OPENPGP_ENCRYPTED_BUT_INCOMPLETE -> INCOMPLETE_ENCRYPTED CryptoError.OPENPGP_SIGNED_BUT_INCOMPLETE -> INCOMPLETE_SIGNED CryptoError.ENCRYPTED_BUT_UNSUPPORTED -> UNSUPPORTED_ENCRYPTED CryptoError.SIGNED_BUT_UNSUPPORTED -> UNSUPPORTED_SIGNED CryptoError.OPENPGP_UI_CANCELED -> CANCELLED CryptoError.OPENPGP_SIGNED_API_ERROR -> UNENCRYPTED_SIGN_ERROR CryptoError.OPENPGP_ENCRYPTED_API_ERROR -> ENCRYPTED_ERROR CryptoError.OPENPGP_ENCRYPTED_NO_PROVIDER -> ENCRYPTED_NO_PROVIDER else -> error("Unhandled case!") } } private fun getDisplayStatusForPgpResult(cryptoResult: CryptoResultAnnotation): MessageCryptoDisplayStatus { var signatureResult = cryptoResult.openPgpSignatureResult val decryptionResult = cryptoResult.openPgpDecryptionResult if (decryptionResult == null || signatureResult == null) { throw AssertionError("Both OpenPGP results must be non-null at this point!") } if (signatureResult.result == RESULT_NO_SIGNATURE && cryptoResult.hasEncapsulatedResult()) { val encapsulatedResult = cryptoResult.encapsulatedResult if (encapsulatedResult.isOpenPgpResult) { signatureResult = encapsulatedResult.openPgpSignatureResult ?: throw AssertionError("OpenPGP must contain signature result at this point!") } } return when (decryptionResult.getResult()) { RESULT_NOT_ENCRYPTED -> getStatusForPgpUnencryptedResult(signatureResult) RESULT_ENCRYPTED -> getStatusForPgpEncryptedResult(signatureResult) RESULT_INSECURE -> ENCRYPTED_INSECURE else -> throw AssertionError("all cases must be handled, this is a bug!") } } private fun getStatusForPgpEncryptedResult( signatureResult: OpenPgpSignatureResult ): MessageCryptoDisplayStatus { return when (signatureResult.result) { RESULT_NO_SIGNATURE -> ENCRYPTED_UNSIGNED RESULT_VALID_KEY_CONFIRMED, RESULT_VALID_KEY_UNCONFIRMED -> { return when (signatureResult.senderStatusResult) { USER_ID_CONFIRMED -> ENCRYPTED_SIGN_VERIFIED USER_ID_UNCONFIRMED -> ENCRYPTED_SIGN_UNVERIFIED USER_ID_MISSING -> ENCRYPTED_SIGN_MISMATCH UNKNOWN -> ENCRYPTED_SIGN_UNVERIFIED else -> error("unhandled encrypted result case!") } } RESULT_KEY_MISSING -> ENCRYPTED_SIGN_UNKNOWN RESULT_INVALID_SIGNATURE -> ENCRYPTED_SIGN_ERROR RESULT_INVALID_KEY_EXPIRED -> ENCRYPTED_SIGN_EXPIRED RESULT_INVALID_KEY_REVOKED -> ENCRYPTED_SIGN_REVOKED RESULT_INVALID_KEY_INSECURE -> ENCRYPTED_SIGN_INSECURE else -> error("unhandled encrypted result case!") } } private fun getStatusForPgpUnencryptedResult( signatureResult: OpenPgpSignatureResult ): MessageCryptoDisplayStatus { return when (signatureResult.result) { RESULT_NO_SIGNATURE -> DISABLED RESULT_VALID_KEY_CONFIRMED, RESULT_VALID_KEY_UNCONFIRMED -> { return when (signatureResult.senderStatusResult) { USER_ID_CONFIRMED -> UNENCRYPTED_SIGN_VERIFIED USER_ID_UNCONFIRMED -> UNENCRYPTED_SIGN_UNVERIFIED USER_ID_MISSING -> UNENCRYPTED_SIGN_MISMATCH UNKNOWN -> UNENCRYPTED_SIGN_UNVERIFIED else -> error("unhandled encrypted result case!") } } RESULT_KEY_MISSING -> UNENCRYPTED_SIGN_UNKNOWN RESULT_INVALID_SIGNATURE -> UNENCRYPTED_SIGN_ERROR RESULT_INVALID_KEY_EXPIRED -> UNENCRYPTED_SIGN_EXPIRED RESULT_INVALID_KEY_REVOKED -> UNENCRYPTED_SIGN_REVOKED RESULT_INVALID_KEY_INSECURE -> UNENCRYPTED_SIGN_INSECURE else -> error("unhandled encrypted result case!") } } } }
apache-2.0
d7aaa96ef1fb8f2a770ee7ac38e48499
44.150769
116
0.667439
4.358182
false
false
false
false
PolymerLabs/arcs
java/arcs/android/storage/StoreOptionsProto.kt
1
1166
package arcs.android.storage import arcs.android.util.decodeProto import arcs.core.data.proto.decode import arcs.core.data.proto.encode import arcs.core.storage.StorageKeyManager import arcs.core.storage.StoreOptions import com.google.protobuf.StringValue /** Constructs a [StoreOptions] from the given [StoreOptionsProto]. */ fun StoreOptionsProto.decode(): StoreOptions { return StoreOptions( storageKey = StorageKeyManager.GLOBAL_INSTANCE.parse(storageKey), type = type.decode(), versionToken = if (hasVersionToken()) versionToken.value else null, writeOnly = writeOnly ) } /** Serializes a [StoreOptions] to its proto form. */ fun StoreOptions.toProto(): StoreOptionsProto { val proto = StoreOptionsProto.newBuilder() .setStorageKey(storageKey.toString()) .setType(type.encode()) .setWriteOnly(writeOnly) // Convert nullable String to StringValue. versionToken?.let { proto.setVersionToken(StringValue.of(it)) } return proto.build() } /** Decodes a [StoreOptions] from the [ByteArray]. */ fun ByteArray.decodeStoreOptions(): StoreOptions { return decodeProto(this, StoreOptionsProto.getDefaultInstance()).decode() }
bsd-3-clause
627e7e88798b0fab45cdc13b45dd0f72
33.294118
75
0.763293
4.24
false
false
false
false
unic/sledge
src/main/kotlin/io/sledge/deployer/crx/PackageManagerCommand.kt
1
1258
package io.sledge.deployer.crx import io.sledge.deployer.core.exception.SledgeCommandException import io.sledge.deployer.http.SledgeHttpResponse const val PATH = "/crx/packmgr/service" const val SERVICE_JSP = "$PATH.jsp" data class Command(val commandName: String, val cmdParam: String, val responseValidationConditions: Set<String>) { fun validate(response: SledgeHttpResponse) { val responseBody = response.bodayAsString if (responseValidationConditions.any { it in responseBody }) else { throw SledgeCommandException("Response did not contain expected validation text.", url(), response.statusCode, responseBody) } } fun url(): String { return "$SERVICE_JSP?cmd=$cmdParam" } } val Upload = Command(commandName = "Upload", cmdParam = "upload", responseValidationConditions = setOf("200")) val Install = Command(commandName = "Install", cmdParam = "inst", responseValidationConditions = setOf("Package installed")) val Uninstall = Command(commandName = "Uninstall", cmdParam = "uninst", responseValidationConditions = setOf("Package uninstalled", "does not exist")) val Delete = Command(commandName = "Delete", cmdParam = "rm", responseValidationConditions = setOf("200", "does not exist"))
apache-2.0
41bc6f42fb8823d8f9bafacf0977d1be
47.384615
150
0.737679
4.221477
false
false
false
false
iskandar1023/template
app/src/main/kotlin/substratum/theme/template/ThemeFunctions.kt
1
5750
package substratum.theme.template import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageManager import android.content.pm.Signature import android.os.RemoteException import substratum.theme.template.AdvancedConstants.BLACKLISTED_APPLICATIONS import substratum.theme.template.AdvancedConstants.ORGANIZATION_THEME_SYSTEMS import substratum.theme.template.AdvancedConstants.OTHER_THEME_SYSTEMS @Suppress("ConstantConditionIf") object ThemeFunctions { fun isCallingPackageAllowed(packageId: String): Boolean { if (BuildConfig.SUPPORTS_THIRD_PARTY_SYSTEMS) { OTHER_THEME_SYSTEMS.contains(packageId) } return ORGANIZATION_THEME_SYSTEMS.contains(packageId) } fun getSelfVerifiedPirateTools(context: Context): Boolean { val pm = context.packageManager val packages = pm.getInstalledApplications(PackageManager.GET_META_DATA) val listOfInstalled = arrayListOf<String>() packages.mapTo(listOfInstalled) { it.packageName } return BLACKLISTED_APPLICATIONS.any { listOfInstalled.contains(it) } } @Suppress("DEPRECATION") @SuppressLint("PackageManagerGetSignatures") fun checkApprovedSignature(context: Context, packageName: String): Boolean { SIGNATURES.filter { try { val pm = context.packageManager val pi = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES) if (pi.signatures != null && pi.signatures.size == 1 && ((SIGNATURES[0] == pi.signatures[0]) || (SIGNATURES[1] == pi.signatures[0]))) { return true } return false } catch (e: RemoteException) { return false } }.forEach { return true } return false } @Suppress("DEPRECATION") @SuppressLint("PackageManagerGetSignatures") fun getSelfSignature(context: Context): Int { try { val sigs = context.packageManager.getPackageInfo( context.packageName, PackageManager.GET_SIGNATURES ).signatures return sigs[0].hashCode() } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return 0 } // Enforce a way to get official support from the team, by ensuring that only private val SUBSTRATUM_SIGNATURE = Signature("" + "308202eb308201d3a003020102020411c02f2f300d06092a864886f70d01010b050030263124302206" + "03550403131b5375627374726174756d20446576656c6f706d656e74205465616d301e170d31363037" + "30333032333335385a170d3431303632373032333335385a3026312430220603550403131b53756273" + "74726174756d20446576656c6f706d656e74205465616d30820122300d06092a864886f70d01010105" + "000382010f003082010a02820101008855626336f645a335aa5d40938f15db911556385f72f72b5f8b" + "ad01339aaf82ae2d30302d3f2bba26126e8da8e76a834e9da200cdf66d1d5977c90a4e4172ce455704" + "a22bbe4a01b08478673b37d23c34c8ade3ec040a704da8570d0a17fce3c7397ea63ebcde3a2a3c7c5f" + "983a163e4cd5a1fc80c735808d014df54120e2e5708874739e22e5a22d50e1c454b2ae310b480825ab" + "3d877f675d6ac1293222602a53080f94e4a7f0692b627905f69d4f0bb1dfd647e281cc0695e0733fa3" + "efc57d88706d4426c4969aff7a177ac2d9634401913bb20a93b6efe60e790e06dad3493776c2c0878c" + "e82caababa183b494120edde3d823333efd464c8aea1f51f330203010001a321301f301d0603551d0e" + "04160414203ec8b075d1c9eb9d600100281c3924a831a46c300d06092a864886f70d01010b05000382" + "01010042d4bd26d535ce2bf0375446615ef5bf25973f61ecf955bdb543e4b6e6b5d026fdcab09fec09" + "c747fb26633c221df8e3d3d0fe39ce30ca0a31547e9ec693a0f2d83e26d231386ff45f8e4fd5c06095" + "8681f9d3bd6db5e940b1e4a0b424f5c463c79c5748a14a3a38da4dd7a5499dcc14a70ba82a50be5fe0" + "82890c89a27e56067d2eae952e0bcba4d6beb5359520845f1fdb7df99868786055555187ba46c69ee6" + "7fa2d2c79e74a364a8b3544997dc29cc625395e2f45bf8bdb2c9d8df0d5af1a59a58ad08b32cdbec38" + "19fa49201bb5b5aadeee8f2f096ac029055713b77054e8af07cd61fe97f7365d0aa92d570be98acb89" + "41b8a2b0053b54f18bfde092eb") // Also allow our CI builds private val SUBSTRATUM_CI_SIGNATURE = Signature("" + "308201dd30820146020101300d06092a864886f70d010105050030373116301406035504030c0d416e" + "64726f69642044656275673110300e060355040a0c07416e64726f6964310b30090603550406130255" + "53301e170d3137303232333036303730325a170d3437303231363036303730325a3037311630140603" + "5504030c0d416e64726f69642044656275673110300e060355040a0c07416e64726f6964310b300906" + "035504061302555330819f300d06092a864886f70d010101050003818d00308189028181008aa6cf56" + "e3ba4d0921da3baf527529205efbe440e1f351c40603afa5e6966e6a6ef2def780c8be80d189dc6101" + "935e6f8340e61dc699cfd34d50e37d69bf66fbb58619d0ebf66f22db5dbe240b6087719aa3ceb1c68f" + "3fa277b8846f1326763634687cc286b0760e51d1b791689fa2d948ae5f31cb8e807e00bd1eb72788b2" + "330203010001300d06092a864886f70d0101050500038181007b2b7e432bff612367fbb6fdf8ed0ad1" + "a19b969e4c4ddd8837d71ae2ec0c35f52fe7c8129ccdcdc41325f0bcbc90c38a0ad6fc0c604a737209" + "17d37421955c47f9104ea56ad05031b90c748b94831969a266fa7c55bc083e20899a13089402be49a5" + "edc769811adc2b0496a8a066924af9eeb33f8d57d625a5fa150f7bc18e55") // Whitelisted signatures private val SIGNATURES = arrayOf( SUBSTRATUM_SIGNATURE, SUBSTRATUM_CI_SIGNATURE ) }
apache-2.0
f46aa97e48d13fb0b047df9cf8941ae4
52.25
98
0.739478
2.957819
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/ui/fragments/favorites/FavoritesFragment.kt
1
12118
package forpdateam.ru.forpda.ui.fragments.favorites import android.app.Dialog import android.os.Bundle import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.tabs.TabLayout import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.LinearLayoutManager import android.util.Log import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.ArrayAdapter import android.widget.Button import android.widget.Spinner import android.widget.Toast import moxy.presenter.InjectPresenter import moxy.presenter.ProvidePresenter import java.util.Arrays import forpdateam.ru.forpda.App import forpdateam.ru.forpda.R import forpdateam.ru.forpda.entity.remote.favorites.FavData import forpdateam.ru.forpda.entity.remote.favorites.FavItem import forpdateam.ru.forpda.model.data.remote.api.favorites.FavoritesApi import forpdateam.ru.forpda.model.data.remote.api.favorites.Sorting import forpdateam.ru.forpda.presentation.favorites.FavoritesPresenter import forpdateam.ru.forpda.presentation.favorites.FavoritesView import forpdateam.ru.forpda.ui.fragments.RecyclerFragment import forpdateam.ru.forpda.ui.views.ContentController import forpdateam.ru.forpda.ui.views.DynamicDialogMenu import forpdateam.ru.forpda.ui.views.FunnyContent import forpdateam.ru.forpda.ui.views.adapters.BaseSectionedAdapter import forpdateam.ru.forpda.ui.views.pagination.PaginationHelper /** * Created by radiationx on 22.09.16. */ class FavoritesFragment : RecyclerFragment(), FavoritesView { private lateinit var dialogMenu: DynamicDialogMenu<FavoritesFragment, FavItem> private lateinit var adapter: FavoritesAdapter private lateinit var paginationHelper: PaginationHelper private lateinit var dialog: BottomSheetDialog private lateinit var sortingView: ViewGroup private lateinit var keySpinner: Spinner private lateinit var orderSpinner: Spinner private lateinit var sortApply: Button private lateinit var sortReset: Button private val paginationListener = object : PaginationHelper.PaginationListener { override fun onTabSelected(tab: TabLayout.Tab): Boolean { return refreshLayout.isRefreshing } override fun onSelectedPage(pageNumber: Int) { presenter.loadFavorites(pageNumber) } } private val adapterListener = object : BaseSectionedAdapter.OnItemClickListener<FavItem> { override fun onItemClick(item: FavItem) { presenter.onItemClick(item) } override fun onItemLongClick(item: FavItem): Boolean { presenter.onItemLongClick(item) return false } } @InjectPresenter lateinit var presenter: FavoritesPresenter @ProvidePresenter internal fun providePresenter(): FavoritesPresenter { return FavoritesPresenter( App.get().Di().favoritesRepository, App.get().Di().forumRepository, App.get().Di().eventsRepository, App.get().Di().listsPreferencesHolder, App.get().Di().notificationPreferencesHolder, App.get().Di().crossScreenInteractor, App.get().Di().router, App.get().Di().linkHandler, App.get().Di().countersHolder, App.get().Di().errorHandler ) } init { configuration.defaultTitle = App.get().getString(R.string.fragment_title_favorite) } private fun getPinText(b: Boolean): CharSequence { return getString(if (b) R.string.fav_unpin else R.string.fav_pin) } private fun getSubText(subTypeIndex: Int): CharSequence { return String.format("%s (%s)", getString(R.string.fav_change_subscribe_type), SUB_NAMES[subTypeIndex]) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) sortingView = View.inflate(context, R.layout.favorite_sorting, null) as ViewGroup keySpinner = sortingView.findViewById<View>(R.id.sorting_key) as Spinner orderSpinner = sortingView.findViewById<View>(R.id.sorting_order) as Spinner sortApply = sortingView.findViewById<View>(R.id.sorting_apply) as Button sortReset = sortingView.findViewById(R.id.sorting_reset) dialog = BottomSheetDialog(context!!) dialog.setOnShowListener { dialog1 -> (dialog1 as Dialog).window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) } paginationHelper = PaginationHelper(activity) paginationHelper.addInToolbar(inflater, toolbarLayout, configuration.isFitSystemWindow) contentController.setFirstLoad(false) return viewFragment } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) dialogMenu = DynamicDialogMenu() dialogMenu.apply { addItem(getString(R.string.copy_link)) { _, data -> presenter.copyLink(data) } addItem(getString(R.string.attachments)) { _, data -> presenter.openAttachments(data) } addItem(getString(R.string.open_theme_forum)) { _, data -> presenter.openForum(data) } addItem(getString(R.string.fav_change_subscribe_type)) { _, data -> presenter.showSubscribeDialog(data) } addItem(getPinText(false)) { _, data -> presenter.changeFav(FavoritesApi.ACTION_EDIT_PIN_STATE, if (data.isPin) "unpin" else "pin", data.favId) } addItem(getString(R.string.delete)) { _, data -> presenter.changeFav(FavoritesApi.ACTION_DELETE, null, data.favId) } } refreshLayout.setOnRefreshListener { presenter.refresh() } recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) adapter = FavoritesAdapter() adapter.setOnItemClickListener(adapterListener) recyclerView.adapter = adapter paginationHelper.setListener(paginationListener) initSpinnerItems(keySpinner, arrayOf(getString(R.string.fav_sort_last_post), getString(R.string.fav_sort_title))) initSpinnerItems(orderSpinner, arrayOf(getString(R.string.sorting_asc), getString(R.string.sorting_desc))) sortApply.setOnClickListener { val key = when (keySpinner.selectedItemPosition) { 0 -> Sorting.Key.LAST_POST 1 -> Sorting.Key.TITLE else -> "" } val order = when (orderSpinner.selectedItemPosition) { 0 -> Sorting.Order.ASC 1 -> Sorting.Order.DESC else -> "" } presenter.updateSorting(key, order) dialog.dismiss() } sortReset.setOnClickListener { presenter.updateSorting("", "") dialog.dismiss() } presenter.refresh() } override fun isShadowVisible(): Boolean { return true } override fun addBaseToolbarMenu(menu: Menu) { super.addBaseToolbarMenu(menu) menu.add(R.string.sorting_title) .setIcon(R.drawable.ic_toolbar_sort) .setOnMenuItemClickListener { hideKeyboard() if (sortingView.parent != null && sortingView.parent is ViewGroup) { (sortingView.parent as ViewGroup).removeView(sortingView) } dialog.setContentView(sortingView) dialog.show() false } .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS) } override fun onMarkAllRead() { Toast.makeText(context, R.string.action_complete, Toast.LENGTH_SHORT).show() } override fun onLoadFavorites(data: FavData) { Log.e("kjkjkj", "onLoadFavorites") selectSpinners(data.sorting) paginationHelper.updatePagination(data.pagination) setSubtitle(paginationHelper.title) } override fun setShowDot(enabled: Boolean) { adapter.setShowDot(enabled) } override fun setUnreadTop(unreadTop: Boolean) { adapter.setUnreadTop(unreadTop) } override fun onShowFavorite(items: List<FavItem>) { Log.e("kjkjkj", "onShowFavorite") if (items.isEmpty()) { if (!contentController.contains(ContentController.TAG_NO_DATA)) { val funnyContent = FunnyContent(context) .setImage(R.drawable.ic_star) .setTitle(R.string.funny_favorites_nodata_title) .setDesc(R.string.funny_favorites_nodata_desc) contentController.addContent(funnyContent, ContentController.TAG_NO_DATA) } contentController.showContent(ContentController.TAG_NO_DATA) } else { contentController.hideContent(ContentController.TAG_NO_DATA) } adapter.bindItems(items) } override fun initSorting(sorting: Sorting) { selectSpinners(sorting) } private fun selectSpinners(sorting: Sorting) { when (sorting.key) { Sorting.Key.LAST_POST -> keySpinner.setSelection(0) Sorting.Key.TITLE -> keySpinner.setSelection(1) } when (sorting.order) { Sorting.Order.ASC -> orderSpinner.setSelection(0) Sorting.Order.DESC -> orderSpinner.setSelection(1) } } private fun initSpinnerItems(spinner: Spinner, items: Array<String>) { val adapter = ArrayAdapter(activity!!, android.R.layout.simple_spinner_item, items) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner.adapter = adapter spinner.setSelection(0) } override fun onDestroy() { super.onDestroy() paginationHelper.destroy() } override fun onChangeFav(result: Boolean) { Toast.makeText(context, R.string.action_complete, Toast.LENGTH_SHORT).show() } override fun showSubscribeDialog(item: FavItem) { val subTypeIndex = Arrays.asList(*FavoritesApi.SUB_TYPES).indexOf(item.subType) AlertDialog.Builder(context!!) .setTitle(R.string.favorites_subscribe_email) .setSingleChoiceItems(FavoritesFragment.SUB_NAMES, subTypeIndex) { dialog, which -> presenter.changeFav(FavoritesApi.ACTION_EDIT_SUB_TYPE, FavoritesApi.SUB_TYPES[which], item.favId) dialog.dismiss() } .show() } override fun showItemDialogMenu(item: FavItem) { dialogMenu.apply { disallowAll() allow(0) if (!item.isForum) { allow(1) allow(2) } allow(3) allow(4) allow(5) val index = containsIndex(getPinText(!item.isPin)) if (index != -1) changeTitle(index, getPinText(item.isPin)) val subTypeIndex = Arrays.asList(*FavoritesApi.SUB_TYPES).indexOf(item.subType) changeTitle(3, getSubText(subTypeIndex)) show(context, this@FavoritesFragment, item) } } companion object { @JvmField var SUB_NAMES = arrayOf<CharSequence>( App.get().getString(R.string.fav_subscribe_none), App.get().getString(R.string.fav_subscribe_delayed), App.get().getString(R.string.fav_subscribe_immediate), App.get().getString(R.string.fav_subscribe_daily), App.get().getString(R.string.fav_subscribe_weekly), App.get().getString(R.string.fav_subscribe_pinned) ) } }
gpl-3.0
07048c8108136c46221d37943b99a30b
36.987461
121
0.649695
4.595374
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/compose/theme/AppTheme.kt
1
1415
package org.wordpress.android.ui.compose.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.runtime.Composable import org.wordpress.android.BuildConfig /** * This theme should be used to support light/dark colors if the root composable does not support * [contentColor](https://developer.android.com/jetpack/compose/themes/material#content-color). */ @Composable fun AppTheme( isDarkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { AppThemeWithoutBackground(isDarkTheme) { ContentInSurface(content) } } /** * Use this theme only when the root composable supports * [contentColor](https://developer.android.com/jetpack/compose/themes/material#content-color). * Otherwise use [AppTheme]. */ @Composable fun AppThemeWithoutBackground( isDarkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colorPalette = when (BuildConfig.IS_JETPACK_APP) { true -> JpColorPalette(isDarkTheme) else -> WpColorPalette(isDarkTheme) } MaterialTheme( colors = colorPalette, content = content ) } @Composable private fun ContentInSurface( content: @Composable () -> Unit ) { Surface(color = MaterialTheme.colors.background) { content() } }
gpl-2.0
0b9018603f23c8b2009256f8ee5f1ebd
26.745098
97
0.721555
4.39441
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/main/MeViewModel.kt
1
6197
package org.wordpress.android.ui.main import android.annotation.SuppressLint import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.map import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import org.wordpress.android.BuildConfig import org.wordpress.android.WordPress import org.wordpress.android.models.recommend.RecommendApiCallsProvider import org.wordpress.android.models.recommend.RecommendApiCallsProvider.RecommendAppName import org.wordpress.android.models.recommend.RecommendApiCallsProvider.RecommendCallResult import org.wordpress.android.models.recommend.RecommendApiCallsProvider.RecommendCallResult.Failure import org.wordpress.android.models.recommend.RecommendApiCallsProvider.RecommendCallResult.Success import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.mysite.SelectedSiteRepository import org.wordpress.android.util.analytics.AnalyticsUtils.RecommendAppSource.ME import org.wordpress.android.ui.recommend.RecommendAppState import org.wordpress.android.ui.recommend.RecommendAppState.ApiFetchedResult import org.wordpress.android.ui.recommend.RecommendAppState.FetchingApi import org.wordpress.android.util.analytics.AnalyticsUtilsWrapper import org.wordpress.android.viewmodel.Event import org.wordpress.android.viewmodel.ScopedViewModel import javax.inject.Inject import javax.inject.Named @HiltViewModel class MeViewModel @Inject constructor( @Named(UI_THREAD) mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) val bgDispatcher: CoroutineDispatcher, private val selectedSiteRepository: SelectedSiteRepository, private val recommendApiCallsProvider: RecommendApiCallsProvider, private val analyticsUtilsWrapper: AnalyticsUtilsWrapper ) : ScopedViewModel(mainDispatcher) { private val _showDisconnectDialog = MutableLiveData<Event<Boolean>>() val showDisconnectDialog: LiveData<Event<Boolean>> = _showDisconnectDialog private val _recommendUiState = MutableLiveData<RecommendAppState>() val recommendUiState: LiveData<Event<RecommendAppUiState>> = _recommendUiState.map { it.toUiState() } private val _showUnifiedAbout = MutableLiveData<Event<Boolean>>() val showUnifiedAbout: LiveData<Event<Boolean>> = _showUnifiedAbout private val _showScanLoginCode = MutableLiveData<Event<Boolean>>() val showScanLoginCode: LiveData<Event<Boolean>> = _showScanLoginCode private val _showJetpackPoweredBottomSheet = MutableLiveData<Event<Boolean>>() val showJetpackPoweredBottomSheet: LiveData<Event<Boolean>> = _showJetpackPoweredBottomSheet data class RecommendAppUiState( val showLoading: Boolean = false, val error: String? = null, val message: String, val link: String ) { constructor(showLoading: Boolean) : this( showLoading = showLoading, message = "", link = "" ) constructor(error: String) : this( error = error, message = "", link = "" ) fun isError() = error != null } fun signOutWordPress(application: WordPress) { launch { _showDisconnectDialog.value = Event(true) withContext(bgDispatcher) { application.wordPressComSignOut() } _showDisconnectDialog.value = Event(false) } } fun openDisconnectDialog() { _showDisconnectDialog.value = Event(true) } fun getSite() = selectedSiteRepository.getSelectedSite() fun showUnifiedAbout() { _showUnifiedAbout.value = Event(true) } fun showScanLoginCode() { _showScanLoginCode.value = Event(true) } fun showJetpackPoweredBottomSheet() { _showJetpackPoweredBottomSheet.value = Event(true) } @SuppressLint("NullSafeMutableLiveData") fun onRecommendTheApp() { when (val state = _recommendUiState.value) { is ApiFetchedResult -> { if (state.isError()) { getRecommendTemplate() } else { _recommendUiState.value = state } } FetchingApi -> { return } null -> { getRecommendTemplate() } } } private fun getRecommendTemplate() { launch { _recommendUiState.value = FetchingApi withContext(bgDispatcher) { delay(SHOW_LOADING_DELAY) val fetchedResult = recommendApiCallsProvider.getRecommendTemplate( if (BuildConfig.IS_JETPACK_APP) { RecommendAppName.Jetpack.appName } else { RecommendAppName.WordPress.appName }, ME ).toFetchedResult() _recommendUiState.postValue(fetchedResult) } } } private fun RecommendCallResult.toFetchedResult(): ApiFetchedResult { return when (this) { is Failure -> ApiFetchedResult(error = this.error) is Success -> ApiFetchedResult( message = this.templateData.message, link = this.templateData.link ) } } private fun RecommendAppState.toUiState(): Event<RecommendAppUiState> { return Event(when (this) { is ApiFetchedResult -> if (this.isError()) { RecommendAppUiState(this.error!!) } else { RecommendAppUiState( link = this.link, message = this.message ).also { analyticsUtilsWrapper.trackRecommendAppEngaged(ME) } } FetchingApi -> RecommendAppUiState(showLoading = true) }) } companion object { private const val SHOW_LOADING_DELAY = 300L } }
gpl-2.0
4fccbe34c3f1cfb905a6215b8ec78268
35.452941
105
0.657576
5.198826
false
false
false
false
ingokegel/intellij-community
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/WorkspaceModelImpl.kt
1
6809
// 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.workspaceModel.ide.impl import com.intellij.diagnostic.StartUpMeasurer.startActivity import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.workspaceModel.ide.* import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.VersionedEntityStorageImpl import com.intellij.workspaceModel.storage.impl.assertConsistency import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import kotlin.system.measureTimeMillis open class WorkspaceModelImpl(private val project: Project) : WorkspaceModel, Disposable { @Volatile var loadedFromCache = false private set final override val entityStorage: VersionedEntityStorageImpl val entityTracer: EntityTracingLogger = EntityTracingLogger() var userWarningLoggingLevel = false @TestOnly set init { log.debug { "Loading workspace model" } val initialContent = WorkspaceModelInitialTestContent.pop() val cache = WorkspaceModelCache.getInstance(project) val projectEntities: MutableEntityStorage = when { initialContent != null -> initialContent.toBuilder() cache != null -> { val activity = startActivity("cache loading") val previousStorage: MutableEntityStorage? val loadingCacheTime = measureTimeMillis { previousStorage = cache.loadCache()?.toBuilder() } val storage = if (previousStorage == null) { MutableEntityStorage.create() } else { log.info("Load workspace model from cache in $loadingCacheTime ms") loadedFromCache = true entityTracer.printInfoAboutTracedEntity(previousStorage, "cache") previousStorage } activity.end() storage } else -> MutableEntityStorage.create() } @Suppress("LeakingThis") prepareModel(project, projectEntities) entityStorage = VersionedEntityStorageImpl(projectEntities.toSnapshot()) entityTracer.subscribe(project) } /** * Used only in Rider IDE */ @ApiStatus.Internal open fun prepareModel(project: Project, storage: MutableEntityStorage) = Unit fun ignoreCache() { loadedFromCache = false } final override fun <R> updateProjectModel(updater: (MutableEntityStorage) -> R): R { ApplicationManager.getApplication().assertWriteAccessAllowed() val before = entityStorage.current val builder = MutableEntityStorage.from(before) val result = updater(builder) startPreUpdateHandlers(before, builder) val changes = builder.collectChanges(before) val newStorage = builder.toSnapshot() if (Registry.`is`("ide.workspace.model.assertions.on.update", false)) { before.assertConsistency() newStorage.assertConsistency() } entityStorage.replace(newStorage, changes, this::onBeforeChanged, this::onChanged) return result } final override fun <R> updateProjectModelSilent(updater: (MutableEntityStorage) -> R): R { val before = entityStorage.current val builder = MutableEntityStorage.from(entityStorage.current) val result = updater(builder) val newStorage = builder.toSnapshot() if (Registry.`is`("ide.workspace.model.assertions.on.update", false)) { before.assertConsistency() newStorage.assertConsistency() } entityStorage.replaceSilently(newStorage) return result } final override fun getBuilderSnapshot(): BuilderSnapshot { val current = entityStorage.pointer return BuilderSnapshot(current.version, current.storage) } final override fun replaceProjectModel(replacement: StorageReplacement): Boolean { ApplicationManager.getApplication().assertWriteAccessAllowed() if (entityStorage.version != replacement.version) return false entityStorage.replace(replacement.snapshot, replacement.changes, this::onBeforeChanged, this::onChanged) return true } final override fun dispose() = Unit private fun onBeforeChanged(change: VersionedStorageChange) { ApplicationManager.getApplication().assertWriteAccessAllowed() if (project.isDisposed) return /** * Order of events: initialize project libraries, initialize module bridge + module friends, all other listeners */ val workspaceModelTopics = WorkspaceModelTopics.getInstance(project) logErrorOnEventHandling { workspaceModelTopics.syncProjectLibs(project.messageBus).beforeChanged(change) } logErrorOnEventHandling { workspaceModelTopics.syncModuleBridge(project.messageBus).beforeChanged(change) } logErrorOnEventHandling { workspaceModelTopics.syncPublisher(project.messageBus).beforeChanged(change) } } private fun onChanged(change: VersionedStorageChange) { ApplicationManager.getApplication().assertWriteAccessAllowed() if (project.isDisposed) return val workspaceModelTopics = WorkspaceModelTopics.getInstance(project) logErrorOnEventHandling { workspaceModelTopics.syncProjectLibs(project.messageBus).changed(change) } logErrorOnEventHandling { workspaceModelTopics.syncModuleBridge(project.messageBus).changed(change) } logErrorOnEventHandling { workspaceModelTopics.syncPublisher(project.messageBus).changed(change) } } private fun startPreUpdateHandlers(before: EntityStorage, builder: MutableEntityStorage) { var startUpdateLoop = true var updatesStarted = 0 while (startUpdateLoop && updatesStarted < PRE_UPDATE_LOOP_BLOCK) { updatesStarted += 1 startUpdateLoop = false PRE_UPDATE_HANDLERS.extensionsIfPointIsRegistered.forEach { startUpdateLoop = startUpdateLoop or it.update(before, builder) } } if (updatesStarted >= PRE_UPDATE_LOOP_BLOCK) { log.error("Loop workspace model updating") } } private fun logErrorOnEventHandling(action: () -> Unit) { try { action.invoke() } catch (e: Throwable) { val message = "Exception at Workspace Model event handling" if (userWarningLoggingLevel) { log.warn(message, e) } else { log.error(message, e) } } } companion object { private val log = logger<WorkspaceModelImpl>() private val PRE_UPDATE_HANDLERS = ExtensionPointName.create<WorkspaceModelPreUpdateHandler>("com.intellij.workspaceModel.preUpdateHandler") private const val PRE_UPDATE_LOOP_BLOCK = 100 } }
apache-2.0
775ca9a136e0423fe4b236e56a88ae99
34.649215
143
0.740344
4.952
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedMainParameterInspection.kt
5
1628
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemsHolder import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.quickfix.RemoveUnusedFunctionParameterFix import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.parameterVisitor import org.jetbrains.kotlin.resolve.BindingContext.UNUSED_MAIN_PARAMETER import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class UnusedMainParameterInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = parameterVisitor(fun(parameter: KtParameter) { val function = parameter.ownerFunction as? KtNamedFunction ?: return if (function.name != "main") return val context = function.analyzeWithContent() if (context[UNUSED_MAIN_PARAMETER, parameter] == true) { holder.registerProblem( parameter, KotlinBundle.message("since.kotlin.1.3.main.parameter.is.not.necessary"), IntentionWrapper(RemoveUnusedFunctionParameterFix(parameter)) ) } }) }
apache-2.0
17b56a609bf3c67dfbbc2c5a261c1c30
48.363636
120
0.753071
5.055901
false
false
false
false
airbnb/lottie-android
sample-compose/src/main/java/com/airbnb/lottie/sample/compose/examples/DynamicPropertiesExamplesPage.kt
1
5918
package com.airbnb.lottie.sample.compose.examples import android.graphics.PointF import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.dp import com.airbnb.lottie.LottieProperty import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.LottieConstants import com.airbnb.lottie.compose.rememberLottieComposition import com.airbnb.lottie.compose.rememberLottieDynamicProperties import com.airbnb.lottie.compose.rememberLottieDynamicProperty import com.airbnb.lottie.sample.compose.R @Composable fun DynamicPropertiesExamplesPage() { UsageExamplePageScaffold { Column( modifier = Modifier .fillMaxWidth() .verticalScroll(rememberScrollState()) ) { ExampleCard("Heart Color + Blur", "Click to change color") { HeartColor() } ExampleCard("Change Properties", "Click to toggle whether the dynamic property is used") { ToggleProperty() } ExampleCard("Jump Height", "Click to jump height") { JumpHeight() } } } } @Composable private fun HeartColor() { val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.heart)) val colors = remember { listOf( Color.Red, Color.Green, Color.Blue, Color.Yellow, ) } var colorIndex by remember { mutableStateOf(0) } val color by derivedStateOf { colors[colorIndex] } val blurRadius = with(LocalDensity.current) { 12.dp.toPx() } val dynamicProperties = rememberLottieDynamicProperties( rememberLottieDynamicProperty( property = LottieProperty.COLOR, value = color.toArgb(), keyPath = arrayOf( "H2", "Shape 1", "Fill 1", ) ), rememberLottieDynamicProperty( property = LottieProperty.BLUR_RADIUS, value = blurRadius, keyPath = arrayOf( "**", "Stroke 1", ) ), ) LottieAnimation( composition, iterations = LottieConstants.IterateForever, dynamicProperties = dynamicProperties, modifier = Modifier .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = { colorIndex = (colorIndex + 1) % colors.size }, ) ) } @Composable private fun JumpHeight() { val composition by rememberLottieComposition(LottieCompositionSpec.Asset("AndroidWave.json")) val extraJumpHeights = remember { listOf(0.dp, 24.dp, 48.dp, 128.dp) } var extraJumpIndex by remember { mutableStateOf(0) } val extraJumpHeight by derivedStateOf { extraJumpHeights[extraJumpIndex] } val extraJumpHeightPx = with(LocalDensity.current) { extraJumpHeight.toPx() } val point = remember { PointF() } val dynamicProperties = rememberLottieDynamicProperties( rememberLottieDynamicProperty(LottieProperty.TRANSFORM_POSITION, "Body") { frameInfo -> var startY = frameInfo.startValue.y var endY = frameInfo.endValue.y when { startY > endY -> startY += extraJumpHeightPx else -> endY += extraJumpHeightPx } point.set(frameInfo.startValue.x, lerp(startY, endY, frameInfo.interpolatedKeyframeProgress)) point } ) LottieAnimation( composition, iterations = LottieConstants.IterateForever, dynamicProperties = dynamicProperties, modifier = Modifier .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = { extraJumpIndex = (extraJumpIndex + 1) % extraJumpHeights.size }, ) ) } @Composable private fun ToggleProperty() { val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.heart)) var useDynamicProperty by remember { mutableStateOf(true) } val dynamicProperties = rememberLottieDynamicProperties( rememberLottieDynamicProperty( property = LottieProperty.COLOR, value = Color.Green.toArgb(), keyPath = arrayOf( "H2", "Shape 1", "Fill 1", ) ), ) LottieAnimation( composition, iterations = LottieConstants.IterateForever, dynamicProperties = dynamicProperties.takeIf { useDynamicProperty }, modifier = Modifier .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = { useDynamicProperty = !useDynamicProperty }, ) ) } private fun lerp(valueA: Float, valueB: Float, progress: Float): Float { val smallerY = minOf(valueA, valueB) val largerY = maxOf(valueA, valueB) return smallerY + progress * (largerY - smallerY) }
apache-2.0
993298c61cfe113eb4ccf67dbec728e4
35.085366
105
0.65174
5.045183
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/controls/behaviours/MouseDragSphere.kt
1
2333
package graphics.scenery.controls.behaviours import graphics.scenery.BoundingGrid import graphics.scenery.Camera import graphics.scenery.Node import graphics.scenery.utils.LazyLogger import graphics.scenery.utils.extensions.minus import graphics.scenery.utils.extensions.plus import graphics.scenery.utils.extensions.times import org.joml.Vector3f import org.scijava.ui.behaviour.DragBehaviour /** * Drag nodes roughly along a sphere around the camera by mouse. * Implements algorithm from https://forum.unity.com/threads/implement-a-drag-and-drop-script-with-c.130515/ * * @author Jan Tiemann <[email protected]> */ open class MouseDragSphere( protected val name: String, camera: () -> Camera?, protected var debugRaycast: Boolean = false, var ignoredObjects: List<Class<*>> = listOf<Class<*>>(BoundingGrid::class.java) ) : DragBehaviour, WithCameraDelegateBase(camera) { protected val logger by LazyLogger() protected var currentNode: Node? = null protected var currentHit: Vector3f = Vector3f() protected var distance: Float = 0f override fun init(x: Int, y: Int) { cam?.let { cam -> val matches = cam.getNodesForScreenSpacePosition(x, y, ignoredObjects, debugRaycast) currentNode = matches.matches.firstOrNull()?.node distance = matches.matches.firstOrNull()?.distance ?: 0f//currentNode?.position?.distance(cam.position) ?: 0f val (rayStart, rayDir) = cam.screenPointToRay(x, y) rayDir.normalize() currentHit = rayStart + rayDir * distance } } override fun drag(x: Int, y: Int) { if (distance <= 0) return cam?.let { cam -> currentNode?.let { val (rayStart, rayDir) = cam.screenPointToRay(x, y) rayDir.normalize() val newHit = rayStart + rayDir * distance val movement = newHit - currentHit it.ifSpatial { val newPos = position + movement / worldScale() currentNode?.spatialOrNull()?.position = newPos currentHit = newHit } } } } override fun end(x: Int, y: Int) { // intentionally empty. A new click will overwrite the running variables. } }
lgpl-3.0
599410b5b7fdef4a91dc7bb96fbaa877
32.811594
121
0.640806
4.249545
false
false
false
false
mdanielwork/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUDeclarationsExpression.kt
6
1347
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.PsiElement import org.jetbrains.uast.* class JavaUDeclarationsExpression( uastParent: UElement? ) : JavaAbstractUElement(uastParent), UDeclarationsExpression, JvmDeclarationUElement { override lateinit var declarations: List<UDeclaration> internal set constructor(parent: UElement?, declarations: List<UDeclaration>) : this(parent) { this.declarations = declarations } override val annotations: List<UAnnotation> get() = emptyList() override val psi: PsiElement? get() = null override fun equals(other: Any?): Boolean = other is JavaUDeclarationsExpression && declarations == other.declarations override fun hashCode(): Int = declarations.hashCode() }
apache-2.0
ae4190bb99f55aa0bc753b5725cc05a4
32.7
120
0.753526
4.550676
false
false
false
false
mikepenz/FastAdapter
fastadapter/src/main/java/com/mikepenz/fastadapter/select/SelectExtension.kt
1
18678
package com.mikepenz.fastadapter.select import android.os.Bundle import android.view.MotionEvent import android.view.View import androidx.collection.ArraySet import androidx.recyclerview.widget.RecyclerView import com.mikepenz.fastadapter.* import com.mikepenz.fastadapter.dsl.FastAdapterDsl import com.mikepenz.fastadapter.extensions.ExtensionsFactories import com.mikepenz.fastadapter.utils.AdapterPredicate import java.util.* /** * Extension method to retrieve or create the SelectExtension from the current FastAdapter. * This will return a non null variant and fail if something terrible happens. */ fun <Item : GenericItem> FastAdapter<Item>.getSelectExtension(): SelectExtension<Item> { SelectExtension.toString() // enforces the vm to lead in the companion object return requireOrCreateExtension() } /** * Extension method to retrieve or create the SelectExtension from the current FastAdapter. * This will return a non null variant and fail if something terrible happens. */ inline fun <Item : GenericItem> FastAdapter<Item>.selectExtension(block: SelectExtension<Item>.() -> Unit) { getSelectExtension().apply(block) } /** * Created by mikepenz on 04/06/2017. */ @FastAdapterDsl class SelectExtension<Item : GenericItem>(private val fastAdapter: FastAdapter<Item>) : IAdapterExtension<Item> { // if enabled we will select the item via a notifyItemChanged -> will animate with the Animator // you can also use this if you have any custom logic for selections, and do not depend on the "selected" state of the view // note if enabled it will feel a bit slower because it will animate the selection /** * Select between the different selection behaviors. * there are now 2 different variants of selection. you can toggle this via `withSelectWithItemUpdate(boolean)` (where false == default - variant 1) * 1.) direct selection via the view "selected" state, we also make sure we do not animate here so no notifyItemChanged is called if we repeatedly press the same item * 2.) we select the items via a notifyItemChanged. this will allow custom selected logic within your views (isSelected() - do something...) and it will also animate the change via the provided itemAnimator. because of the animation of the itemAnimator the selection will have a small delay (time of animating) */ var selectWithItemUpdate = false // if we want multiSelect enabled // Enable this if you want multiSelection possible in the list var multiSelect = false // if we want the multiSelect only on longClick // Disable this if you want the selection on a single tap var selectOnLongClick = false // if a user can deselect a selection via click. required if there is always one selected item! // If false, a user can't deselect an item via click (you can still do this programmatically) var allowDeselection = true // if items are selectable in general /** If items are selectable */ var isSelectable = false //a listener that get's notified whenever an item is selected or deselected var selectionListener: ISelectionListener<Item>? = null //------------------------- //------------------------- //Selection stuff //------------------------- //------------------------- /** * @return a set with the global positions of all selected items (which are currently in the list (includes expanded expandable items)) */ val selections: Set<Int> get() { return (0 until fastAdapter.itemCount).mapNotNullTo(ArraySet<Int>()) { i -> i.takeIf { fastAdapter.getItem(i)?.isSelected == true } } } /** * @return a set with all items which are currently selected (includes subitems) */ val selectedItems: MutableSet<Item> get() { val items = ArraySet<Item>() fastAdapter.recursive(object : AdapterPredicate<Item> { override fun apply( lastParentAdapter: IAdapter<Item>, lastParentPosition: Int, item: Item, position: Int ): Boolean { if (item.isSelected) { items.add(item) } return false } }, false) return items } override fun withSavedInstanceState(savedInstanceState: Bundle?, prefix: String) { val selectedItems = savedInstanceState?.getLongArray(BUNDLE_SELECTIONS + prefix) ?: return for (id in selectedItems) { selectByIdentifier(id, false, true) } } override fun saveInstanceState(savedInstanceState: Bundle?, prefix: String) { if (savedInstanceState == null) { return } val selections = selectedItems val selectionsArray = LongArray(selections.size) for ((i, item) in selections.withIndex()) { selectionsArray[i] = item.identifier } //remember the selections savedInstanceState.putLongArray(BUNDLE_SELECTIONS + prefix, selectionsArray) } override fun onClick(v: View, pos: Int, fastAdapter: FastAdapter<Item>, item: Item): Boolean { //handle the selection if the event was not yet consumed, and we are allowed to select an item (only occurs when we select with long click only) //this has to happen before expand or collapse. otherwise the position is wrong which is used to select if (!selectOnLongClick && isSelectable) { handleSelection(v, item, pos) } return false } override fun onLongClick( v: View, pos: Int, fastAdapter: FastAdapter<Item>, item: Item ): Boolean { //now handle the selection if we are in multiSelect mode and allow selecting on longClick if (selectOnLongClick && isSelectable) { handleSelection(v, item, pos) } return false } override fun onTouch( v: View, event: MotionEvent, position: Int, fastAdapter: FastAdapter<Item>, item: Item ): Boolean { return false } override fun notifyAdapterDataSetChanged() {} override fun notifyAdapterItemRangeInserted(position: Int, itemCount: Int) {} override fun notifyAdapterItemRangeRemoved(position: Int, itemCount: Int) {} override fun notifyAdapterItemMoved(fromPosition: Int, toPosition: Int) {} override fun notifyAdapterItemRangeChanged(position: Int, itemCount: Int, payload: Any?) {} override fun set(items: List<Item>, resetFilter: Boolean) {} override fun performFiltering(constraint: CharSequence?) {} /** * Toggles the selection of the item at the given position * * @param position the global position */ fun toggleSelection(position: Int) { if (fastAdapter.getItem(position)?.isSelected == true) { deselect(position) } else { select(position) } } /** * Handles the selection and deselects item if multiSelect is disabled * * @param position the global position */ private fun handleSelection(view: View?, item: Item, position: Int) { //if this item is not selectable don't continue if (!item.isSelectable) { return } //if we have disabled deselection via click don't continue if (item.isSelected && !allowDeselection) { return } val selected = item.isSelected if (selectWithItemUpdate || view == null) { if (!multiSelect) { deselect() } if (selected) { deselect(position) } else { select(position) } } else { if (!multiSelect) { //we have to separately handle deselection here because if we toggle the current item we do not want to deselect this first! val selections = selectedItems selections.remove(item) deselectByItems(selections) } //we toggle the state of the view item.isSelected = !selected view.isSelected = !selected //notify that the selection changed selectionListener?.onSelectionChanged(item, !selected) } } /** * Select all items * * @param considerSelectableFlag true if the select method should not select an item if its not selectable */ @JvmOverloads fun select(considerSelectableFlag: Boolean = false) { fastAdapter.recursive(object : AdapterPredicate<Item> { override fun apply( lastParentAdapter: IAdapter<Item>, lastParentPosition: Int, item: Item, position: Int ): Boolean { select(lastParentAdapter, item, RecyclerView.NO_POSITION, false, considerSelectableFlag) return false } }, false) fastAdapter.notifyDataSetChanged() } /** * Select's a provided item, this won't notify the adapter * * @param item the item to select * @param considerSelectableFlag true if the select method should not select an item if its not selectable */ fun select(item: Item, considerSelectableFlag: Boolean) { if (considerSelectableFlag && !item.isSelectable) { return } item.isSelected = true selectionListener?.onSelectionChanged(item, true) } /** * Selects all items at the positions in the iterable * * @param positions the global positions to select */ fun select(positions: Iterable<Int>) { positions.forEach { select(it) } } /** * Selects an item and remembers its position in the selections list * * @param position the global position * @param fireEvent true if the onClick listener should be called * @param considerSelectableFlag true if the select method should not select an item if its not selectable */ @JvmOverloads fun select(position: Int, fireEvent: Boolean = false, considerSelectableFlag: Boolean = false) { val relativeInfo = fastAdapter.getRelativeInfo(position) relativeInfo.item?.let { item -> relativeInfo.adapter?.let { adapter -> select(adapter, item, position, fireEvent, considerSelectableFlag) } } } /** * Selects an item and remembers its position in the selections list * * @param adapter adapter holding this item (or it's parent) * @param item the item to select * @param position the global position (or < 0 if the item is not displayed) * @param fireEvent true if the onClick listener should be called * @param considerSelectableFlag true if the select method should not select an item if its not selectable */ fun select(adapter: IAdapter<Item>, item: Item, position: Int, fireEvent: Boolean, considerSelectableFlag: Boolean) { if (considerSelectableFlag && !item.isSelectable) { return } item.isSelected = true fastAdapter.notifyItemChanged(position) selectionListener?.onSelectionChanged(item, true) if (fireEvent) { fastAdapter.onClickListener?.invoke(null, adapter, item, position) } } /** * Selects an item by it's identifier * * @param identifier the identifier of the item to select * @param fireEvent true if the onClick listener should be called * @param considerSelectableFlag true if the select method should not select an item if its not selectable */ fun selectByIdentifier(identifier: Long, fireEvent: Boolean, considerSelectableFlag: Boolean) { fastAdapter.recursive(object : AdapterPredicate<Item> { override fun apply(lastParentAdapter: IAdapter<Item>, lastParentPosition: Int, item: Item, position: Int): Boolean { if (item.identifier == identifier) { select(lastParentAdapter, item, position, fireEvent, considerSelectableFlag) return true } return false } }, true) } /** * @param identifiers the set of identifiers to select * @param fireEvent true if the onClick listener should be called * @param considerSelectableFlag true if the select method should not select an item if its not selectable */ fun selectByIdentifiers(identifiers: Set<Long>, fireEvent: Boolean, considerSelectableFlag: Boolean) { fastAdapter.recursive(object : AdapterPredicate<Item> { override fun apply(lastParentAdapter: IAdapter<Item>, lastParentPosition: Int, item: Item, position: Int): Boolean { if (identifiers.contains(item.identifier)) { select(lastParentAdapter, item, position, fireEvent, considerSelectableFlag) } return false } }, false) } /** * Deselects all selections */ fun deselect() { fastAdapter.recursive(object : AdapterPredicate<Item> { override fun apply(lastParentAdapter: IAdapter<Item>, lastParentPosition: Int, item: Item, position: Int): Boolean { deselect(item) return false } }, false) fastAdapter.notifyDataSetChanged() } /** * Deselects all items at the positions in the iterable * * @param positions the global positions to deselect */ fun deselect(positions: MutableIterable<Int>) { val entries = positions.iterator() while (entries.hasNext()) { deselect(entries.next(), entries) } } /** * Deselects an item and removes its position in the selections list * also takes an iterator to remove items from the map * * @param position the global position * @param entries the iterator which is used to deselect all */ @JvmOverloads fun deselect(position: Int, entries: MutableIterator<Int>? = null) { val item = fastAdapter.getItem(position) ?: return deselect(item, position, entries) } /** * Deselects an item and removes its position in the selections list * also takes an iterator to remove items from the map * * @param item the item to deselected * @param position the global position (or < 0 if the item is not displayed) * @param entries the iterator which is used to deselect all */ @JvmOverloads fun deselect(item: Item, position: Int = RecyclerView.NO_POSITION, entries: MutableIterator<Int>? = null) { item.isSelected = false entries?.remove() if (position >= 0) { fastAdapter.notifyItemChanged(position) } selectionListener?.onSelectionChanged(item, false) } /** * Selects an item by it's identifier * * @param identifier the identifier of the item to deselect */ fun deselectByIdentifier(identifier: Long) { fastAdapter.recursive(object : AdapterPredicate<Item> { override fun apply(lastParentAdapter: IAdapter<Item>, lastParentPosition: Int, item: Item, position: Int): Boolean { if (item.identifier == identifier) { deselect(item, position, null) return true } return false } }, true) } /** * @param identifiers the set of identifiers to deselect */ fun deselectByIdentifiers(identifiers: Set<Long>) { fastAdapter.recursive(object : AdapterPredicate<Item> { override fun apply(lastParentAdapter: IAdapter<Item>, lastParentPosition: Int, item: Item, position: Int): Boolean { if (identifiers.contains(item.identifier)) { deselect(item, position, null) } return false } }, false) } /** * @param items the set of items to deselect. They require a identifier. */ fun deselectByItems(items: Set<Item>) { fastAdapter.recursive(object : AdapterPredicate<Item> { override fun apply(lastParentAdapter: IAdapter<Item>, lastParentPosition: Int, item: Item, position: Int): Boolean { if (items.contains(item)) { deselect(item, position, null) } return false } }, false) } /** * Deletes all current selected items * * @return a list of the IItem elements which were deleted */ fun deleteAllSelectedItems(): List<Item> { val deletedItems = ArrayList<Item>() val positions = ArrayList<Int>() fastAdapter.recursive(object : AdapterPredicate<Item> { override fun apply(lastParentAdapter: IAdapter<Item>, lastParentPosition: Int, item: Item, position: Int): Boolean { if (item.isSelected) { //if it's a subitem remove it from the parent (item as? IExpandable<*>?)?.let { expandable -> //a sub item which is not in the list can be instantly deleted expandable.parent?.subItems?.remove(item) } if (position != RecyclerView.NO_POSITION) { //a normal displayed item can only be deleted afterwards positions.add(position) } } return false } }, false) //we have to re-fetch the selections array again and again as the position will change after one item is deleted for (i in positions.indices.reversed()) { val ri = fastAdapter.getRelativeInfo(positions[i]) if (ri.item != null && ri.item!!.isSelected) { //double verify (ri.adapter as? IItemAdapter<*, *>)?.remove(positions[i]) } } return deletedItems } companion object { private const val BUNDLE_SELECTIONS = "bundle_selections" init { ExtensionsFactories.register(SelectExtensionFactory()) } } }
apache-2.0
8f8290c6e2f523d3f6cada1d132efa34
36.963415
314
0.612753
5.035859
false
false
false
false
dahlstrom-g/intellij-community
plugins/eclipse/testSources/org/jetbrains/idea/eclipse/SettingMappingTest.kt
8
2409
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.eclipse import org.jetbrains.idea.eclipse.codeStyleMapping.util.* import org.jetbrains.idea.eclipse.codeStyleMapping.util.SettingsMappingHelpers.const import org.jetbrains.idea.eclipse.codeStyleMapping.util.SettingsMappingHelpers.field import org.jetbrains.idea.eclipse.codeStyleMapping.util.SettingsMappingHelpers.compute import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows class SettingMappingTest { class TestObject { var boolField = false var intField = 0 } var obj = TestObject() @BeforeEach fun resetTestObject() { obj = TestObject() } @Test fun testFieldSettingMapping() { val mapping = field(obj::boolField).convert(BooleanConvertor) assertEquals("false", mapping.export()) mapping.import("True") assertEquals(true, obj.boolField) } @Test fun testUnexpectedIncomingValue() { val mapping = field(obj::intField).convert(IntConvertor) assertThrows<UnexpectedIncomingValue> { mapping.import("not a number") } assertEquals(0, obj.intField) } @Test fun testDoNotImportSettingMapping() { val mapping = field(obj::boolField).doNotImport() assertTrue(mapping.isExportAllowed) assertEquals(false, mapping.export()) assertFalse(mapping.isImportAllowed) assertThrows<IllegalStateException> { mapping.import(true) } } @Test fun testConstSettingMapping() { val mapping = const(true).convert(BooleanConvertor) assertTrue(mapping.isExportAllowed) assertEquals("true", mapping.export()) assertFalse(mapping.isImportAllowed) assertThrows<IllegalStateException> { mapping.import("true") } } @Test fun testManualSettingMapping() { val mapping = compute( import = { obj.boolField = it }, export = { obj.boolField } ) assertTrue(mapping.isExportAllowed) assertTrue(mapping.isImportAllowed) assertEquals(false, obj.boolField) mapping.import(true) assertEquals(true, obj.boolField) } @Test fun testInvertingBooleanSettingMapping() { val mapping = field(obj::boolField).invert() assertEquals(true, mapping.export()) mapping.import(false) assertEquals(true, obj.boolField) } }
apache-2.0
2407b48d1c9241ebef9c52835c4329aa
29.125
120
0.739726
4.069257
false
true
false
false
dahlstrom-g/intellij-community
python/src/com/jetbrains/python/console/PyConsoleEnterHandler.kt
7
5898
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.console import com.intellij.ide.DataManager import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.actionSystem.EditorActionManager import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.DocumentUtil import com.jetbrains.python.PyTokenTypes import com.jetbrains.python.psi.PyStatementListContainer import com.jetbrains.python.psi.PyStringLiteralExpression import com.jetbrains.python.psi.PyStringLiteralUtil import com.jetbrains.python.psi.PyTryPart import com.jetbrains.python.psi.impl.PyPsiUtils class PyConsoleEnterHandler { fun handleEnterPressed(editor: EditorEx): Boolean { val project = editor.project ?: throw IllegalArgumentException() val lineCount = editor.document.lineCount if (lineCount > 0) { // move to end of line editor.selectionModel.removeSelection() val caretPosition = editor.caretModel.logicalPosition if (caretPosition.line == lineCount - 1) { // we can move caret if only it's on the last line of command val lineEndOffset = editor.document.getLineEndOffset(caretPosition.line) editor.caretModel.moveToOffset(lineEndOffset) } else { // otherwise just process enter action executeEnterHandler(project, editor) return false } } else { return true } val psiMgr = PsiDocumentManager.getInstance(project) psiMgr.commitDocument(editor.document) val caretOffset = editor.expectedCaretOffset val atElement = findFirstNoneSpaceElement(psiMgr.getPsiFile(editor.document)!!, caretOffset) if (atElement == null) { executeEnterHandler(project, editor) return false } val firstLine = getLineAtOffset(editor.document, DocumentUtil.getFirstNonSpaceCharOffset(editor.document, 0)) val isCellMagic = firstLine.trim().startsWith("%%") && !firstLine.trimEnd().endsWith("?") val prevLine = getLineAtOffset(editor.document, caretOffset) val isLineContinuation = prevLine.trim().endsWith('\\') val insideDocString = isElementInsideDocString(atElement, caretOffset) val isMultiLineCommand = PsiTreeUtil.getParentOfType(atElement, PyStatementListContainer::class.java) != null || isCellMagic val isAtTheEndOfCommand = editor.document.getLineNumber(caretOffset) == editor.document.lineCount - 1 val hasCompleteStatement = !insideDocString && !isLineContinuation && checkComplete(atElement) executeEnterHandler(project, editor) return isAtTheEndOfCommand && hasCompleteStatement && ((isMultiLineCommand && prevLine.isBlank()) || (!isMultiLineCommand)) } private fun executeEnterHandler(project: Project, editor:EditorEx) { val enterHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ENTER) WriteCommandAction.runWriteCommandAction(project) { enterHandler.execute(editor, null, DataManager.getInstance().getDataContext(editor.component)) } } private fun isElementInsideDocString(atElement: PsiElement, caretOffset: Int): Boolean { return atElement.context is PyStringLiteralExpression && (PyTokenTypes.TRIPLE_NODES.contains(atElement.node.elementType) || atElement.node.elementType === PyTokenTypes.DOCSTRING) && isMultilineString(atElement.text) && (atElement.textRange.endOffset > caretOffset || !isCompleteDocString(atElement.text)) } private fun checkComplete(el: PsiElement): Boolean { val compoundStatement = PsiTreeUtil.getParentOfType(el, PyStatementListContainer::class.java) if (compoundStatement != null && compoundStatement !is PyTryPart) { return compoundStatement.statementList.statements.size != 0 } val topLevel = PyPsiUtils.getParentRightBefore(el, el.containingFile) return topLevel != null && !PsiTreeUtil.hasErrorElements(topLevel) } private fun findFirstNoneSpaceElement(psiFile: PsiFile, offset: Int): PsiElement? { for (i in offset downTo 0) { val el = psiFile.findElementAt(i) if (el != null && el !is PsiWhiteSpace) { return el } } return null } private fun getLineAtOffset(doc: Document, offset: Int): String { val line = doc.getLineNumber(offset) val start = doc.getLineStartOffset(line) val end = doc.getLineEndOffset(line) return doc.getText(TextRange(start, end)) } private fun isMultilineString(str: String): Boolean { val text = str.substring(PyStringLiteralUtil.getPrefixLength(str)) return text.startsWith("\"\"\"") || text.startsWith("'''") } private fun isCompleteDocString(str: String): Boolean { val prefixLen = PyStringLiteralUtil.getPrefixLength(str) val text = str.substring(prefixLen) for (token in arrayOf("\"\"\"", "'''")) { if (text.length >= 2 * token.length && text.startsWith(token) && text.endsWith(token)) { return true } } return false } }
apache-2.0
2328f82e9be90b905df5a59ba1b4d281
39.965278
128
0.742794
4.474962
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/reflect/KotlinCompilationReflection.kt
1
2218
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.gradleTooling.reflect import org.gradle.api.Named import org.jetbrains.kotlin.idea.gradleTooling.getMethodOrNull fun KotlinCompilationReflection(kotlinCompilation: Any): KotlinCompilationReflection = KotlinCompilationReflectionImpl(kotlinCompilation) interface KotlinCompilationReflection { val compilationName: String val gradleCompilation: Named val sourceSets: Collection<Named>? // Source Sets that directly added to compilation val allSourceSets: Collection<Named>? // this.sourceSets + their transitive closure through dependsOn relation val compilationOutput: KotlinCompilationOutputReflection? val konanTargetName: String? val compileKotlinTaskName: String? } private class KotlinCompilationReflectionImpl(private val instance: Any) : KotlinCompilationReflection { override val gradleCompilation: Named get() = instance as Named override val compilationName: String by lazy { gradleCompilation.name } override val sourceSets: Collection<Named>? by lazy { instance.callReflectiveGetter("getKotlinSourceSets", logger) } override val allSourceSets: Collection<Named>? by lazy { instance.callReflectiveGetter("getAllKotlinSourceSets", logger) } override val compilationOutput: KotlinCompilationOutputReflection? by lazy { instance.callReflectiveAnyGetter("getOutput", logger)?.let { gradleOutput -> KotlinCompilationOutputReflection(gradleOutput) } } // Get konanTarget (for native compilations only). override val konanTargetName: String? by lazy { if (instance.javaClass.getMethodOrNull("getKonanTarget") == null) null else instance.callReflectiveAnyGetter("getKonanTarget", logger) ?.callReflectiveGetter("getName", logger) } override val compileKotlinTaskName: String? by lazy { instance.callReflectiveGetter("getCompileKotlinTaskName", logger) } companion object { private val logger: ReflectionLogger = ReflectionLogger(KotlinCompilationReflection::class.java) } }
apache-2.0
afb8620e102cc820237855a5de80c630
41.673077
134
0.761497
5.409756
false
false
false
false
chrhsmt/Sishen
app/src/main/java/com/chrhsmt/sisheng/NiniReibunViewAdapterForTab.kt
1
2690
package com.chrhsmt.sisheng import android.os.Build import android.support.v7.widget.RecyclerView import android.text.Html import android.text.Spanned import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.chrhsmt.sisheng.NiniReibunFragmentForTab.OnListFragmentInteractionListener import kotlinx.android.synthetic.main.fragment_tab_nini_reibun_item.view.* /** * [RecyclerView.Adapter] that can display a [DummyItem] and makes a call to the * specified [OnListFragmentInteractionListener]. * TODO: Replace the implementation with code for your data type. */ class NiniReibunViewAdapterForTab( private val mValues: List<ReibunInfo.ReibunInfoItem>, private val mListener: OnListFragmentInteractionListener?) : RecyclerView.Adapter<NiniReibunViewAdapterForTab.ViewHolder>() { private val mOnClickListener: View.OnClickListener init { mOnClickListener = View.OnClickListener { v -> val item = v.tag as ReibunInfo.ReibunInfoItem // Notify the active callbacks interface (the activity, if the fragment is attached to // one) that an item has been selected. mListener?.onListFragmentInteraction(item) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.fragment_tab_nini_reibun_item, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = mValues[position] holder.mIdView.text = Integer.toString(item.id) var htmlStr: String = ReibunInfo.replaceNewLineWithBrTag(item.chinese + "\\n" + item.english) htmlStr = htmlStr.replace(item.strong_word, "<font color=\"red\">" + item.strong_word + "</font>") holder.mContentView.text = fromHtml(htmlStr) with(holder.mView) { tag = item setOnClickListener(mOnClickListener) } } fun fromHtml(source: String): Spanned { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY) } else { Html.fromHtml(source) } } override fun getItemCount(): Int = mValues.size inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) { val mIdView: TextView = mView.item_number val mContentView: TextView = mView.content override fun toString(): String { return super.toString() + " '" + mContentView.text + "'" } } }
mit
d3b9c5b7f712748d5b3fec000a4286dd
35.351351
106
0.687361
4.373984
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/mediastore/src/main/kotlin/com/kotlin/mediastore/DeleteContainer.kt
1
1757
// snippet-sourcedescription:[DeleteContainer.kt demonstrates how to delete a given AWS Elemental MediaStore container.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[AWS Elemental MediaStore] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.mediastore // snippet-start:[mediastore.kotlin.delete_container.import] import aws.sdk.kotlin.services.mediastore.MediaStoreClient import aws.sdk.kotlin.services.mediastore.model.DeleteContainerRequest import kotlin.system.exitProcess // snippet-end:[mediastore.kotlin.delete_container.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: <containerName> Where: containerName - the name of the container to delete. """ if (args.size != 1) { println(usage) exitProcess(0) } val containerName = args[0] deleteMediaContainer(containerName) } // snippet-start:[mediastore.kotlin.delete_container.main] suspend fun deleteMediaContainer(containerNameVal: String?) { val request = DeleteContainerRequest { containerName = containerNameVal } MediaStoreClient { region = "us-west-2" }.use { mediaStoreClient -> mediaStoreClient.deleteContainer(request) println("The $containerNameVal was deleted") } } // snippet-end:[mediastore.kotlin.delete_container.main]
apache-2.0
fadf75a5c97e3201d62fa11d83fc6713
28.824561
120
0.702334
4.114754
false
false
false
false
BenAlderfer/percent-calculatorv2
app/src/main/java/com/alderferstudios/percentcalculatorv2/fragment/CostFragment.kt
1
1477
package com.alderferstudios.percentcalculatorv2.fragment import android.content.Intent import android.os.Bundle import android.view.* import android.widget.EditText import com.alderferstudios.percentcalculatorv2.R import com.alderferstudios.percentcalculatorv2.activity.SettingsActivity /** * Cost screen */ class CostFragment : BaseFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_cost, container, false) override fun onStart() { super.onStart() getBaseActivity().buttons.add(activity?.findViewById(R.id.next)) } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { inflater?.inflate(R.menu.menu_cost, menu) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem?): Boolean = when (item?.itemId) { R.id.settings -> { val settingsActivity = Intent(activity, SettingsActivity::class.java) startActivity(settingsActivity) true } else -> super.onOptionsItemSelected(item) } override fun fieldsAreValid(): Boolean { val costBox = activity?.findViewById<EditText>(R.id.cost) return costBox?.text.toString() != "" && costBox?.text.toString().toDouble() > 0.0 } }
gpl-3.0
9dc0e9fd7d2ca18c13920524b511e44c
32.590909
116
0.658091
4.659306
false
false
false
false
PaulWoitaschek/MaterialAudiobookPlayer
app/src/main/java/de/ph1b/audiobook/uitools/CircularRevealBookPlayTransition.kt
1
2306
package de.ph1b.audiobook.uitools import android.animation.Animator import android.animation.AnimatorSet import android.transition.TransitionValues import android.transition.Visibility import android.view.View import android.view.ViewAnimationUtils import android.view.ViewGroup import de.ph1b.audiobook.R import de.ph1b.audiobook.uitools.noPauseAnimator.noPause private const val FINAL_RADIUS = "de.ph1b.audiobook:CircularRevealBookPlayTransition:finalRadius" class CircularRevealBookPlayTransition : Visibility() { override fun captureEndValues(transitionValues: TransitionValues?) { super.captureEndValues(transitionValues) if (transitionValues == null) return val parent = transitionValues.view.parent as View val previous = parent.findViewById<View?>(R.id.previous) val next = parent.findViewById<View?>(R.id.next) if (previous == null || next == null) return val finalRadius = next.right - previous.left transitionValues.values.put(FINAL_RADIUS, finalRadius) } override fun onAppear( sceneRoot: ViewGroup?, startValues: TransitionValues?, startVisibility: Int, endValues: TransitionValues?, endVisibility: Int ): Animator? { if (endVisibility != View.VISIBLE || endValues == null) return null val view = endValues.view val parent = view.parent as? View? ?: return null val parentWidth = parent.width val finalRadius = endValues.values?.getOrElse(FINAL_RADIUS) { parentWidth } as Int val circularReveal = circularRevealAnimator( target = endValues.view, cx = parentWidth / 2, finalRadius = finalRadius.toFloat() ) .apply { interpolator = Interpolators.fastOutSlowIn addListener(object : DefaultAnimatorListener { override fun onAnimationStart(animator: Animator) { view.visibility = endVisibility } }) } return AnimatorSet() .apply { playTogether(circularReveal) view.visibility = View.INVISIBLE } } private fun circularRevealAnimator(target: View, cx: Int, finalRadius: Float): Animator = ViewAnimationUtils.createCircularReveal( target, cx - target.left, target.height / 2, 0f, finalRadius ).noPause() }
lgpl-3.0
b0ba0f24a3dc4f931b5f6122a43dc589
28.189873
97
0.701648
4.460348
false
false
false
false
google/intellij-community
plugins/git4idea/src/git4idea/config/GitVcsPanel.kt
1
16583
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.config import com.intellij.application.options.editor.CheckboxDescriptor import com.intellij.application.options.editor.checkBox import com.intellij.dvcs.branch.DvcsSyncSettings import com.intellij.dvcs.repo.VcsRepositoryManager import com.intellij.dvcs.repo.VcsRepositoryMappingListener import com.intellij.dvcs.ui.DvcsBundle import com.intellij.ide.ui.search.OptionDescription import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.options.BoundCompositeConfigurable import com.intellij.openapi.options.SearchableConfigurable import com.intellij.openapi.options.UnnamedConfigurable import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.options.advanced.AdvancedSettingsChangeListener import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsEnvCustomizer import com.intellij.openapi.vcs.update.AbstractCommonUpdateAction import com.intellij.ui.EnumComboBoxModel import com.intellij.ui.Gray import com.intellij.ui.JBColor import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.TextComponentEmptyText import com.intellij.ui.components.fields.ExpandableTextField import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.builder.Cell import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.layout.* import com.intellij.util.Function import com.intellij.util.execution.ParametersListUtil import com.intellij.vcs.commit.CommitModeManager import com.intellij.vcs.log.VcsLogFilterCollection.STRUCTURE_FILTER import com.intellij.vcs.log.impl.MainVcsLogUiProperties import com.intellij.vcs.log.ui.VcsLogColorManagerImpl import com.intellij.vcs.log.ui.filter.StructureFilterPopupComponent import com.intellij.vcs.log.ui.filter.VcsLogClassicFilterUi import git4idea.GitVcs import git4idea.branch.GitBranchIncomingOutgoingManager import git4idea.config.GitExecutableSelectorPanel.Companion.createGitExecutableSelectorRow import git4idea.config.gpg.GpgSignConfigurableRow.Companion.createGpgSignRow import git4idea.i18n.GitBundle.message import git4idea.index.canEnableStagingArea import git4idea.index.enableStagingArea import git4idea.repo.GitRepositoryManager import git4idea.update.GitUpdateProjectInfoLogProperties import git4idea.update.getUpdateMethods import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import javax.swing.border.Border private fun gitSharedSettings(project: Project) = GitSharedSettings.getInstance(project) private fun projectSettings(project: Project) = GitVcsSettings.getInstance(project) private val applicationSettings get() = GitVcsApplicationSettings.getInstance() private val gitOptionGroupName get() = message("settings.git.option.group") // @formatter:off private fun cdSyncBranches(project: Project) = CheckboxDescriptor(DvcsBundle.message("sync.setting"), PropertyBinding({ projectSettings(project).syncSetting == DvcsSyncSettings.Value.SYNC }, { projectSettings(project).syncSetting = if (it) DvcsSyncSettings.Value.SYNC else DvcsSyncSettings.Value.DONT_SYNC }), groupName = gitOptionGroupName) private fun cdAddCherryPickSuffix(project: Project) = CheckboxDescriptor(message("settings.add.suffix"), PropertyBinding({ projectSettings(project).shouldAddSuffixToCherryPicksOfPublishedCommits() }, { projectSettings(project).setAddSuffixToCherryPicks(it) }), groupName = gitOptionGroupName) private fun cdWarnAboutCrlf(project: Project) = CheckboxDescriptor(message("settings.crlf"), PropertyBinding({ projectSettings(project).warnAboutCrlf() }, { projectSettings(project).setWarnAboutCrlf(it) }), groupName = gitOptionGroupName) private fun cdWarnAboutDetachedHead(project: Project) = CheckboxDescriptor(message("settings.detached.head"), PropertyBinding({ projectSettings(project).warnAboutDetachedHead() }, { projectSettings(project).setWarnAboutDetachedHead(it) }), groupName = gitOptionGroupName) private fun cdAutoUpdateOnPush(project: Project) = CheckboxDescriptor(message("settings.auto.update.on.push.rejected"), PropertyBinding({ projectSettings(project).autoUpdateIfPushRejected() }, { projectSettings(project).setAutoUpdateIfPushRejected(it) }), groupName = gitOptionGroupName) private fun cdShowCommitAndPushDialog(project: Project) = CheckboxDescriptor(message("settings.push.dialog"), PropertyBinding({ projectSettings(project).shouldPreviewPushOnCommitAndPush() }, { projectSettings(project).setPreviewPushOnCommitAndPush(it) }), groupName = gitOptionGroupName) private fun cdHidePushDialogForNonProtectedBranches(project: Project) = CheckboxDescriptor(message("settings.push.dialog.for.protected.branches"), PropertyBinding({ projectSettings(project).isPreviewPushProtectedOnly }, { projectSettings(project).isPreviewPushProtectedOnly = it }), groupName = gitOptionGroupName) private val cdOverrideCredentialHelper get() = CheckboxDescriptor(message("settings.credential.helper"), PropertyBinding({ applicationSettings.isUseCredentialHelper }, { applicationSettings.isUseCredentialHelper = it }), groupName = gitOptionGroupName) private fun synchronizeBranchProtectionRules(project: Project) = CheckboxDescriptor(message("settings.synchronize.branch.protection.rules"), PropertyBinding({gitSharedSettings(project).isSynchronizeBranchProtectionRules}, { gitSharedSettings(project).isSynchronizeBranchProtectionRules = it }), groupName = gitOptionGroupName, comment = message("settings.synchronize.branch.protection.rules.description")) private val cdEnableStagingArea get() = CheckboxDescriptor(message("settings.enable.staging.area"), PropertyBinding({ applicationSettings.isStagingAreaEnabled }, { enableStagingArea(it) }), groupName = gitOptionGroupName, comment = message("settings.enable.staging.area.comment")) // @formatter:on internal fun gitOptionDescriptors(project: Project): List<OptionDescription> { val list = mutableListOf( cdAutoUpdateOnPush(project), cdWarnAboutCrlf(project), cdWarnAboutDetachedHead(project), cdEnableStagingArea ) val manager = GitRepositoryManager.getInstance(project) if (manager.moreThanOneRoot()) { list += cdSyncBranches(project) } return list.map(CheckboxDescriptor::asOptionDescriptor) } internal class GitVcsPanel(private val project: Project) : BoundCompositeConfigurable<UnnamedConfigurable>(message("settings.git.option.group"), "project.propVCSSupport.VCSs.Git"), SearchableConfigurable { private val projectSettings get() = GitVcsSettings.getInstance(project) private fun Panel.branchUpdateInfoRow() { row(message("settings.explicitly.check")) { comboBox(EnumComboBoxModel(GitIncomingCheckStrategy::class.java)) .bindItem({ projectSettings.incomingCheckStrategy }, { selectedStrategy -> projectSettings.incomingCheckStrategy = selectedStrategy as GitIncomingCheckStrategy if (!project.isDefault) { GitBranchIncomingOutgoingManager.getInstance(project).updateIncomingScheduling() } }) }.enabledIf(AdvancedSettingsPredicate("git.update.incoming.outgoing.info", disposable!!)) } private fun Panel.protectedBranchesRow() { row(message("settings.protected.branched")) { val sharedSettings = gitSharedSettings(project) val protectedBranchesField = ExpandableTextFieldWithReadOnlyText(ParametersListUtil.COLON_LINE_PARSER, ParametersListUtil.COLON_LINE_JOINER) if (sharedSettings.isSynchronizeBranchProtectionRules) { protectedBranchesField.readOnlyText = ParametersListUtil.COLON_LINE_JOINER.`fun`(sharedSettings.additionalProhibitedPatterns) } cell(protectedBranchesField) .horizontalAlign(HorizontalAlign.FILL) .bind<List<String>>( { ParametersListUtil.COLON_LINE_PARSER.`fun`(it.text) }, { component, value -> component.text = ParametersListUtil.COLON_LINE_JOINER.`fun`(value) }, MutableProperty( { sharedSettings.forcePushProhibitedPatterns }, { sharedSettings.forcePushProhibitedPatterns = it }) ) } indent { row { checkBox(synchronizeBranchProtectionRules(project)) } } } override fun getId() = "vcs.${GitVcs.NAME}" override fun createConfigurables(): List<UnnamedConfigurable> { return VcsEnvCustomizer.EP_NAME.extensionList.mapNotNull { it.getConfigurable(project) } } override fun createPanel(): DialogPanel = panel { createGitExecutableSelectorRow(project, disposable!!) group(message("settings.commit.group.title")) { row { checkBox(cdEnableStagingArea) .enabledIf(StagingAreaAvailablePredicate(project, disposable!!)) } row { checkBox(cdWarnAboutCrlf(project)) } row { checkBox(cdWarnAboutDetachedHead(project)) } row { checkBox(cdAddCherryPickSuffix(project)) } createGpgSignRow(project, disposable!!) } group(message("settings.push.group.title")) { row { checkBox(cdAutoUpdateOnPush(project)) } lateinit var previewPushOnCommitAndPush: Cell<JBCheckBox> row { previewPushOnCommitAndPush = checkBox(cdShowCommitAndPushDialog(project)) } indent { row { checkBox(cdHidePushDialogForNonProtectedBranches(project)) .enabledIf(previewPushOnCommitAndPush.selected) } } protectedBranchesRow() } group(message("settings.update.group.title")) { buttonsGroup { row(message("settings.update.method")) { getUpdateMethods().forEach { saveSetting -> radioButton(saveSetting.methodName, saveSetting) } }.layout(RowLayout.INDEPENDENT) }.bind({ projectSettings.updateMethod }, { projectSettings.updateMethod = it }) buttonsGroup { row(message("settings.clean.working.tree")) { GitSaveChangesPolicy.values().forEach { saveSetting -> radioButton(saveSetting.text, saveSetting) } }.layout(RowLayout.INDEPENDENT) }.bind({ projectSettings.saveChangesPolicy }, { projectSettings.saveChangesPolicy = it }) if (AbstractCommonUpdateAction.showsCustomNotification(listOf(GitVcs.getInstance(project)))) { updateProjectInfoFilter() } } if (project.isDefault || GitRepositoryManager.getInstance(project).moreThanOneRoot()) { row { checkBox(cdSyncBranches(project)) .gap(RightGap.SMALL) contextHelp(DvcsBundle.message("sync.setting.description", GitVcs.DISPLAY_NAME.get())) } } branchUpdateInfoRow() row { checkBox(cdOverrideCredentialHelper) } for (configurable in configurables) { appendDslConfigurable(configurable) } } private fun Panel.updateProjectInfoFilter() { val currentUpdateInfoFilterProperties = MyLogProperties(project.service()) row(message("settings.filter.update.info")) { val storedProperties = project.service<GitUpdateProjectInfoLogProperties>() val roots = ProjectLevelVcsManager.getInstance(project).getRootsUnderVcs(GitVcs.getInstance(project)).toSet() val model = VcsLogClassicFilterUi.FileFilterModel(roots, currentUpdateInfoFilterProperties, null) val component = object : StructureFilterPopupComponent(currentUpdateInfoFilterProperties, model, VcsLogColorManagerImpl(roots)) { override fun shouldDrawLabel(): DrawLabelMode = DrawLabelMode.NEVER override fun shouldIndicateHovering(): Boolean = false override fun getEmptyFilterValue(): String { return ALL_ACTION_TEXT.get() } override fun createUnfocusedBorder(): Border { return FilledRoundedBorder(JBColor.namedColor("Component.borderColor", Gray.xBF), ARC_SIZE, BORDER_SIZE, true) } }.initUi() cell(component) .onIsModified { storedProperties.getFilterValues(STRUCTURE_FILTER.name) != currentUpdateInfoFilterProperties.structureFilter } .onApply { storedProperties.saveFilterValues(STRUCTURE_FILTER.name, currentUpdateInfoFilterProperties.structureFilter) } .onReset { currentUpdateInfoFilterProperties.structureFilter = storedProperties.getFilterValues(STRUCTURE_FILTER.name) model.updateFilterFromProperties() } } } private class MyLogProperties(mainProperties: GitUpdateProjectInfoLogProperties) : MainVcsLogUiProperties by mainProperties { var structureFilter: List<String>? = null override fun getFilterValues(filterName: String): List<String>? = structureFilter.takeIf { filterName == STRUCTURE_FILTER.name } override fun saveFilterValues(filterName: String, values: MutableList<String>?) { if (filterName == STRUCTURE_FILTER.name) { structureFilter = values } } } } private typealias ParserFunction = Function<String, List<String>> private typealias JoinerFunction = Function<List<String>, String> internal class ExpandableTextFieldWithReadOnlyText(lineParser: ParserFunction, private val lineJoiner: JoinerFunction) : ExpandableTextField(lineParser, lineJoiner) { var readOnlyText = "" init { addFocusListener(object : FocusAdapter() { override fun focusLost(e: FocusEvent) { val myComponent = this@ExpandableTextFieldWithReadOnlyText if (e.component == myComponent) { val document = myComponent.document val documentText = document.getText(0, document.length) updateReadOnlyText(documentText) } } }) } override fun setText(t: String?) { if (!t.isNullOrBlank() && t != text) { updateReadOnlyText(t) } super.setText(t) } private fun updateReadOnlyText(@NlsSafe text: String) { if (readOnlyText.isBlank()) return val readOnlySuffix = if (text.isBlank()) readOnlyText else lineJoiner.join("", readOnlyText) // NON-NLS with(emptyText as TextComponentEmptyText) { clear() appendText(text, SimpleTextAttributes.REGULAR_ATTRIBUTES) appendText(readOnlySuffix, SimpleTextAttributes.GRAYED_ATTRIBUTES) setTextToTriggerStatus(text) //this will force status text rendering in case if the text field is not empty } } fun JoinerFunction.join(vararg items: String): String = `fun`(items.toList()) } class StagingAreaAvailablePredicate(val project: Project, val disposable: Disposable) : ComponentPredicate() { override fun addListener(listener: (Boolean) -> Unit) { project.messageBus.connect(disposable).subscribe(CommitModeManager.SETTINGS, object : CommitModeManager.SettingsListener { override fun settingsChanged() { listener(invoke()) } }) } override fun invoke(): Boolean = canEnableStagingArea() } class HasGitRootsPredicate(val project: Project, val disposable: Disposable) : ComponentPredicate() { override fun addListener(listener: (Boolean) -> Unit) { project.messageBus.connect(disposable).subscribe(VcsRepositoryManager.VCS_REPOSITORY_MAPPING_UPDATED, VcsRepositoryMappingListener { listener(invoke()) }) } override fun invoke(): Boolean = GitRepositoryManager.getInstance(project).repositories.size != 0 } class AdvancedSettingsPredicate(val id: String, val disposable: Disposable) : ComponentPredicate() { override fun addListener(listener: (Boolean) -> Unit) { ApplicationManager.getApplication().messageBus.connect(disposable) .subscribe(AdvancedSettingsChangeListener.TOPIC, object : AdvancedSettingsChangeListener { override fun advancedSettingChanged(id: String, oldValue: Any, newValue: Any) { listener(invoke()) } }) } override fun invoke(): Boolean = AdvancedSettings.getBoolean(id) }
apache-2.0
79fb7d0c75c0e0b1fed6af1acf90284e
48.354167
420
0.741603
4.909118
false
true
false
false
google/intellij-community
platform/execution/src/com/intellij/execution/target/TargetEnvironment.kt
2
6733
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.target import com.intellij.execution.ExecutionException import com.intellij.openapi.progress.ProgressIndicator import org.jetbrains.annotations.ApiStatus import java.io.IOException import java.nio.file.Path /** * Represents created target environment. It might be local machine, * local or remote Docker container, SSH machine or any other machine * that is able to run processes on it. */ @ApiStatus.Experimental abstract class TargetEnvironment( open val request: TargetEnvironmentRequest ) { sealed class TargetPath { /** * Request for a certain path on the target machine. If the [absolutePath] does not exist, it should be created. */ data class Persistent(val absolutePath: String) : TargetPath() /** * Request for any not used random path. */ class Temporary @JvmOverloads constructor( /** Any string. An environment implementation may reuse previously created directories for the same hint. */ val hint: String? = null, /** Prefix for the randomly generated directory name */ val prefix: String? = null, /** If null, use `/tmp` or something similar, autodetected. */ val parentDirectory: String? = null ) : TargetPath() { override fun toString(): String = "Temporary(hint=$hint, prefix=$prefix, parentDirectory=$parentDirectory)" override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Temporary // instance with null hint considered unique thus differs from any other instance if (hint == null) return false if (hint != other.hint) return false if (prefix != other.prefix) return false if (parentDirectory != other.parentDirectory) return false return true } override fun hashCode(): Int { // instance with null hint considered unique if (hint == null) return super.hashCode() var result = hint.hashCode() result = 31 * result + (prefix?.hashCode() ?: 0) result = 31 * result + (parentDirectory?.hashCode() ?: 0) return result } } } /** * Mapping of localPath -> Something */ interface MappingWithLocalPath { val localRootPath: Path } /** * Unonditional map between local and remote root. * Targets API do not create this mapping, it just exists */ data class SynchronizedVolume(override val localRootPath: Path, val targetPath: String): MappingWithLocalPath data class UploadRoot @JvmOverloads constructor( override val localRootPath: Path, val targetRootPath: TargetPath, /** * If true, IDE should try to remove the directory when [shutdown] is being called. * TODO maybe get rid of it? It causes a race between two environments using the same upload root. */ val removeAtShutdown: Boolean = false ): MappingWithLocalPath { var volumeData: TargetEnvironmentType.TargetSpecificVolumeData? = null // excluded from equals / hashcode } data class DownloadRoot @JvmOverloads constructor( /** * A certain path on the local machine or null for creating a temporary directory. * The temporary directory should be deleted with [shutdown]. */ val localRootPath: Path?, /** TODO Should [Temprorary] paths with the same hint point on the same directory for uploads and downloads? */ val targetRootPath: TargetPath, /** * If not null, target should try to persist the contents of the folder between the sessions, * and make it available for the next session requests with the same persistentId */ val persistentId: String? = null ) /** Target TCP port forwardings. */ data class TargetPortBinding( val local: Int?, /** There is no robust way to get a random free port inside the Docker target. */ val target: Int ) /** Local TCP port forwardings. */ data class LocalPortBinding( val local: Int, val target: Int? ) interface Volume { val localRoot: Path val targetRoot: String /** * Returns the resulting remote path (even if it's predictable, many tests rely on specific, usually relative paths) * of uploading `"$localRootPath/$relativePath"` to `"$targetRoot/$relativePath"`. * Does not perform any kind of bytes transfer. */ @Throws(IOException::class) fun resolveTargetPath(relativePath: String): String } /** * TODO Do we really need to have two different kinds of bind mounts? * Docker and SSH provides bi-directional access to the target files. */ interface UploadableVolume : Volume { /** * Upload `"$localRootPath/$relativePath"` to `"$targetRoot/$relativePath"` */ @Throws(IOException::class) fun upload(relativePath: String, targetProgressIndicator: TargetProgressIndicator) } interface DownloadableVolume : Volume { @Throws(IOException::class) fun download(relativePath: String, progressIndicator: ProgressIndicator) } open val uploadVolumes: Map<UploadRoot, UploadableVolume> get() = throw UnsupportedOperationException() open val downloadVolumes: Map<DownloadRoot, DownloadableVolume> get() = throw UnsupportedOperationException() /** Values are local ports. */ open val targetPortBindings: Map<TargetPortBinding, Int> get() = throw UnsupportedOperationException() open val localPortBindings: Map<LocalPortBinding, ResolvedPortBinding> get() = throw UnsupportedOperationException() // TODO There are planned further modifications related to this method: // 1. Get rid of any `Promise` in `TargetedCommandLine`. // Likely, there will be a completely new class similar to the `GeneralCommandLine` with adapter from `TargetedCommandLine`. // 2. Call of this method should consume the environment, i.e. there will be no need in the `shutdown` method. // Therefore, to indicate the disposable nature of environments, the method might be moved to the `TargetEnvironmentFactory`. @Throws(ExecutionException::class) abstract fun createProcess(commandLine: TargetedCommandLine, indicator: ProgressIndicator): Process abstract val targetPlatform: TargetPlatform //FIXME: document abstract fun shutdown() interface BatchUploader { fun canUploadInBatches(): Boolean @Throws(IOException::class) fun runBatchUpload(uploads: List<Pair<UploadableVolume, String>>, targetProgressIndicator: TargetProgressIndicator) } }
apache-2.0
1d4d83db0d91a756811a7791704d1840
34.072917
140
0.699094
4.911014
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SelfLinkedEntityImpl.kt
1
8159
// 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.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class SelfLinkedEntityImpl(val dataSource: SelfLinkedEntityData) : SelfLinkedEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(SelfLinkedEntity::class.java, SelfLinkedEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } override val parentEntity: SelfLinkedEntity? get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: SelfLinkedEntityData?) : ModifiableWorkspaceEntityBase<SelfLinkedEntity>(), SelfLinkedEntity.Builder { constructor() : this(SelfLinkedEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity SelfLinkedEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as SelfLinkedEntity this.entitySource = dataSource.entitySource if (parents != null) { this.parentEntity = parents.filterIsInstance<SelfLinkedEntity>().singleOrNull() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var parentEntity: SelfLinkedEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? SelfLinkedEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? SelfLinkedEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override fun getEntityData(): SelfLinkedEntityData = result ?: super.getEntityData() as SelfLinkedEntityData override fun getEntityClass(): Class<SelfLinkedEntity> = SelfLinkedEntity::class.java } } class SelfLinkedEntityData : WorkspaceEntityData<SelfLinkedEntity>() { override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SelfLinkedEntity> { val modifiable = SelfLinkedEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): SelfLinkedEntity { return getCached(snapshot) { val entity = SelfLinkedEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return SelfLinkedEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return SelfLinkedEntity(entitySource) { this.parentEntity = parents.filterIsInstance<SelfLinkedEntity>().singleOrNull() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as SelfLinkedEntityData if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as SelfLinkedEntityData return true } override fun hashCode(): Int { var result = entitySource.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
17c83a7cf802e971167c3ef91cfa514c
35.918552
153
0.705233
5.280906
false
false
false
false
RuneSuite/client
api/src/main/java/org/runestar/client/api/game/NpcDefinition.kt
1
1015
package org.runestar.client.api.game import org.runestar.client.raw.access.XNPCType inline class NpcDefinition(val accessor: XNPCType) { val id get() = accessor.id val actions: Array<String?> get() = accessor.op val name: String? get() = accessor.name.takeUnless { it == "null" } val headIconPrayer: Int get() = accessor.headIconPrayer var drawMapDot: Boolean get() = accessor.drawMapDot set(value) { accessor.drawMapDot = value } fun recolor(from: HslColor, to: HslColor) { if (accessor.recol_s == null) { accessor.recol_s = shortArrayOf(from.packed) accessor.recol_d = shortArrayOf(to.packed) } else { val i = accessor.recol_s.indexOf(from.packed) if (i == -1) { accessor.recol_s = accessor.recol_s.plus(from.packed) accessor.recol_d = accessor.recol_d.plus(to.packed) } else { accessor.recol_d[i] = to.packed } } } }
mit
d1a35f014482f4d0e5b6fee813207808
29.787879
71
0.592118
3.5
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/grammar/dumb/Rule.kt
1
2000
package org.jetbrains.grammar.dumb import com.intellij.psi.tree.IElementType import java.util.ArrayList import java.util.HashSet class Rule(val name : String, val variants : List<Variant>, val left : List<Variant>) { var done : Boolean = false var canBeEmpty : Boolean = false var first : Set<IElementType>? = null override fun toString() : String { val n = name + ":\n" val v = " variants: ${variants}\n" val l = if (left.isNotEmpty()) " left: ${left}\n" else "" return n + v + l } fun makeAnalysis(grammar : Map<String, Rule>) { if (done) { return } for (variant in variants) { variant.makeAnalysis(grammar) } for (variant in variants) { canBeEmpty = canBeEmpty || variant.isCanBeEmpty() } val result = HashSet<IElementType>() for (variant in variants) { if (variant is NonTerminalVariant) { if (variant.first != null) { result.addAll(variant.first!!) } else { return } } } if (canBeEmpty) { for (lVariant in left) { val next = (lVariant as NonTerminalVariant).next for (variant in next) { val term = (variant as NonTerminalVariant).term if (term is Terminal){ result.add(term.tokenType) } else { variant.makeAnalysis(grammar) result.addAll(variant.first!!) } } } } first = HashSet(result) } fun makeDeepAnalysis(grammar: Map<String, Rule>) { for (variant in variants) { variant.makeDeepAnalysis(grammar) } for (variant in left) { variant.makeDeepAnalysis(grammar) } } }
apache-2.0
82ed234dc9dd1e57e8f3fd30666bad54
26.410959
67
0.494
4.807692
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/code-insight/inspections-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/inspections/ImplicitThisInspection.kt
1
7152
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.k2.codeinsight.inspections import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.components.KtImplicitReceiver import org.jetbrains.kotlin.analysis.api.symbols.* import org.jetbrains.kotlin.analysis.api.types.KtFunctionalType import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.applicators.* import org.jetbrains.kotlin.idea.codeinsight.api.applicable.inspections.AbstractKotlinApplicableInspectionWithContext import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicabilityRange import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.renderer.render internal class ImplicitThisInspection : AbstractKotlinApplicableInspectionWithContext<KtExpression, ImplicitThisInspection.ImplicitReceiverInfo>(KtExpression::class) { data class ImplicitReceiverInfo( val receiverLabel: Name?, val isUnambiguousLabel: Boolean ) override fun getProblemDescription(element: KtExpression, context: ImplicitReceiverInfo): String = KotlinBundle.message("inspection.implicit.this.display.name") override fun getActionFamilyName(): String = KotlinBundle.message("inspection.implicit.this.action.name") override fun getApplicabilityRange(): KotlinApplicabilityRange<KtExpression> = ApplicabilityRanges.SELF override fun isApplicableByPsi(element: KtExpression): Boolean { return when (element) { is KtSimpleNameExpression -> { if (element !is KtNameReferenceExpression) return false if (element.parent is KtThisExpression) return false if (element.parent is KtCallableReferenceExpression) return false if (element.isSelectorOfDotQualifiedExpression()) return false val parent = element.parent if (parent is KtCallExpression && parent.isSelectorOfDotQualifiedExpression()) return false true } is KtCallableReferenceExpression -> element.receiverExpression == null else -> false } } context(KtAnalysisSession) override fun prepareContext(element: KtExpression): ImplicitReceiverInfo? { val reference = if (element is KtCallableReferenceExpression) element.callableReference else element val declarationSymbol = reference.mainReference?.resolveToSymbol() ?: return null // Get associated class symbol on declaration-site val declarationAssociatedClass = getAssociatedClass(declarationSymbol) ?: return null // Getting the implicit receiver val allImplicitReceivers = reference.containingKtFile.getScopeContextForPosition(reference).implicitReceivers return getImplicitReceiverInfoOfClass(allImplicitReceivers, declarationAssociatedClass) } override fun apply(element: KtExpression, context: ImplicitReceiverInfo, project: Project, editor: Editor?) { element.addImplicitThis(context) } } context(KtAnalysisSession) private fun getAssociatedClass(symbol: KtSymbol): KtClassOrObjectSymbol? { // both variables and functions are callable and only they can be referenced by "this" if (symbol !is KtCallableSymbol) return null return when (symbol) { is KtFunctionSymbol, is KtPropertySymbol -> if (symbol.isExtension) symbol.receiverType?.expandedClassSymbol else symbol.getContainingSymbol() as? KtClassOrObjectSymbol is KtVariableLikeSymbol -> { val variableType = symbol.returnType as? KtFunctionalType variableType?.receiverType?.expandedClassSymbol } else -> null } } context(KtAnalysisSession) private fun getImplicitReceiverInfoOfClass( implicitReceivers: List<KtImplicitReceiver>, associatedClass: KtClassOrObjectSymbol ): ImplicitThisInspection.ImplicitReceiverInfo? { // We can't use "this" with label if the label is already taken val alreadyReservedLabels = mutableListOf<Name>() var isInnermostReceiver = true for (receiver in implicitReceivers) { val (receiverClass, receiverLabel) = getImplicitReceiverClassAndTag(receiver) ?: return null if (receiverClass == associatedClass) { if (receiverLabel in alreadyReservedLabels) return null return if (isInnermostReceiver || receiverLabel != null) ImplicitThisInspection.ImplicitReceiverInfo( receiverLabel, isInnermostReceiver ) else null } receiverLabel?.let { alreadyReservedLabels.add(it) } isInnermostReceiver = false } return null } context(KtAnalysisSession) private fun getImplicitReceiverClassAndTag(receiver: KtImplicitReceiver): Pair<KtClassOrObjectSymbol, Name?>? { val associatedClass = receiver.type.expandedClassSymbol ?: return null val associatedTag: Name? = when (val receiverSymbol = receiver.ownerSymbol) { is KtClassOrObjectSymbol -> receiverSymbol.name is KtAnonymousFunctionSymbol -> { val receiverPsi = receiverSymbol.psi val potentialLabeledPsi = receiverPsi?.parent?.parent if (potentialLabeledPsi is KtLabeledExpression) potentialLabeledPsi.getLabelNameAsName() else { val potentialCallExpression = potentialLabeledPsi?.parent as? KtCallExpression val potentialCallNameReference = (potentialCallExpression?.calleeExpression as? KtNameReferenceExpression) potentialCallNameReference?.getReferencedNameAsName() } } is KtFunctionSymbol -> receiverSymbol.name else -> null } return Pair(associatedClass, associatedTag) } private fun KtExpression.isSelectorOfDotQualifiedExpression(): Boolean { val parent = parent return parent is KtDotQualifiedExpression && parent.selectorExpression == this } private fun KtExpression.addImplicitThis(input: ImplicitThisInspection.ImplicitReceiverInfo) { val reference = if (this is KtCallableReferenceExpression) callableReference else this val thisExpressionText = if (input.isUnambiguousLabel) "this" else "this@${input.receiverLabel?.render()}" val factory = KtPsiFactory(project) with(reference) { when (parent) { is KtCallExpression -> parent.replace(factory.createExpressionByPattern("$0.$1", thisExpressionText, parent)) is KtCallableReferenceExpression -> parent.replace( factory.createExpressionByPattern( "$0::$1", thisExpressionText, this ) ) else -> this.replace(factory.createExpressionByPattern("$0.$1", thisExpressionText, this)) } } }
apache-2.0
bb9e09fe16456f6261655bcd9d7f9c0a
46.364238
136
0.73448
5.488872
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/stage/bg/TengokuBackground.kt
2
2391
package io.github.chrislo27.rhre3.stage.bg import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.glutils.ShapeRenderer import com.badlogic.gdx.math.MathUtils import io.github.chrislo27.rhre3.RHRE3 import io.github.chrislo27.toolboks.util.gdxutils.drawQuad class TengokuBackground(id: String, maxParticles: Int = 40, val topColor: Color = Color.valueOf("4048e0"), val bottomColor: Color = Color.valueOf("d020a0"), var cycleSpeed: Float = 1f / 20f) : ParticleBasedBackground(id, maxParticles) { class Square(x: Float, y: Float, size: Float = MathUtils.random(20f, 80f), speedX: Float = MathUtils.random(0.075f, 0.2f), speedY: Float = -MathUtils.random(0.075f, 0.2f), rotSpeed: Float = MathUtils.random(90f, 200f) * MathUtils.randomSign(), rotation: Float = MathUtils.random(360f)) : Particle(x, y, size, size, speedX, speedY, rotSpeed, rotation, "menu_bg_square") private val hsv: FloatArray = FloatArray(3) override fun renderBackground(camera: OrthographicCamera, batch: SpriteBatch, shapeRenderer: ShapeRenderer, delta: Float) { val width = camera.viewportWidth val height = camera.viewportHeight val ratioX = width / RHRE3.WIDTH val ratioY = height / RHRE3.HEIGHT if (cycleSpeed > 0f) { topColor.toHsv(hsv) hsv[0] = (hsv[0] - delta * cycleSpeed * 360f) % 360f topColor.fromHsv(hsv) bottomColor.toHsv(hsv) hsv[0] = (hsv[0] - delta * cycleSpeed * 360f) % 360f bottomColor.fromHsv(hsv) } batch.drawQuad(0f, 0f, bottomColor, width, 0f, bottomColor, width, height, topColor, 0f, height, topColor) // Remove OoB squares particles.removeIf { it.x > 1f + (ratioX * it.sizeX) / width || it.y < -(ratioY * it.sizeY) / height } } override fun createParticle(initial: Boolean): Particle? { return if (!initial) { Square(-0.5f, 1f + MathUtils.random(1f)) } else { Square(MathUtils.random(1f), MathUtils.random(1f)) } } }
gpl-3.0
81830415f37e55a6e8cea200d41b0063
38.213115
127
0.606859
3.801272
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/toolboks/ui/Button.kt
2
2843
package io.github.chrislo27.toolboks.ui import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.glutils.ShapeRenderer import io.github.chrislo27.toolboks.ToolboksScreen import io.github.chrislo27.toolboks.util.gdxutils.fillRect open class Button<S : ToolboksScreen<*, *>> : UIElement<S>, Palettable, Backgrounded { override var palette: UIPalette constructor(palette: UIPalette, parent: UIElement<S>, stage: Stage<S>) : super(parent, stage) { this.palette = palette this.labels = mutableListOf() } val labels: List<Label<S>> var enabled = true override var background: Boolean = true fun addLabel(l: Label<S>) { if (l.parent !== this) { throw IllegalArgumentException("Label parent must be this") } labels as MutableList if (l !in labels) { labels.add(l) } } fun addLabel(index: Int, l: Label<S>) { if (l.parent !== this) { throw IllegalArgumentException("Label parent must be this") } labels as MutableList if (l !in labels) { labels.add(index.coerceIn(0, labels.size), l) } } fun removeLabel(l: Label<S>) { if (l.parent !== this) { throw IllegalArgumentException("Label parent must be this") } labels as MutableList labels.remove(l) } override fun canBeClickedOn(): Boolean { return enabled } override fun render(screen: S, batch: SpriteBatch, shapeRenderer: ShapeRenderer) { if (background) { val oldBatchColor = batch.color if (wasClickedOn && enabled) { batch.color = palette.clickedBackColor } else if (isMouseOver() && enabled) { batch.color = palette.highlightedBackColor } else { batch.color = palette.backColor } batch.fillRect(location.realX, location.realY, location.realWidth, location.realHeight) batch.color = oldBatchColor } labels.forEach { if (it.visible) { it.render(screen, batch, shapeRenderer) } } if (!enabled) { val oldBatchColor = batch.packedColor batch.setColor(0.15f, 0.15f, 0.15f, 0.75f) batch.fillRect(location.realX, location.realY, location.realWidth, location.realHeight) batch.packedColor = oldBatchColor } } override fun onResize(width: Float, height: Float, pixelUnitX: Float, pixelUnitY: Float) { super.onResize(width, height, pixelUnitX, pixelUnitY) labels.forEach { it.onResize(this.location.realWidth, this.location.realHeight, pixelUnitX, pixelUnitY) } } }
gpl-3.0
03367f804348151fa4760f1e5fe4c34a
28.625
99
0.596201
4.320669
false
false
false
false
square/okio
okio/src/commonTest/kotlin/okio/CommonBufferTest.kt
1
14086
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okio import okio.ByteString.Companion.decodeHex import kotlin.random.Random import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue /** * Tests solely for the behavior of Buffer's implementation. For generic BufferedSink or * BufferedSource behavior use BufferedSinkTest or BufferedSourceTest, respectively. */ class CommonBufferTest { @Test fun readAndWriteUtf8() { val buffer = Buffer() buffer.writeUtf8("ab") assertEquals(2, buffer.size) buffer.writeUtf8("cdef") assertEquals(6, buffer.size) assertEquals("abcd", buffer.readUtf8(4)) assertEquals(2, buffer.size) assertEquals("ef", buffer.readUtf8(2)) assertEquals(0, buffer.size) assertFailsWith<EOFException> { buffer.readUtf8(1) } } /** Buffer's toString is the same as ByteString's. */ @Test fun bufferToString() { assertEquals("[size=0]", Buffer().toString()) assertEquals( "[text=a\\r\\nb\\nc\\rd\\\\e]", Buffer().writeUtf8("a\r\nb\nc\rd\\e").toString() ) assertEquals( "[text=Tyrannosaur]", Buffer().writeUtf8("Tyrannosaur").toString() ) assertEquals( "[text=təˈranəˌsôr]", Buffer() .write("74c999cb8872616ec999cb8c73c3b472".decodeHex()) .toString() ) assertEquals( "[hex=0000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000]", Buffer().write(ByteArray(64)).toString() ) } @Test fun multipleSegmentBuffers() { val buffer = Buffer() buffer.writeUtf8('a'.repeat(1000)) buffer.writeUtf8('b'.repeat(2500)) buffer.writeUtf8('c'.repeat(5000)) buffer.writeUtf8('d'.repeat(10000)) buffer.writeUtf8('e'.repeat(25000)) buffer.writeUtf8('f'.repeat(50000)) assertEquals('a'.repeat(999), buffer.readUtf8(999)) // a...a assertEquals("a" + 'b'.repeat(2500) + "c", buffer.readUtf8(2502)) // ab...bc assertEquals('c'.repeat(4998), buffer.readUtf8(4998)) // c...c assertEquals("c" + 'd'.repeat(10000) + "e", buffer.readUtf8(10002)) // cd...de assertEquals('e'.repeat(24998), buffer.readUtf8(24998)) // e...e assertEquals("e" + 'f'.repeat(50000), buffer.readUtf8(50001)) // ef...f assertEquals(0, buffer.size) } @Test fun fillAndDrainPool() { val buffer = Buffer() // Take 2 * MAX_SIZE segments. This will drain the pool, even if other tests filled it. buffer.write(ByteArray(SegmentPool.MAX_SIZE)) buffer.write(ByteArray(SegmentPool.MAX_SIZE)) assertEquals(0, SegmentPool.byteCount) // Recycle MAX_SIZE segments. They're all in the pool. buffer.skip(SegmentPool.MAX_SIZE.toLong()) assertEquals(SegmentPool.MAX_SIZE, SegmentPool.byteCount) // Recycle MAX_SIZE more segments. The pool is full so they get garbage collected. buffer.skip(SegmentPool.MAX_SIZE.toLong()) assertEquals(SegmentPool.MAX_SIZE, SegmentPool.byteCount) // Take MAX_SIZE segments to drain the pool. buffer.write(ByteArray(SegmentPool.MAX_SIZE)) assertEquals(0, SegmentPool.byteCount) // Take MAX_SIZE more segments. The pool is drained so these will need to be allocated. buffer.write(ByteArray(SegmentPool.MAX_SIZE)) assertEquals(0, SegmentPool.byteCount) } @Test fun moveBytesBetweenBuffersShareSegment() { val size = Segment.SIZE / 2 - 1 val segmentSizes = moveBytesBetweenBuffers('a'.repeat(size), 'b'.repeat(size)) assertEquals(listOf(size * 2), segmentSizes) } @Test fun moveBytesBetweenBuffersReassignSegment() { val size = Segment.SIZE / 2 + 1 val segmentSizes = moveBytesBetweenBuffers('a'.repeat(size), 'b'.repeat(size)) assertEquals(listOf(size, size), segmentSizes) } @Test fun moveBytesBetweenBuffersMultipleSegments() { val size = 3 * Segment.SIZE + 1 val segmentSizes = moveBytesBetweenBuffers('a'.repeat(size), 'b'.repeat(size)) assertEquals( listOf( Segment.SIZE, Segment.SIZE, Segment.SIZE, 1, Segment.SIZE, Segment.SIZE, Segment.SIZE, 1 ), segmentSizes ) } private fun moveBytesBetweenBuffers(vararg contents: String): List<Int> { val expected = StringBuilder() val buffer = Buffer() for (s in contents) { val source = Buffer() source.writeUtf8(s) buffer.writeAll(source) expected.append(s) } val segmentSizes = segmentSizes(buffer) assertEquals(expected.toString(), buffer.readUtf8(expected.length.toLong())) return segmentSizes } /** The big part of source's first segment is being moved. */ @Test fun writeSplitSourceBufferLeft() { val writeSize = Segment.SIZE / 2 + 1 val sink = Buffer() sink.writeUtf8('b'.repeat(Segment.SIZE - 10)) val source = Buffer() source.writeUtf8('a'.repeat(Segment.SIZE * 2)) sink.write(source, writeSize.toLong()) assertEquals(listOf(Segment.SIZE - 10, writeSize), segmentSizes(sink)) assertEquals(listOf(Segment.SIZE - writeSize, Segment.SIZE), segmentSizes(source)) } /** The big part of source's first segment is staying put. */ @Test fun writeSplitSourceBufferRight() { val writeSize = Segment.SIZE / 2 - 1 val sink = Buffer() sink.writeUtf8('b'.repeat(Segment.SIZE - 10)) val source = Buffer() source.writeUtf8('a'.repeat(Segment.SIZE * 2)) sink.write(source, writeSize.toLong()) assertEquals(listOf(Segment.SIZE - 10, writeSize), segmentSizes(sink)) assertEquals(listOf(Segment.SIZE - writeSize, Segment.SIZE), segmentSizes(source)) } @Test fun writePrefixDoesntSplit() { val sink = Buffer() sink.writeUtf8('b'.repeat(10)) val source = Buffer() source.writeUtf8('a'.repeat(Segment.SIZE * 2)) sink.write(source, 20) assertEquals(listOf(30), segmentSizes(sink)) assertEquals(listOf(Segment.SIZE - 20, Segment.SIZE), segmentSizes(source)) assertEquals(30, sink.size) assertEquals((Segment.SIZE * 2 - 20).toLong(), source.size) } @Test fun writePrefixDoesntSplitButRequiresCompact() { val sink = Buffer() sink.writeUtf8('b'.repeat(Segment.SIZE - 10)) // limit = size - 10 sink.readUtf8((Segment.SIZE - 20).toLong()) // pos = size = 20 val source = Buffer() source.writeUtf8('a'.repeat(Segment.SIZE * 2)) sink.write(source, 20) assertEquals(listOf(30), segmentSizes(sink)) assertEquals(listOf(Segment.SIZE - 20, Segment.SIZE), segmentSizes(source)) assertEquals(30, sink.size) assertEquals((Segment.SIZE * 2 - 20).toLong(), source.size) } @Test fun moveAllRequestedBytesWithRead() { val sink = Buffer() sink.writeUtf8('a'.repeat(10)) val source = Buffer() source.writeUtf8('b'.repeat(15)) assertEquals(10, source.read(sink, 10)) assertEquals(20, sink.size) assertEquals(5, source.size) assertEquals('a'.repeat(10) + 'b'.repeat(10), sink.readUtf8(20)) } @Test fun moveFewerThanRequestedBytesWithRead() { val sink = Buffer() sink.writeUtf8('a'.repeat(10)) val source = Buffer() source.writeUtf8('b'.repeat(20)) assertEquals(20, source.read(sink, 25)) assertEquals(30, sink.size) assertEquals(0, source.size) assertEquals('a'.repeat(10) + 'b'.repeat(20), sink.readUtf8(30)) } @Test fun indexOfWithOffset() { val buffer = Buffer() val halfSegment = Segment.SIZE / 2 buffer.writeUtf8('a'.repeat(halfSegment)) buffer.writeUtf8('b'.repeat(halfSegment)) buffer.writeUtf8('c'.repeat(halfSegment)) buffer.writeUtf8('d'.repeat(halfSegment)) assertEquals(0, buffer.indexOf('a'.code.toByte(), 0)) assertEquals((halfSegment - 1).toLong(), buffer.indexOf('a'.code.toByte(), (halfSegment - 1).toLong())) assertEquals(halfSegment.toLong(), buffer.indexOf('b'.code.toByte(), (halfSegment - 1).toLong())) assertEquals((halfSegment * 2).toLong(), buffer.indexOf('c'.code.toByte(), (halfSegment - 1).toLong())) assertEquals((halfSegment * 3).toLong(), buffer.indexOf('d'.code.toByte(), (halfSegment - 1).toLong())) assertEquals((halfSegment * 3).toLong(), buffer.indexOf('d'.code.toByte(), (halfSegment * 2).toLong())) assertEquals((halfSegment * 3).toLong(), buffer.indexOf('d'.code.toByte(), (halfSegment * 3).toLong())) assertEquals((halfSegment * 4 - 1).toLong(), buffer.indexOf('d'.code.toByte(), (halfSegment * 4 - 1).toLong())) } @Test fun byteAt() { val buffer = Buffer() buffer.writeUtf8("a") buffer.writeUtf8('b'.repeat(Segment.SIZE)) buffer.writeUtf8("c") assertEquals('a'.code.toLong(), buffer[0].toLong()) assertEquals('a'.code.toLong(), buffer[0].toLong()) // getByte doesn't mutate! assertEquals('c'.code.toLong(), buffer[buffer.size - 1].toLong()) assertEquals('b'.code.toLong(), buffer[buffer.size - 2].toLong()) assertEquals('b'.code.toLong(), buffer[buffer.size - 3].toLong()) } @Test fun getByteOfEmptyBuffer() { val buffer = Buffer() assertFailsWith<IndexOutOfBoundsException> { buffer[0] } } @Test fun writePrefixToEmptyBuffer() { val sink = Buffer() val source = Buffer() source.writeUtf8("abcd") sink.write(source, 2) assertEquals("ab", sink.readUtf8(2)) } @Suppress("ReplaceAssertBooleanWithAssertEquality") @Test fun equalsAndHashCodeEmpty() { val a = Buffer() val b = Buffer() assertTrue(a == b) assertTrue(a.hashCode() == b.hashCode()) } @Suppress("ReplaceAssertBooleanWithAssertEquality") @Test fun equalsAndHashCode() { val a = Buffer().writeUtf8("dog") val b = Buffer().writeUtf8("hotdog") assertFalse(a == b) assertFalse(a.hashCode() == b.hashCode()) b.readUtf8(3) // Leaves b containing 'dog'. assertTrue(a == b) assertTrue(a.hashCode() == b.hashCode()) } @Suppress("ReplaceAssertBooleanWithAssertEquality") @Test fun equalsAndHashCodeSpanningSegments() { val data = ByteArray(1024 * 1024) val dice = Random(0) dice.nextBytes(data) val a = bufferWithRandomSegmentLayout(dice, data) val b = bufferWithRandomSegmentLayout(dice, data) assertTrue(a == b) assertTrue(a.hashCode() == b.hashCode()) data[data.size / 2]++ // Change a single byte. val c = bufferWithRandomSegmentLayout(dice, data) assertFalse(a == c) assertFalse(a.hashCode() == c.hashCode()) } /** * When writing data that's already buffered, there's no reason to page the * data by segment. */ @Test fun readAllWritesAllSegmentsAtOnce() { val write1 = Buffer().writeUtf8( 'a'.repeat(Segment.SIZE) + 'b'.repeat(Segment.SIZE) + 'c'.repeat(Segment.SIZE) ) val source = Buffer().writeUtf8( 'a'.repeat(Segment.SIZE) + 'b'.repeat(Segment.SIZE) + 'c'.repeat(Segment.SIZE) ) val mockSink = MockSink() assertEquals((Segment.SIZE * 3).toLong(), source.readAll(mockSink)) assertEquals(0, source.size) mockSink.assertLog("write($write1, ${write1.size})") } @Test fun writeAllMultipleSegments() { val source = Buffer().writeUtf8('a'.repeat(Segment.SIZE * 3)) val sink = Buffer() assertEquals((Segment.SIZE * 3).toLong(), sink.writeAll(source)) assertEquals(0, source.size) assertEquals('a'.repeat(Segment.SIZE * 3), sink.readUtf8()) } @Test fun copyTo() { val source = Buffer() source.writeUtf8("party") val target = Buffer() source.copyTo(target, 1, 3) assertEquals("art", target.readUtf8()) assertEquals("party", source.readUtf8()) } @Test fun copyToOnSegmentBoundary() { val `as` = 'a'.repeat(Segment.SIZE) val bs = 'b'.repeat(Segment.SIZE) val cs = 'c'.repeat(Segment.SIZE) val ds = 'd'.repeat(Segment.SIZE) val source = Buffer() source.writeUtf8(`as`) source.writeUtf8(bs) source.writeUtf8(cs) val target = Buffer() target.writeUtf8(ds) source.copyTo(target, `as`.length.toLong(), (bs.length + cs.length).toLong()) assertEquals(ds + bs + cs, target.readUtf8()) } @Test fun copyToOffSegmentBoundary() { val `as` = 'a'.repeat(Segment.SIZE - 1) val bs = 'b'.repeat(Segment.SIZE + 2) val cs = 'c'.repeat(Segment.SIZE - 4) val ds = 'd'.repeat(Segment.SIZE + 8) val source = Buffer() source.writeUtf8(`as`) source.writeUtf8(bs) source.writeUtf8(cs) val target = Buffer() target.writeUtf8(ds) source.copyTo(target, `as`.length.toLong(), (bs.length + cs.length).toLong()) assertEquals(ds + bs + cs, target.readUtf8()) } @Test fun copyToSourceAndTargetCanBeTheSame() { val `as` = 'a'.repeat(Segment.SIZE) val bs = 'b'.repeat(Segment.SIZE) val source = Buffer() source.writeUtf8(`as`) source.writeUtf8(bs) source.copyTo(source, 0, source.size) assertEquals(`as` + bs + `as` + bs, source.readUtf8()) } @Test fun copyToEmptySource() { val source = Buffer() val target = Buffer().writeUtf8("aaa") source.copyTo(target, 0L, 0L) assertEquals("", source.readUtf8()) assertEquals("aaa", target.readUtf8()) } @Test fun copyToEmptyTarget() { val source = Buffer().writeUtf8("aaa") val target = Buffer() source.copyTo(target, 0L, 3L) assertEquals("aaa", source.readUtf8()) assertEquals("aaa", target.readUtf8()) } @Test fun snapshotReportsAccurateSize() { val buf = Buffer().write(byteArrayOf(0, 1, 2, 3)) assertEquals(1, buf.snapshot(1).size) } }
apache-2.0
6c57be7df0cd10faeee794b0438d8d5f
31.746512
115
0.665933
3.703577
false
true
false
false
Skatteetaten/boober
src/main/kotlin/no/skatteetaten/aurora/boober/feature/SecretVaultFeature.kt
1
14095
package no.skatteetaten.aurora.boober.feature import com.fkorotkov.kubernetes.metadata import com.fkorotkov.kubernetes.newEnvVar import com.fkorotkov.kubernetes.newSecret import com.fkorotkov.kubernetes.secretKeyRef import com.fkorotkov.kubernetes.valueFrom import io.fabric8.kubernetes.api.model.EnvVar import no.skatteetaten.aurora.boober.model.AuroraConfigFieldHandler import no.skatteetaten.aurora.boober.model.AuroraContextCommand import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec import no.skatteetaten.aurora.boober.model.AuroraResource import no.skatteetaten.aurora.boober.model.addEnvVarsToMainContainers import no.skatteetaten.aurora.boober.model.findSubKeys import no.skatteetaten.aurora.boober.service.AuroraDeploymentSpecValidationException import no.skatteetaten.aurora.boober.service.UnauthorizedAccessException import no.skatteetaten.aurora.boober.service.resourceprovisioning.VaultProvider import no.skatteetaten.aurora.boober.service.resourceprovisioning.VaultRequest import no.skatteetaten.aurora.boober.service.resourceprovisioning.VaultSecretEnvResult import no.skatteetaten.aurora.boober.utils.addIfNotNull import no.skatteetaten.aurora.boober.utils.boolean import no.skatteetaten.aurora.boober.utils.ensureEndsWith import no.skatteetaten.aurora.boober.utils.ensureStartWith import no.skatteetaten.aurora.boober.utils.filterProperties import no.skatteetaten.aurora.boober.utils.normalizeKubernetesName import no.skatteetaten.aurora.boober.utils.takeIfNotEmpty import org.apache.commons.codec.binary.Base64 import org.springframework.stereotype.Service private const val SECRETS_CONTEXT_KEY = "secrets" private val FeatureContext.secrets: List<AuroraSecret> get() = this.getContextKey(SECRETS_CONTEXT_KEY) // also used in AzureFeature fun AuroraDeploymentSpec.secretEnvName(secretVaultName: String): String = secretVaultName .ensureStartWith(this.name, "-") .ensureEndsWith("vault", "-") .lowercase().replace("_", "-") @Service class SecretVaultFeature( val vaultProvider: VaultProvider ) : Feature { fun secretVaultKeyMappingHandlers(cmd: AuroraContextCommand) = cmd.applicationFiles.find { it.asJsonNode.at("/secretVault/keyMappings") != null }?.let { AuroraConfigFieldHandler("secretVault/keyMappings") } override fun handlers(header: AuroraDeploymentSpec, cmd: AuroraContextCommand): Set<AuroraConfigFieldHandler> { val secretVaultsHandlers = cmd.applicationFiles.findSubKeys("secretVaults").flatMap { key -> listOf( AuroraConfigFieldHandler( "secretVaults/$key/name", defaultValue = key ), AuroraConfigFieldHandler( "secretVaults/$key/enabled", validator = { it.boolean() }, defaultValue = true ), AuroraConfigFieldHandler( "secretVaults/$key/file", defaultValue = "latest.properties" ), AuroraConfigFieldHandler("secretVaults/$key/keys"), AuroraConfigFieldHandler("secretVaults/$key/keyMappings") ) } return listOf( AuroraConfigFieldHandler("secretVault"), AuroraConfigFieldHandler("secretVault/name"), AuroraConfigFieldHandler("secretVault/keys") ) .addIfNotNull(secretVaultKeyMappingHandlers(cmd)) .addIfNotNull(secretVaultsHandlers) .toSet() } override fun createContext(spec: AuroraDeploymentSpec, cmd: AuroraContextCommand, validationContext: Boolean): Map<String, Any> { return mapOf(SECRETS_CONTEXT_KEY to getSecretVaults(spec, cmd)) } // TODO: Room for lots of better refactorings here. override fun validate( adc: AuroraDeploymentSpec, fullValidation: Boolean, context: FeatureContext ): List<Exception> { val secrets = context.secrets val shallowValidation = validateSecretNames(secrets) if (!fullValidation) return shallowValidation return shallowValidation .addIfNotNull(validateVaultExistence(secrets, adc.affiliation)) .addIfNotNull(validateKeyMappings(secrets)) .addIfNotNull(validateSecretVaultKeys(secrets, adc.affiliation)) .addIfNotNull(validateSecretVaultFiles(secrets, adc.affiliation)) .addIfNotNull(validateDuplicateSecretEnvNames(secrets)) .addIfNotNull(validatePublicVaults(adc.affiliation)) } fun validatePublicVaults(vaultCollection: String): List<AuroraDeploymentSpecValidationException> { return vaultProvider.findPublicVaults(vaultCollection).map { AuroraDeploymentSpecValidationException("Vault=$it in VaultCollection=$vaultCollection is public. Please add atleast one group to limit access.") } } fun validateVaultExistence( secrets: List<AuroraSecret>, vaultCollectionName: String ): List<AuroraDeploymentSpecValidationException> { return secrets.map { it.secretVaultName } .mapNotNull { if (!vaultProvider.vaultExists(vaultCollectionName, it)) { AuroraDeploymentSpecValidationException("Referenced Vault $it in Vault Collection $vaultCollectionName does not exist") } else null } } fun validateSecretNames(secrets: List<AuroraSecret>): List<AuroraDeploymentSpecValidationException> { return secrets.mapNotNull { secret -> if (secret.name.length > 63) { AuroraDeploymentSpecValidationException("The name of the secretVault=${secret.name} is too long. Max 63 characters. Note that we ensure that the name starts with @name@-") } else null } } private fun validateKeyMappings(secrets: List<AuroraSecret>): List<AuroraDeploymentSpecValidationException> { return secrets.mapNotNull { validateKeyMapping(it) } } private fun validateKeyMapping(secret: AuroraSecret): AuroraDeploymentSpecValidationException? { val keyMappings = secret.keyMappings.takeIfNotEmpty() ?: return null val keys = secret.secretVaultKeys.takeIfNotEmpty() ?: return null val diff = keyMappings.keys - keys return if (diff.isNotEmpty()) { AuroraDeploymentSpecValidationException("The secretVault keyMappings $diff were not found in keys") } else null } /** * Validates that any secretVaultKeys specified actually exist in the vault. * Note that this method always uses the latest.properties file regardless of the version of the application and * the contents of the vault. * TODO: Note that this should really allow rewriting a key even if you do not specify it in the keys array. */ private fun validateSecretVaultKeys( secrets: List<AuroraSecret>, vaultCollection: String ): List<AuroraDeploymentSpecValidationException> { return secrets.mapNotNull { validateSecretVaultKey(it, vaultCollection) } } private fun validateSecretVaultKey( secret: AuroraSecret, vaultCollection: String ): AuroraDeploymentSpecValidationException? { val vaultName = secret.secretVaultName val keys = secret.secretVaultKeys.takeIfNotEmpty() ?: return null val vaultKeys = vaultProvider.findVaultKeys(vaultCollection, vaultName, secret.file) val missingKeys = keys - vaultKeys return if (missingKeys.isNotEmpty()) { throw AuroraDeploymentSpecValidationException("The keys $missingKeys were not found in the secret vault=$vaultName in collection=$vaultCollection") } else null } private fun validateSecretVaultFiles( secrets: List<AuroraSecret>, vaultCollection: String ): List<AuroraDeploymentSpecValidationException> { return secrets.mapNotNull { validateSecretVaultFile(it, vaultCollection) } } private fun validateSecretVaultFile( secret: AuroraSecret, vaultCollectionName: String ): AuroraDeploymentSpecValidationException? { return try { vaultProvider.findFileInVault( vaultCollectionName = vaultCollectionName, vaultName = secret.secretVaultName, fileName = secret.file ) null } catch (e: UnauthorizedAccessException) { AuroraDeploymentSpecValidationException(e.localizedMessage, e) } catch (e: Exception) { AuroraDeploymentSpecValidationException( "File with name=${secret.file} is not present in vault=${secret.secretVaultName} in collection=$vaultCollectionName", e ) } } /* * Validates that the name property of a secret it unique */ private fun validateDuplicateSecretEnvNames(secrets: List<AuroraSecret>): AuroraDeploymentSpecValidationException? { val secretNames = secrets.map { it.name } return if (secretNames.size != secretNames.toSet().size) { AuroraDeploymentSpecValidationException( "SecretVaults does not have unique names=[${ secretNames.joinToString( ", " ) }]" ) } else null } override fun generate(adc: AuroraDeploymentSpec, context: FeatureContext): Set<AuroraResource> { val secrets = context.secrets val secretEnvResult = handleSecretEnv(adc, secrets) return secretEnvResult.map { val secret = newSecret { metadata { name = it.name namespace = adc.namespace } data = it.secrets.mapValues { Base64.encodeBase64String(it.value) } } generateResource(secret) }.toSet() } private fun handleSecretEnv(adc: AuroraDeploymentSpec, secrets: List<AuroraSecret>): List<VaultSecretEnvResult> { return secrets.mapNotNull { secret: AuroraSecret -> val request = VaultRequest( collectionName = adc.affiliation, name = secret.secretVaultName ) vaultProvider.findVaultDataSingle(request)[secret.file]?.let { file -> // TODO: Do we need to do this in the properties file? We can just do it afterwards where we map? // TODO: Do the rewriting of the keys in the DC and keep the secret keys the same as in the vault? val properties = filterProperties(file, secret.secretVaultKeys, secret.keyMappings) properties.map { it.key.toString() to it.value.toString().toByteArray() } }?.let { VaultSecretEnvResult( adc.secretEnvName(secret.secretVaultName), it.toMap() ) } } } override fun modify( adc: AuroraDeploymentSpec, resources: Set<AuroraResource>, context: FeatureContext ) { val secrets = context.secrets val secretEnv: List<EnvVar> = handleSecretEnv(adc, secrets).flatMap { result -> result.secrets.map { secretValue -> newEnvVar { name = secretValue.key valueFrom { secretKeyRef { key = secretValue.key name = result.name optional = false } } } } } resources.addEnvVarsToMainContainers(secretEnv, this::class.java) } private fun getSecretVaults(adc: AuroraDeploymentSpec, cmd: AuroraContextCommand): List<AuroraSecret> { val secret = getSecretVault(adc)?.let { AuroraSecret( secretVaultName = it, keyMappings = adc.getKeyMappings(secretVaultKeyMappingHandlers(cmd))?.let { keyMappings -> keyMappings.mapKeys { keyMapping -> adc.replacer.replace(keyMapping.key) } }, secretVaultKeys = getSecretVaultKeys(adc).map { k -> adc.replacer.replace(k) }, file = "latest.properties", name = adc.name ) } val secretVaults = cmd.applicationFiles.findSubKeys("secretVaults").mapNotNull { val enabled: Boolean = adc["secretVaults/$it/enabled"] if (!enabled) { null } else { AuroraSecret( secretVaultKeys = adc.getOrNull<List<String>>("secretVaults/$it/keys") ?.map { k -> adc.replacer.replace(k) } ?: listOf(), keyMappings = adc.getOrNull<Map<String, String>>("secretVaults/$it/keyMappings") ?.let { keyMappings -> keyMappings.mapKeys { keyMapping -> adc.replacer.replace(keyMapping.key) } }, file = adc["secretVaults/$it/file"], name = adc.replacer.replace(it).ensureStartWith(adc.name, "-").normalizeKubernetesName(), secretVaultName = adc["secretVaults/$it/name"] ) } } return secretVaults.addIfNotNull(secret) } private fun getSecretVault(auroraDeploymentSpec: AuroraDeploymentSpec): String? = auroraDeploymentSpec.getOrNull("secretVault/name") ?: auroraDeploymentSpec.getOrNull("secretVault") private fun getSecretVaultKeys(auroraDeploymentSpec: AuroraDeploymentSpec): List<String> = auroraDeploymentSpec.getOrNull("secretVault/keys") ?: listOf() } data class AuroraSecret( val secretVaultName: String, val secretVaultKeys: List<String>, val keyMappings: Map<String, String>?, val file: String, val name: String )
apache-2.0
d8399bb0dbe33f3f86dc5ee07d8e3664
40.949405
187
0.646896
5.168684
false
false
false
false
mrlem/happy-cows
core/src/org/mrlem/happycows/ui/screens/AbstractScreen.kt
1
1087
package org.mrlem.happycows.ui.screens import com.badlogic.gdx.Screen import com.badlogic.gdx.scenes.scene2d.Stage import org.mrlem.happycows.HappyCowsGame import org.mrlem.happycows.ui.renderers.ShapeRenderer /** * @author Sébastien Guillemin <[email protected]> */ abstract class AbstractScreen( val game: HappyCowsGame ) : Screen { lateinit var stage: Stage var shapeRenderer = ShapeRenderer() private var state = State.DEFAULT override fun render(delta: Float) { shapeRenderer.clear() doUpdate(delta) doRender(delta) } override fun dispose() { stage.dispose() } override fun resize(width: Int, height: Int) {} override fun pause() {} override fun resume() {} override fun hide() {} protected open fun doUpdate(delta: Float) {} protected abstract fun doRender(delta: Float) fun `is`(state: State): Boolean { return state == this.state } fun set(state: State) { this.state = state } enum class State { DEFAULT, ENTERING, EXITING } }
gpl-3.0
f436a1de2e21ae40ec8a1958ddc4d0b3
20.294118
53
0.651934
4.052239
false
false
false
false
tsagi/JekyllForAndroid
app/src/main/java/gr/tsagi/jekyllforandroid/app/utils/ParsePostData.kt
2
3643
package gr.tsagi.jekyllforandroid.app.utils import android.util.Base64 import android.util.Log import com.jchanghong.data.DatabaseManager import com.jchanghong.model.Category import com.jchanghong.model.Note import com.jchanghong.utils.date_id_toTitle import com.jchanghong.utils.getyam import com.jchanghong.utils.path2Catogery import org.yaml.snakeyaml.Yaml import java.io.UnsupportedEncodingException /** \* Created with IntelliJ IDEA. \* User: jchanghong \* Date: 8/15/14 \* Time: 15:14 \*/ class ParsePostData { internal val JK_TITLE = "title" internal val JK_CATEGORY = "category" internal val JK_TAGS = "tags" fun getNoteFrombyte(id: String, path: String, contentBytes: String, type: Int, currentparent: String): Note { // Log.d("jiangchanghong",currentparent+"") // Get and insert the new posts information into the database val note = Note() note.parentPath=currentparent // Blobs return with Base64 encoding so we have to UTF-8 them. val bytes = Base64.decode(contentBytes, Base64.DEFAULT) val postContent: String = try { String(bytes, charset("UTF-8")) } catch (e: UnsupportedEncodingException) { e.printStackTrace() "" } note.content = postContent val yaml = Yaml() val map: Map<*, *>? map = yaml.load(postContent.getyam()) as? Map<*, *> var title:String var tags: String? = null val category: String? if (map == null) { note.tittle = id.date_id_toTitle() var date: Long = 0 if (type == 0) { val i = id.indexOf('-', 1 + id.indexOf('-', 1 + id.indexOf('-'))) date = java.lang.Long.parseLong(id.substring(0, i).replace("-", "")) } note.lastEdit = date note.category = getornew(null, path.path2Catogery()) return note } title = map[JK_TITLE].toString() note.tittle = title if (map.containsKey(JK_TAGS)) { tags = map[JK_TAGS].toString().replace("[", "").replace("]", "") } else { tags = null } if (map.containsKey(JK_CATEGORY)) { category = map[JK_CATEGORY].toString() } else { category = null } val categorymode = getornew(tags, category) note.category = categorymode var date: Long = 0 if (type == 0) { val i = id.indexOf('-', 1 + id.indexOf('-', 1 + id.indexOf('-'))) date = java.lang.Long.parseLong(id.substring(0, i).replace("-", "")) } note.lastEdit = date // First, check if the post exists in the db return note } private fun getornew(tags: String?, category: String?): Category { if (category != null) { var c = DatabaseManager.getCategoryByName(category) if (c != null) { return c } else { c = Category(name = category) DatabaseManager.insertCategory(c) return c } } if (tags != null) { val c1 = Category(name = tags.trim().split(" ")[0]) val c = DatabaseManager.getCategoryByName(c1.name) if (c != null) { return c } else { DatabaseManager.insertCategory(c1) return c1 } } Log.d("jiangchanghong", "no cat find ,use default") return DatabaseManager.defaultCAT } }
gpl-2.0
b189049a0f719e29d96f962c7ec65951
30.678261
113
0.545704
4.211561
false
false
false
false
zdary/intellij-community
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/ModuleBridgeImpl.kt
1
6079
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.ide.impl.legacyBridge.module import com.intellij.facet.FacetFromExternalSourcesStorage import com.intellij.facet.FacetManager import com.intellij.ide.plugins.IdeaPluginDescriptorImpl import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.application.Application import com.intellij.openapi.application.WriteAction import com.intellij.openapi.module.Module import com.intellij.openapi.module.impl.ModuleImpl import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootManager import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.ide.impl.VirtualFileUrlBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.facet.FacetManagerBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerComponentBridge.Companion.findModuleEntity import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleRootComponentBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.impl.VersionedEntityStorageOnStorage import com.intellij.workspaceModel.storage.url.VirtualFileUrl internal class ModuleBridgeImpl( override var moduleEntityId: ModuleId, name: String, project: Project, virtualFileUrl: VirtualFileUrl?, override var entityStorage: VersionedEntityStorage, override var diff: WorkspaceEntityStorageDiffBuilder? ) : ModuleImpl(name, project, virtualFileUrl as? VirtualFileUrlBridge), ModuleBridge { init { // default project doesn't have modules if (!project.isDefault) { val busConnection = project.messageBus.connect(this) WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(busConnection, object : WorkspaceModelChangeListener { override fun beforeChanged(event: VersionedStorageChange) { event.getChanges(ModuleEntity::class.java).filterIsInstance<EntityChange.Removed<ModuleEntity>>().forEach { if (it.entity.persistentId() == moduleEntityId) { val currentStore = entityStorage.current val storage = if (currentStore is WorkspaceEntityStorageBuilder) currentStore.toStorage() else currentStore entityStorage = VersionedEntityStorageOnStorage(storage) assert(entityStorage.current.resolve( moduleEntityId) != null) { "Cannot resolve module $moduleEntityId. Current store: $currentStore" } } } } }) } } fun rename(newName: String, newModuleFileUrl: VirtualFileUrl?, notifyStorage: Boolean) { myImlFilePointer = newModuleFileUrl as VirtualFileUrlBridge rename(newName, notifyStorage) } override fun rename(newName: String, notifyStorage: Boolean) { moduleEntityId = moduleEntityId.copy(name = newName) super<ModuleImpl>.rename(newName, notifyStorage) } override fun registerComponents(plugins: List<IdeaPluginDescriptorImpl>, app: Application?, listenerCallbacks: MutableList<Runnable>?) { super.registerComponents(plugins, app, null) val corePlugin = plugins.find { it.pluginId == PluginManagerCore.CORE_ID } ?: return registerComponent(ModuleRootManager::class.java, ModuleRootComponentBridge::class.java, corePlugin, true) registerComponent(FacetManager::class.java, FacetManagerBridge::class.java, corePlugin, true) unregisterComponent(DeprecatedModuleOptionManager::class.java) try { //todo improve val apiClass = Class.forName("com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager", true, javaClass.classLoader) val implClass = Class.forName("com.intellij.openapi.externalSystem.service.project.ExternalSystemModulePropertyManagerBridge", true, javaClass.classLoader) registerService(apiClass, implClass, corePlugin, true) } catch (ignored: Throwable) { } unregisterComponent(FacetFromExternalSourcesStorage::class.java.name) } override fun getOptionValue(key: String): String? { val moduleEntity = entityStorage.current.findModuleEntity(this) if (key == Module.ELEMENT_TYPE) { return moduleEntity?.type } return moduleEntity?.customImlData?.customModuleOptions?.get(key) } override fun setOption(key: String, value: String?) { fun updateOptionInEntity(diff: WorkspaceEntityStorageDiffBuilder, entity: ModuleEntity) { if (key == Module.ELEMENT_TYPE) { diff.modifyEntity(ModifiableModuleEntity::class.java, entity) { type = value } } else { val customImlData = entity.customImlData if (customImlData == null) { if (value != null) { diff.addModuleCustomImlDataEntity(null, mapOf(key to value), entity, entity.entitySource) } } else { diff.modifyEntity(ModifiableModuleCustomImlDataEntity::class.java, customImlData) { if (value != null) { customModuleOptions[key] = value } else { customModuleOptions.remove(key) } } } } } val diff = diff if (diff != null) { val entity = entityStorage.current.findModuleEntity(this) if (entity != null) { updateOptionInEntity(diff, entity) } } else { WriteAction.runAndWait<RuntimeException> { WorkspaceModel.getInstance(project).updateProjectModel { builder -> val entity = builder.findModuleEntity(this) if (entity != null) { updateOptionInEntity(builder, entity) } } } } return } override fun getOptionsModificationCount(): Long = 0 }
apache-2.0
9744963dda94a3e834f506a6d00feced
42.120567
140
0.73466
5.173617
false
false
false
false
leafclick/intellij-community
platform/dvcs-impl/src/com/intellij/dvcs/ui/RepositoryChangesGroupingPolicy.kt
1
2320
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.dvcs.ui import com.intellij.dvcs.repo.Repository import com.intellij.dvcs.repo.VcsRepositoryManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.NotNullLazyKey import com.intellij.openapi.vcs.changes.ui.BaseChangesGroupingPolicy import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNode import com.intellij.openapi.vcs.changes.ui.ChangesGroupingPolicyFactory import com.intellij.openapi.vcs.changes.ui.StaticFilePath import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder.* import javax.swing.tree.DefaultTreeModel class RepositoryChangesGroupingPolicy(val project: Project, val model: DefaultTreeModel) : BaseChangesGroupingPolicy() { private val repositoryManager = VcsRepositoryManager.getInstance(project) override fun getParentNodeFor(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*>? { val file = resolveVirtualFile(nodePath) val nextPolicyParent = nextPolicy?.getParentNodeFor(nodePath, subtreeRoot) file?.let { repositoryManager.getRepositoryForFileQuick(it) }?.let { repository -> if (repositoryManager.isExternal(repository)) return nextPolicyParent val grandParent = nextPolicyParent ?: subtreeRoot val cachingRoot = getCachingRoot(grandParent, subtreeRoot) REPOSITORY_CACHE.getValue(cachingRoot)[repository]?.let { return it } RepositoryChangesBrowserNode(repository).let { it.markAsHelperNode() model.insertNodeInto(it, grandParent, grandParent.childCount) REPOSITORY_CACHE.getValue(cachingRoot)[repository] = it IS_CACHING_ROOT.set(it, true) DIRECTORY_CACHE.getValue(it)[staticFrom(repository.root).key] = it return it } } return nextPolicyParent } internal class Factory : ChangesGroupingPolicyFactory() { override fun createGroupingPolicy(project: Project, model: DefaultTreeModel) = RepositoryChangesGroupingPolicy(project, model) } companion object { val REPOSITORY_CACHE = NotNullLazyKey.create<MutableMap<Repository, ChangesBrowserNode<*>>, ChangesBrowserNode<*>>("ChangesTree.RepositoryCache") { mutableMapOf() } } }
apache-2.0
6ef1ae39d42210683a4fcfb43e3370c9
43.634615
168
0.778879
4.686869
false
false
false
false
nobuoka/vc-oauth-java
core/src/main/kotlin/info/vividcode/oauth/ProtocolParameterSet.kt
1
608
package info.vividcode.oauth interface ProtocolParameterSet : List<ProtocolParameter<*>> { @Suppress("UNCHECKED_CAST") fun <E : ProtocolParameter<*>> get(name: ProtocolParameter.Name<E>): E? = find { it.name == name } as E class Builder { private val list = mutableListOf<ProtocolParameter<*>>() fun add(parameter: ProtocolParameter<*>) = apply { list.add(parameter) } fun add(set: Collection<ProtocolParameter<*>>) = apply { list.addAll(set) } fun build(): ProtocolParameterSet = object : ProtocolParameterSet, List<ProtocolParameter<*>> by list {} } }
apache-2.0
6b2c588f61f9b3b8fb06317c5f201b45
34.764706
112
0.671053
4.537313
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/specialBuiltins/bridgeNotEmptyMap.kt
2
1405
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS private object NotEmptyMap : MutableMap<Any, Int> { override fun containsKey(key: Any): Boolean = true override fun containsValue(value: Int): Boolean = true // non-special bridges get(Object)Integer -> get(Object)I override fun get(key: Any): Int = 1 override fun remove(key: Any): Int = 1 override val size: Int get() = 0 override fun isEmpty(): Boolean = true override fun put(key: Any, value: Int): Int? = throw UnsupportedOperationException() override fun putAll(from: Map<out Any, Int>): Unit = throw UnsupportedOperationException() override fun clear(): Unit = throw UnsupportedOperationException() override val entries: MutableSet<MutableMap.MutableEntry<Any, Int>> get() = null!! override val keys: MutableSet<Any> get() = null!! override val values: MutableCollection<Int> get() = null!! } fun box(): String { val n = NotEmptyMap as MutableMap<Any?, Any?> if (n.get(null) != null) return "fail 1" if (n.containsKey(null)) return "fail 2" if (n.containsValue(null)) return "fail 3" if (n.remove(null) != null) return "fail 4" if (n.get(1) == null) return "fail 5" if (!n.containsKey("")) return "fail 6" if (!n.containsValue(3)) return "fail 7" if (n.remove("") == null) return "fail 8" return "OK" }
apache-2.0
7b6267124cf7a558135e26caf17486ac
36.972973
94
0.66548
3.849315
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/utils.kt
5
1461
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.gradleTooling import java.util.* fun Class<*>.getMethodOrNull(name: String, vararg parameterTypes: Class<*>) = try { getMethod(name, *parameterTypes) } catch (e: Exception) { null } fun Class<*>.getDeclaredMethodOrNull(name: String, vararg parameterTypes: Class<*>) = try { getDeclaredMethod(name, *parameterTypes)?.also { it.isAccessible = true } } catch (e: Exception) { null } fun ClassLoader.loadClassOrNull(name: String): Class<*>? { return try { loadClass(name) } catch (e: LinkageError) { return null } catch (e: ClassNotFoundException) { return null } } fun compilationFullName(simpleName: String, classifier: String?) = if (classifier != null) classifier + simpleName.capitalize() else simpleName fun String.capitalize(): String { /* Default implementation as suggested by 'capitalize' deprecation */ if (KotlinVersion.CURRENT.isAtLeast(1, 5)) { return this.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } } /* Fallback implementation for older Kotlin versions */ if (this.isEmpty()) return this @Suppress("DEPRECATION") return this[0].toUpperCase() + this.drop(1) }
apache-2.0
d2a4de5de9dc3ccb84cb84e4edaa56d8
32.204545
158
0.676934
4.348214
false
false
false
false
smmribeiro/intellij-community
python/src/com/jetbrains/python/console/PydevConsoleExecuteActionHandler.kt
1
8902
// 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.jetbrains.python.console import com.intellij.application.options.RegistryManager import com.intellij.codeInsight.hint.HintManager import com.intellij.execution.console.LanguageConsoleImpl import com.intellij.execution.console.LanguageConsoleView import com.intellij.execution.process.ProcessHandler import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.components.service import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.psi.util.PsiTreeUtil import com.jetbrains.python.console.actions.CommandQueueForPythonConsoleService import com.jetbrains.python.console.pydev.ConsoleCommunication import com.jetbrains.python.console.pydev.ConsoleCommunicationListener import com.jetbrains.python.psi.PyElementGenerator import com.jetbrains.python.psi.PyFile import com.jetbrains.python.psi.PyStatementList import com.jetbrains.python.psi.impl.PythonLanguageLevelPusher import java.awt.Font open class PydevConsoleExecuteActionHandler(private val myConsoleView: LanguageConsoleView, processHandler: ProcessHandler, final override val consoleCommunication: ConsoleCommunication) : PythonConsoleExecuteActionHandler(processHandler, false), ConsoleCommunicationListener { private val project = myConsoleView.project private val myEnterHandler = PyConsoleEnterHandler() private var myIpythonInputPromptCount = 2 fun decreaseInputPromptCount(value : Int) { myIpythonInputPromptCount -= value } override var isEnabled: Boolean = false set(value) { field = value updateConsoleState() } init { this.consoleCommunication.addCommunicationListener(this) } override fun processLine(line: String) { executeMultiLine(line) } private fun executeMultiLine(text: String) { val commandText = if (!text.endsWith("\n")) { text + "\n" } else { text } sendLineToConsole(ConsoleCommunication.ConsoleCodeFragment(commandText, checkSingleLine(text))) } override fun checkSingleLine(text: String): Boolean { val languageLevel = PythonLanguageLevelPusher.getLanguageLevelForVirtualFile(project, myConsoleView.virtualFile) val pyFile = PyElementGenerator.getInstance(project).createDummyFile(languageLevel, text) as PyFile return PsiTreeUtil.findChildOfAnyType(pyFile, PyStatementList::class.java) == null && pyFile.statements.size < 2 } private fun sendLineToConsole(code: ConsoleCommunication.ConsoleCodeFragment) { val consoleComm = consoleCommunication if (!consoleComm.isWaitingForInput) { executingPrompt() } if (ipythonEnabled && !consoleComm.isWaitingForInput && !code.getText().isBlank()) { ++myIpythonInputPromptCount } if (RegistryManager.getInstance().`is`("python.console.CommandQueue")) { // add new command to CommandQueue service service<CommandQueueForPythonConsoleService>().addNewCommand(this, code) } else { consoleComm.execInterpreter(code) {} } } override fun updateConsoleState() { if (!isEnabled) { executingPrompt() } else if (consoleCommunication.isWaitingForInput) { waitingForInputPrompt() } else if (canExecuteNow()) { if (consoleCommunication.needsMore()) { more() } else { inPrompt() } } else { if (RegistryManager.getInstance().`is`("python.console.CommandQueue")) { inPrompt() } else { executingPrompt() } } } private fun inPrompt() { if (ipythonEnabled) { ipythonInPrompt() } else { ordinaryPrompt() } } private fun ordinaryPrompt() { if (PyConsoleUtil.ORDINARY_PROMPT != myConsoleView.prompt) { myConsoleView.prompt = PyConsoleUtil.ORDINARY_PROMPT myConsoleView.indentPrompt = PyConsoleUtil.INDENT_PROMPT PyConsoleUtil.scrollDown(myConsoleView.currentEditor) } } private val ipythonEnabled: Boolean get() = PyConsoleUtil.getOrCreateIPythonData(myConsoleView.virtualFile).isIPythonEnabled private fun ipythonInPrompt() { myConsoleView.setPromptAttributes(object : ConsoleViewContentType("", TextAttributes()) { override fun getAttributes(): TextAttributes { val attrs = EditorColorsManager.getInstance().globalScheme.getAttributes(USER_INPUT_KEY); attrs.fontType = Font.PLAIN return attrs } }) val prompt = "In [$myIpythonInputPromptCount]:" val indentPrompt = PyConsoleUtil.IPYTHON_INDENT_PROMPT.padStart(prompt.length) myConsoleView.prompt = prompt myConsoleView.indentPrompt = indentPrompt PyConsoleUtil.scrollDown(myConsoleView.currentEditor) } private fun executingPrompt() { myConsoleView.prompt = PyConsoleUtil.EXECUTING_PROMPT myConsoleView.indentPrompt = PyConsoleUtil.EXECUTING_PROMPT } private fun waitingForInputPrompt() { if (PyConsoleUtil.INPUT_PROMPT != myConsoleView.prompt && PyConsoleUtil.HELP_PROMPT != myConsoleView.prompt) { myConsoleView.prompt = PyConsoleUtil.INPUT_PROMPT myConsoleView.indentPrompt = PyConsoleUtil.INPUT_PROMPT PyConsoleUtil.scrollDown(myConsoleView.currentEditor) } } private fun more() { val prompt = if (ipythonEnabled) { PyConsoleUtil.IPYTHON_INDENT_PROMPT } else { PyConsoleUtil.INDENT_PROMPT } if (prompt != myConsoleView.prompt) { myConsoleView.prompt = prompt myConsoleView.indentPrompt = prompt PyConsoleUtil.scrollDown(myConsoleView.currentEditor) } } override fun commandExecuted(more: Boolean): Unit = updateConsoleState() override fun inputRequested() { isEnabled = true } override val cantExecuteMessage: String get() { if (!isEnabled) { return consoleIsNotEnabledMessage } else if (!canExecuteNow()) { return prevCommandRunningMessage } else { return "Can't execute the command" } } override fun runExecuteAction(console: LanguageConsoleView) { if (isEnabled) { if (RegistryManager.getInstance().`is`("python.console.CommandQueue")) { doRunExecuteAction(console) } else { if (!canExecuteNow()) { HintManager.getInstance().showErrorHint(console.consoleEditor, prevCommandRunningMessage) } else { doRunExecuteAction(console) } } } else { HintManager.getInstance().showErrorHint(console.consoleEditor, consoleIsNotEnabledMessage) } } private fun doRunExecuteAction(console: LanguageConsoleView) { val doc = myConsoleView.editorDocument val endMarker = doc.createRangeMarker(doc.textLength, doc.textLength) endMarker.isGreedyToLeft = false endMarker.isGreedyToRight = true val isComplete = myEnterHandler.handleEnterPressed(console.consoleEditor) if (isComplete || consoleCommunication.isWaitingForInput) { deleteString(doc, endMarker) if (shouldCopyToHistory(console)) { copyToHistoryAndExecute(console) } else { processLine(myConsoleView.consoleEditor.document.text) } } } private fun copyToHistoryAndExecute(console: LanguageConsoleView) = super.runExecuteAction(console) override fun canExecuteNow(): Boolean = !consoleCommunication.isExecuting || consoleCommunication.isWaitingForInput protected open val consoleIsNotEnabledMessage: String get() = notEnabledMessage companion object { val prevCommandRunningMessage: String get() = "Previous command is still running. Please wait or press Ctrl+C in console to interrupt." val notEnabledMessage: String get() = "Console is not enabled." private fun shouldCopyToHistory(console: LanguageConsoleView): Boolean { return !PyConsoleUtil.isPagingPrompt(console.prompt) } fun deleteString(document: Document, endMarker : RangeMarker) { if (endMarker.endOffset - endMarker.startOffset > 0) { ApplicationManager.getApplication().runWriteAction { CommandProcessor.getInstance().runUndoTransparentAction { document.deleteString(endMarker.startOffset, endMarker.endOffset) } } } } } } private var LanguageConsoleView.indentPrompt: String get() { return (this as? LanguageConsoleImpl)?.consolePromptDecorator?.indentPrompt ?: "" } set(value) { (this as? LanguageConsoleImpl)?.consolePromptDecorator?.indentPrompt = value }
apache-2.0
0af3179ca0390630d6e5134ae67a96aa
32.466165
197
0.726129
4.945556
false
false
false
false
kpi-ua/ecampus-client-android
app/src/main/java/com/goldenpiedevs/schedule/app/ui/lesson/LessonActivity.kt
1
3828
package com.goldenpiedevs.schedule.app.ui.lesson import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import androidx.core.content.ContextCompat import com.goldenpiedevs.schedule.app.R import com.goldenpiedevs.schedule.app.ui.base.BaseActivity import com.r0adkll.slidr.Slidr import kotlinx.android.synthetic.main.lesson_activity_layout.* import org.osmdroid.config.Configuration import org.osmdroid.util.GeoPoint import org.osmdroid.views.overlay.Marker class LessonActivity : BaseActivity<LessonPresenter, LessonView>(), LessonView { override fun getPresenterChild(): LessonPresenter = presenter private lateinit var presenter: LessonPresenter override fun getActivityLayout(): Int = R.layout.lesson_activity_layout override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Configuration.getInstance().userAgentValue = packageName Slidr.attach(this) presenter = LessonImplementation() with(presenter) { attachView(this@LessonActivity) setFragmentManager(supportFragmentManager) showLessonData(intent.extras!!) } teacher.setOnClickListener { presenter.onTeacherClick() } } override fun showLessonName(string: String) { widget_lesson_title.text = string } override fun showLessonTeachers(string: String) { teacher.apply { visibility = View.VISIBLE subText = string } } override fun showLessonRoom(string: String) { widget_lesson_location.apply { visibility = View.VISIBLE subText = string } } override fun showLessonType(string: String) { type.apply { visibility = View.VISIBLE subText = string } } private var startMarker: Marker? = null override fun showLessonLocation(geoPoint: GeoPoint) { startMarker = Marker(map).apply { position = geoPoint setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM) icon = ContextCompat.getDrawable(this@LessonActivity, R.drawable.ic_room_location) //Ignore marker click setOnMarkerClickListener { _, _ -> true } } map.apply { visibility = View.VISIBLE setBuiltInZoomControls(false) overlays.add(startMarker) controller.apply { setZoom(17.0) setCenter(geoPoint) } } } override fun showLessonTime(string: String) { widget_lesson_time.apply { visibility = View.VISIBLE text = string } } override fun onPrepareOptionsMenu(menu: Menu?): Boolean { menu?.findItem(R.id.edit_note)?.isVisible = !presenter.isInEditMode() return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { return when (item!!.itemId) { android.R.id.home -> { onBackPressed() true } R.id.edit_note -> { presenter.onEditNoteClick() true } else -> super.onOptionsItemSelected(item) } } fun saveNote() { presenter.onNoteSaved() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.lessons_menu, menu) return true } override fun onBackPressed() { presenter.onBackPressed() super.onBackPressed() } override fun onDestroy() { map.overlays.remove(startMarker) startMarker = null super.onDestroy() } fun deleteNote() { presenter.onNoteDeleted() } }
apache-2.0
8298146a563248b0adf2bf33d3a0afc5
26.35
94
0.625392
4.821159
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ExclExclCallFixes.kt
1
10210
// 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.quickfix import com.intellij.codeInsight.FileModificationService import com.intellij.codeInsight.daemon.impl.actions.IntentionActionWithFixAllOption import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassifierDescriptor import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.diagnostics.Errors.UNSAFE_CALL import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression import org.jetbrains.kotlin.idea.resolve.getDataFlowValueFactory import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.resolvedCallUtil.getImplicitReceiverValue import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.util.isValidOperator import org.jetbrains.kotlin.utils.addToStdlib.safeAs abstract class ExclExclCallFix(psiElement: PsiElement) : KotlinQuickFixAction<PsiElement>(psiElement) { override fun getFamilyName(): String = text override fun startInWriteAction(): Boolean = true } class RemoveExclExclCallFix(psiElement: PsiElement) : ExclExclCallFix(psiElement), CleanupFix, HighPriorityAction, IntentionActionWithFixAllOption { override fun getText(): String = KotlinBundle.message("fix.remove.non.null.assertion") override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = getExclExclPostfixExpression() != null override fun invoke(project: Project, editor: Editor?, file: KtFile) { val postfixExpression = getExclExclPostfixExpression() ?: return val expression = KtPsiFactory(project).createExpression(postfixExpression.baseExpression!!.text) postfixExpression.replace(expression) } private fun getExclExclPostfixExpression(): KtPostfixExpression? { val operationParent = element?.parent if (operationParent is KtPostfixExpression && operationParent.baseExpression != null) { return operationParent } return null } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction = RemoveExclExclCallFix(diagnostic.psiElement) } } class AddExclExclCallFix(psiElement: PsiElement, val checkImplicitReceivers: Boolean) : ExclExclCallFix(psiElement), LowPriorityAction { constructor(psiElement: PsiElement) : this(psiElement, true) override fun getText() = KotlinBundle.message("fix.introduce.non.null.assertion") override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = getExpressionForIntroduceCall() != null override fun invoke(project: Project, editor: Editor?, file: KtFile) { if (!FileModificationService.getInstance().prepareFileForWrite(file)) return val expr = getExpressionForIntroduceCall() ?: return val modifiedExpression = expr.expression val psiFactory = KtPsiFactory(project) val exclExclExpression = if (expr.implicitReceiver) { if (modifiedExpression is KtCallableReferenceExpression) { psiFactory.createExpressionByPattern("this!!::$0", modifiedExpression.callableReference) } else { psiFactory.createExpressionByPattern("this!!.$0", modifiedExpression) } } else { psiFactory.createExpressionByPattern("$0!!", modifiedExpression) } modifiedExpression.replace(exclExclExpression) } private class ExpressionForCall(val expression: KtExpression, val implicitReceiver: Boolean) private fun KtExpression?.expressionForCall(implicitReceiver: Boolean = false) = this?.let { ExpressionForCall(it, implicitReceiver) } private fun getExpressionForIntroduceCall(): ExpressionForCall? { val psiElement = element ?: return null if ((psiElement as? KtExpression).isNullExpression()) { return null } if (psiElement is LeafPsiElement && psiElement.elementType == KtTokens.DOT) { return (psiElement.prevSibling as? KtExpression).expressionForCall() } return when (psiElement) { is KtArrayAccessExpression -> psiElement.expressionForCall() is KtOperationReferenceExpression -> { when (val parent = psiElement.parent) { is KtUnaryExpression -> parent.baseExpression.expressionForCall() is KtBinaryExpression -> { val receiver = if (KtPsiUtil.isInOrNotInOperation(parent)) parent.right else parent.left receiver.expressionForCall() } else -> null } } is KtExpression -> { val parent = psiElement.parent val context = psiElement.analyze() if (checkImplicitReceivers && psiElement.getResolvedCall(context)?.getImplicitReceiverValue() is ExtensionReceiver) { val expressionToReplace = parent as? KtCallExpression ?: parent as? KtCallableReferenceExpression ?: psiElement expressionToReplace.expressionForCall(implicitReceiver = true) } else { val targetElement = parent.safeAs<KtCallableReferenceExpression>()?.receiverExpression ?: psiElement context[BindingContext.EXPRESSION_TYPE_INFO, targetElement]?.let { val type = it.type val dataFlowValueFactory = targetElement.getResolutionFacade().getDataFlowValueFactory() if (type != null) { val nullability = it.dataFlowInfo.getStableNullability( dataFlowValueFactory.createDataFlowValue(targetElement, type, context, targetElement.findModuleDescriptor()) ) if (!nullability.canBeNonNull()) return null } } targetElement.expressionForCall() } } else -> null } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction { val psiElement = diagnostic.psiElement if (diagnostic.factory == UNSAFE_CALL && psiElement is KtArrayAccessExpression) { psiElement.arrayExpression?.let { return AddExclExclCallFix(it) } } return AddExclExclCallFix(psiElement) } } } object SmartCastImpossibleExclExclFixFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { if (diagnostic.factory !== Errors.SMARTCAST_IMPOSSIBLE) return null val element = diagnostic.psiElement as? KtExpression ?: return null val analyze = element.analyze(BodyResolveMode.PARTIAL) val type = analyze.getType(element) if (type == null || !TypeUtils.isNullableType(type)) return null val diagnosticWithParameters = Errors.SMARTCAST_IMPOSSIBLE.cast(diagnostic) val expectedType = diagnosticWithParameters.a if (TypeUtils.isNullableType(expectedType)) return null val nullableExpectedType = TypeUtils.makeNullable(expectedType) if (!type.isSubtypeOf(nullableExpectedType)) return null return AddExclExclCallFix(element, checkImplicitReceivers = false) } } object MissingIteratorExclExclFixFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val element = diagnostic.psiElement as? KtExpression ?: return null val analyze = element.analyze(BodyResolveMode.PARTIAL) val type = analyze.getType(element) if (type == null || !TypeUtils.isNullableType(type)) return null val descriptor = type.constructor.declarationDescriptor fun hasIteratorFunction(classifierDescriptor: ClassifierDescriptor?): Boolean { if (classifierDescriptor !is ClassDescriptor) return false val memberScope = classifierDescriptor.unsubstitutedMemberScope val functions = memberScope.getContributedFunctions(OperatorNameConventions.ITERATOR, NoLookupLocation.FROM_IDE) return functions.any { it.isValidOperator() } } when (descriptor) { is TypeParameterDescriptor -> { if (descriptor.upperBounds.none { hasIteratorFunction(it.constructor.declarationDescriptor) }) return null } is ClassifierDescriptor -> { if (!hasIteratorFunction(descriptor)) return null } else -> return null } return AddExclExclCallFix(element) } }
apache-2.0
dc55a577ab66eb8832a2c14f81cde601
47.393365
158
0.705681
5.768362
false
false
false
false
smmribeiro/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/EditorTabPreview.kt
1
7840
// 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.vcs.changes import com.intellij.diff.chains.DiffRequestChain import com.intellij.diff.chains.SimpleDiffRequestChain import com.intellij.diff.editor.DiffEditorEscapeAction import com.intellij.diff.editor.DiffEditorTabFilesManager import com.intellij.diff.editor.DiffVirtualFile import com.intellij.diff.impl.DiffRequestProcessor import com.intellij.diff.util.DiffUserDataKeysEx import com.intellij.openapi.Disposable import com.intellij.openapi.ListSelection import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Disposer.isDisposed import com.intellij.openapi.vcs.changes.ui.ChangesTree import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.ToolWindowManager import com.intellij.util.EditSourceOnDoubleClickHandler.isToggleEvent import com.intellij.util.IJSwingUtilities import com.intellij.util.Processor import com.intellij.util.ui.update.DisposableUpdate import com.intellij.util.ui.update.MergingUpdateQueue import org.jetbrains.annotations.Nls import java.awt.event.KeyEvent import java.awt.event.MouseEvent import javax.swing.JComponent import kotlin.streams.toList abstract class EditorTabPreview(protected val diffProcessor: DiffRequestProcessor) : DiffPreview { protected val project get() = diffProcessor.project!! protected val previewFile: PreviewDiffVirtualFile = EditorTabDiffPreviewVirtualFile(this) private val updatePreviewQueue = MergingUpdateQueue("updatePreviewQueue", 100, true, null, diffProcessor).apply { setRestartTimerOnAdd(true) } private val updatePreviewProcessor: DiffPreviewUpdateProcessor? get() = diffProcessor as? DiffPreviewUpdateProcessor var escapeHandler: Runnable? = null fun installListeners(tree: ChangesTree, isOpenEditorDiffPreviewWithSingleClick: Boolean) { installDoubleClickHandler(tree) installEnterKeyHandler(tree) if (isOpenEditorDiffPreviewWithSingleClick) { //do not open file aggressively on start up, do it later DumbService.getInstance(project).smartInvokeLater { if (isDisposed(updatePreviewQueue)) return@smartInvokeLater installSelectionHandler(tree, true) } } else { installSelectionHandler(tree, false) } } private fun installSelectionHandler(tree: ChangesTree, isOpenEditorDiffPreviewWithSingleClick: Boolean) { installSelectionChangedHandler(tree) { if (isOpenEditorDiffPreviewWithSingleClick) { if (!openPreview(false)) closePreview() // auto-close editor tab if nothing to preview } else { updatePreview(false) } } } fun installNextDiffActionOn(component: JComponent) { DumbAwareAction.create { openPreview(true) }.apply { copyShortcutFrom(ActionManager.getInstance().getAction(IdeActions.ACTION_NEXT_DIFF)) registerCustomShortcutSet(component, diffProcessor) } } protected open fun isPreviewOnDoubleClickAllowed(): Boolean = true protected open fun isPreviewOnEnterAllowed(): Boolean = true private fun installDoubleClickHandler(tree: ChangesTree) { val oldDoubleClickHandler = tree.doubleClickHandler val newDoubleClickHandler = Processor<MouseEvent> { e -> if (isToggleEvent(tree, e)) return@Processor false isPreviewOnDoubleClickAllowed() && openPreview(true) || oldDoubleClickHandler?.process(e) == true } tree.doubleClickHandler = newDoubleClickHandler Disposer.register(diffProcessor, Disposable { tree.doubleClickHandler = oldDoubleClickHandler }) } private fun installEnterKeyHandler(tree: ChangesTree) { val oldEnterKeyHandler = tree.enterKeyHandler val newEnterKeyHandler = Processor<KeyEvent> { e -> isPreviewOnEnterAllowed() && openPreview(false) || oldEnterKeyHandler?.process(e) == true } tree.enterKeyHandler = newEnterKeyHandler Disposer.register(diffProcessor, Disposable { tree.enterKeyHandler = oldEnterKeyHandler }) } private fun installSelectionChangedHandler(tree: ChangesTree, handler: () -> Unit) = tree.addSelectionListener( Runnable { updatePreviewQueue.queue(DisposableUpdate.createDisposable(updatePreviewQueue, this) { if (!skipPreviewUpdate()) handler() }) }, updatePreviewQueue ) protected abstract fun getCurrentName(): String? protected abstract fun hasContent(): Boolean protected open fun skipPreviewUpdate(): Boolean = ToolWindowManager.getInstance(project).isEditorComponentActive override fun updatePreview(fromModelRefresh: Boolean) { if (isPreviewOpen()) { updatePreviewProcessor?.refresh(false) } else { updatePreviewProcessor?.clear() } } override fun setPreviewVisible(isPreviewVisible: Boolean, focus: Boolean) { if (isPreviewVisible) openPreview(focus) else closePreview() } protected fun isPreviewOpen(): Boolean = FileEditorManager.getInstance(project).isFileOpen(previewFile) fun closePreview() { FileEditorManager.getInstance(project).closeFile(previewFile) updatePreviewProcessor?.clear() } open fun openPreview(focusEditor: Boolean): Boolean { updatePreviewProcessor?.refresh(false) if (!hasContent()) return false escapeHandler?.let { handler -> registerEscapeHandler(previewFile, handler) } openPreview(project, previewFile, focusEditor) return true } private class EditorTabDiffPreviewVirtualFile(val preview: EditorTabPreview) : PreviewDiffVirtualFile(EditorTabDiffPreviewProvider(preview.diffProcessor) { preview.getCurrentName() }) { init { // EditorTabDiffPreviewProvider does not create new processor, so general assumptions of DiffVirtualFile are violated preview.diffProcessor.putContextUserData(DiffUserDataKeysEx.DIFF_IN_EDITOR_WITH_EXPLICIT_DISPOSABLE, true) } } companion object { fun openPreview(project: Project, file: PreviewDiffVirtualFile, focusEditor: Boolean): Array<out FileEditor> { return DiffEditorTabFilesManager.getInstance(project).showDiffFile(file, focusEditor) } fun registerEscapeHandler(file: VirtualFile, handler: Runnable) { file.putUserData(DiffVirtualFile.ESCAPE_HANDLER, EditorTabPreviewEscapeAction(handler)) } } } internal class EditorTabPreviewEscapeAction(private val escapeHandler: Runnable) : DumbAwareAction(), DiffEditorEscapeAction { override fun actionPerformed(e: AnActionEvent) = escapeHandler.run() } private class EditorTabDiffPreviewProvider( private val diffProcessor: DiffRequestProcessor, private val tabNameProvider: () -> String? ) : ChainBackedDiffPreviewProvider { override fun createDiffRequestProcessor(): DiffRequestProcessor { IJSwingUtilities.updateComponentTreeUI(diffProcessor.component) return diffProcessor } override fun getOwner(): Any = this override fun getEditorTabName(processor: DiffRequestProcessor?): @Nls String = tabNameProvider().orEmpty() override fun createDiffRequestChain(): DiffRequestChain? { if (diffProcessor is ChangeViewDiffRequestProcessor) { val producers = ListSelection.create(diffProcessor.allChanges.toList(), diffProcessor.currentChange).map { it.createProducer(diffProcessor.project) } return SimpleDiffRequestChain.fromProducers(producers.list, producers.selectedIndex) } return null } }
apache-2.0
90017c5a1ac9e9941f718fdb43408ce0
38.59596
126
0.780102
4.845488
false
false
false
false
smmribeiro/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/indices/VirtualFileIndex.kt
2
22294
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl.indices import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtilRt import com.intellij.openapi.util.text.Strings import com.intellij.util.containers.CollectionFactory.createSmallMemoryFootprintMap import com.intellij.util.containers.CollectionFactory.createSmallMemoryFootprintSet import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.bridgeEntities.LibraryRoot import com.intellij.workspaceModel.storage.impl.* import com.intellij.workspaceModel.storage.impl.containers.BidirectionalLongMultiMap import com.intellij.workspaceModel.storage.impl.containers.putAll import com.intellij.workspaceModel.storage.url.MutableVirtualFileUrlIndex import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlIndex import it.unimi.dsi.fastutil.Hash import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet import org.jetbrains.annotations.TestOnly import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty import kotlin.reflect.KProperty1 import kotlin.reflect.full.memberProperties /** * EntityId2Vfu may contains these possible variants, due to memory optimization: * 1) Object2ObjectOpenHashMap<EntityId, Pair<String, VirtualFileUrl>> * 2) Object2ObjectOpenHashMap<EntityId, Pair<String, ObjectOpenHashSet<VirtualFileUrl>>> * 3) Object2ObjectOpenHashMap<EntityId, Object2ObjectOpenHashMap<String, VirtualFileUrl>> * 4) Object2ObjectOpenHashMap<EntityId, Object2ObjectOpenHashMap<String, ObjectOpenHashSet<VirtualFileUrl>>> */ //internal typealias EntityId2Vfu = Object2ObjectOpenHashMap<EntityId, Any> //internal typealias Vfu2EntityId = Object2ObjectOpenHashMap<VirtualFileUrl, Object2ObjectOpenHashMap<String, EntityId>> //internal typealias EntityId2JarDir = BidirectionalMultiMap<EntityId, VirtualFileUrl> internal typealias EntityId2Vfu = Long2ObjectOpenHashMap<Any> internal typealias Vfu2EntityId = Object2ObjectOpenCustomHashMap<VirtualFileUrl, Object2LongOpenHashMap<String>> internal typealias EntityId2JarDir = BidirectionalLongMultiMap<VirtualFileUrl> @Suppress("UNCHECKED_CAST") open class VirtualFileIndex internal constructor( internal open val entityId2VirtualFileUrl: EntityId2Vfu, internal open val vfu2EntityId: Vfu2EntityId, internal open val entityId2JarDir: EntityId2JarDir, ) : VirtualFileUrlIndex { private lateinit var entityStorage: AbstractEntityStorage constructor() : this(EntityId2Vfu(), Vfu2EntityId(getHashingStrategy()), EntityId2JarDir()) internal fun getVirtualFiles(id: EntityId): Set<VirtualFileUrl> { val result = mutableSetOf<VirtualFileUrl>() entityId2VirtualFileUrl[id]?.also { value -> when (value) { is Object2ObjectOpenHashMap<*, *> -> value.values.forEach { vfu -> result.addAll(getVirtualFileUrl(vfu)) } is Pair<*, *> -> result.addAll(getVirtualFileUrl(value.second!!)) } } return result } internal fun getVirtualFileUrlInfoByEntityId(id: EntityId): Map<String, MutableSet<VirtualFileUrl>> { val property2VfuMap = entityId2VirtualFileUrl[id] ?: return emptyMap() val copiedVfuMap = HashMap<String, MutableSet<VirtualFileUrl>>() addVirtualFileUrlsToMap(copiedVfuMap, property2VfuMap) return copiedVfuMap } private fun addVirtualFileUrlsToMap(result: HashMap<String, MutableSet<VirtualFileUrl>>, value: Any) { when (value) { is Object2ObjectOpenHashMap<*, *> -> value.forEach { result[it.key as String] = getVirtualFileUrl(it.value) } is Pair<*, *> -> result[value.first as String] = getVirtualFileUrl(value.second!!) } } private fun getVirtualFileUrl(value: Any): MutableSet<VirtualFileUrl> { return when (value) { is ObjectOpenHashSet<*> -> HashSet(value as ObjectOpenHashSet<VirtualFileUrl>) else -> mutableSetOf(value as VirtualFileUrl) } } override fun findEntitiesByUrl(fileUrl: VirtualFileUrl): Sequence<Pair<WorkspaceEntity, String>> = vfu2EntityId[fileUrl]?.asSequence()?.mapNotNull { val entityData = entityStorage.entityDataById(it.value) ?: return@mapNotNull null entityData.createEntity(entityStorage) to it.key.substring(it.value.asString().length + 1) } ?: emptySequence() fun getIndexedJarDirectories(): Set<VirtualFileUrl> = entityId2JarDir.values internal fun setTypedEntityStorage(storage: AbstractEntityStorage) { entityStorage = storage } internal fun assertConsistency() { val existingVfuInFirstMap = HashSet<VirtualFileUrl>() this.entityId2VirtualFileUrl.forEach { (entityId, property2Vfu) -> fun assertProperty2Vfu(property: String, vfus: Any) { val vfuSet = if (vfus is Set<*>) (vfus as ObjectOpenHashSet<VirtualFileUrl>) else mutableSetOf(vfus as VirtualFileUrl) vfuSet.forEach { vfu -> existingVfuInFirstMap.add(vfu) val property2EntityId = this.vfu2EntityId[vfu] assert(property2EntityId != null) { "VirtualFileUrl: $vfu exists in the first collection by EntityId: ${entityId.asString()} with Property: $property but absent at other" } val compositeKey = getCompositeKey(entityId, property) val existingEntityId = property2EntityId!!.contains(compositeKey) assert(existingEntityId) { "VirtualFileUrl: $vfu exist in both maps but EntityId: ${entityId.asString()} with Property: $property absent at other" } } } when (property2Vfu) { is Object2ObjectOpenHashMap<*, *> -> property2Vfu.forEach { (property, vfus) -> assertProperty2Vfu(property as String, vfus) } is Pair<*, *> -> assertProperty2Vfu(property2Vfu.first as String, property2Vfu.second!!) } } val existingVfuISecondMap = this.vfu2EntityId.keys assert( existingVfuInFirstMap.size == existingVfuISecondMap.size) { "Different count of VirtualFileUrls EntityId2VirtualFileUrl: ${existingVfuInFirstMap.size} Vfu2EntityId: ${existingVfuISecondMap.size}" } existingVfuInFirstMap.removeAll(existingVfuISecondMap) assert(existingVfuInFirstMap.isEmpty()) { "Both maps contain the same amount of VirtualFileUrls but they are different" } } internal fun getCompositeKey(entityId: EntityId, propertyName: String) = "${entityId.asString()}_$propertyName" class MutableVirtualFileIndex private constructor( // Do not write to [entityId2VirtualFileUrl] and [vfu2EntityId] directly! Create a dedicated method for that // and call [startWrite] before write. override var entityId2VirtualFileUrl: EntityId2Vfu, override var vfu2EntityId: Vfu2EntityId, override var entityId2JarDir: EntityId2JarDir, ) : VirtualFileIndex(entityId2VirtualFileUrl, vfu2EntityId, entityId2JarDir), MutableVirtualFileUrlIndex { private var freezed = true @Synchronized override fun index(entity: WorkspaceEntity, propertyName: String, virtualFileUrl: VirtualFileUrl?) { index((entity as WorkspaceEntityBase).id, propertyName, virtualFileUrl) } @Synchronized internal fun index(id: EntityId, propertyName: String, virtualFileUrls: Set<VirtualFileUrl>) { startWrite() val newVirtualFileUrls = HashSet(virtualFileUrls) fun cleanExistingVfu(existingVfu: Any): Boolean { when (existingVfu) { is Set<*> -> { existingVfu as ObjectOpenHashSet<VirtualFileUrl> existingVfu.removeIf { vfu -> val elementRemoved = newVirtualFileUrls.remove(vfu) if (!elementRemoved) removeFromVfu2EntityIdMap(id, propertyName, vfu) return@removeIf !elementRemoved } if (existingVfu.isEmpty()) return true } else -> { existingVfu as VirtualFileUrl val elementRemoved = newVirtualFileUrls.remove(existingVfu) if (!elementRemoved) { removeFromVfu2EntityIdMap(id, propertyName, existingVfu) return true } } } return false } val property2Vfu = entityId2VirtualFileUrl[id] if (property2Vfu != null) { when (property2Vfu) { is Object2ObjectOpenHashMap<*, *> -> { val existingVfu = property2Vfu[propertyName] if (existingVfu != null && cleanExistingVfu(existingVfu)) { property2Vfu.remove(propertyName) if (property2Vfu.isEmpty()) entityId2VirtualFileUrl.remove(id) } } is Pair<*, *> -> { val existingPropertyName = property2Vfu.first as String if (existingPropertyName == propertyName && cleanExistingVfu(property2Vfu.second!!)) entityId2VirtualFileUrl.remove(id) } } } newVirtualFileUrls.forEach { indexVirtualFileUrl(id, propertyName, it) } } @Synchronized internal fun indexJarDirectories(id: EntityId, virtualFileUrls: Set<VirtualFileUrl>) { entityId2JarDir.removeKey(id) if (virtualFileUrls.isEmpty()) return virtualFileUrls.forEach { entityId2JarDir.put(id, it) } } @Synchronized internal fun index(id: EntityId, propertyName: String, virtualFileUrl: VirtualFileUrl? = null) { startWrite() removeByPropertyFromIndexes(id, propertyName) if (virtualFileUrl == null) return indexVirtualFileUrl(id, propertyName, virtualFileUrl) } internal fun updateIndex(oldId: EntityId, newId: EntityId, oldIndex: VirtualFileIndex) { oldIndex.getVirtualFileUrlInfoByEntityId(oldId).forEach { (property, vfus) -> index(newId, property, vfus) } oldIndex.entityId2JarDir.getValues(oldId).apply { indexJarDirectories(newId, this.toSet()) } } @Synchronized internal fun removeRecordsByEntityId(id: EntityId) { startWrite() entityId2JarDir.removeKey(id) val removedValue = entityId2VirtualFileUrl.remove(id) ?: return when (removedValue) { is Object2ObjectOpenHashMap<*, *> -> removedValue.forEach { (property, vfu) -> removeFromVfu2EntityIdMap(id, property as String, vfu) } is Pair<*, *> -> removeFromVfu2EntityIdMap(id, removedValue.first as String, removedValue.second!!) } } @TestOnly internal fun clear() { startWrite() entityId2VirtualFileUrl.clear() vfu2EntityId.clear() entityId2JarDir.clear() } @TestOnly internal fun copyFrom(another: VirtualFileIndex) { startWrite() entityId2VirtualFileUrl.putAll(another.entityId2VirtualFileUrl) vfu2EntityId.putAll(another.vfu2EntityId) entityId2JarDir.putAll(another.entityId2JarDir) } private fun startWrite() { if (!freezed) return freezed = false entityId2VirtualFileUrl = copyEntityMap(entityId2VirtualFileUrl) vfu2EntityId = copyVfuMap(vfu2EntityId) entityId2JarDir = entityId2JarDir.copy() } fun toImmutable(): VirtualFileIndex { freezed = true return VirtualFileIndex(entityId2VirtualFileUrl, vfu2EntityId, entityId2JarDir) } private fun indexVirtualFileUrl(id: EntityId, propertyName: String, virtualFileUrl: VirtualFileUrl) { val property2Vfu = entityId2VirtualFileUrl[id] fun addVfuToPropertyName(vfu: Any): Any { if (vfu is ObjectOpenHashSet<*>) { (vfu as ObjectOpenHashSet<VirtualFileUrl>).add(virtualFileUrl) return vfu } else { val result = createSmallMemoryFootprintSet<VirtualFileUrl>() result.add(vfu as VirtualFileUrl) result.add(virtualFileUrl) return result } } if (property2Vfu != null) { val newProperty2Vfu = when (property2Vfu) { is Object2ObjectOpenHashMap<*, *> -> { property2Vfu as Object2ObjectOpenHashMap<String, Any> val vfu = property2Vfu[propertyName] if (vfu == null) { property2Vfu[propertyName] = virtualFileUrl } else { property2Vfu[propertyName] = addVfuToPropertyName(vfu) } property2Vfu } is Pair<*, *> -> { property2Vfu as Pair<String, Any> if (property2Vfu.first != propertyName) { val result = createSmallMemoryFootprintMap<String, Any>() result[property2Vfu.first] = property2Vfu.second result[propertyName] = virtualFileUrl result } else { Pair(propertyName, addVfuToPropertyName(property2Vfu.second)) } } else -> null } if (newProperty2Vfu != null) entityId2VirtualFileUrl[id] = newProperty2Vfu } else { entityId2VirtualFileUrl[id] = Pair(propertyName, virtualFileUrl) } val property2EntityId = vfu2EntityId.getOrDefault(virtualFileUrl, Object2LongOpenHashMap()) property2EntityId[getCompositeKey(id, propertyName)] = id vfu2EntityId[virtualFileUrl] = property2EntityId } private fun removeByPropertyFromIndexes(id: EntityId, propertyName: String) { val property2vfu = entityId2VirtualFileUrl[id] ?: return when (property2vfu) { is Object2ObjectOpenHashMap<*, *> -> { property2vfu as Object2ObjectOpenHashMap<String, Any> val vfu = property2vfu.remove(propertyName) ?: return if (property2vfu.isEmpty()) entityId2VirtualFileUrl.remove(id) removeFromVfu2EntityIdMap(id, propertyName, vfu) } is Pair<*, *> -> { val existingPropertyName = property2vfu.first as String if (existingPropertyName != propertyName) return entityId2VirtualFileUrl.remove(id) removeFromVfu2EntityIdMap(id, propertyName, property2vfu.second!!) } } } private fun removeFromVfu2EntityIdMap(id: EntityId, property: String, vfus: Any) { when (vfus) { is Set<*> -> vfus.forEach { removeFromVfu2EntityIdMap(id, property, it as VirtualFileUrl) } else -> removeFromVfu2EntityIdMap(id, property, vfus as VirtualFileUrl) } } private fun removeFromVfu2EntityIdMap(id: EntityId, propertyName: String, vfu: VirtualFileUrl) { val property2EntityId = vfu2EntityId[vfu] if (property2EntityId == null) { LOG.error("The record for $id <=> ${vfu} should be available in both maps") return } property2EntityId.removeLong(getCompositeKey(id, propertyName)) if (property2EntityId.isEmpty()) vfu2EntityId.remove(vfu) } private fun copyEntityMap(originMap: EntityId2Vfu): EntityId2Vfu { val copiedMap = EntityId2Vfu() fun getVirtualFileUrl(value: Any) = if (value is Set<*>) ObjectOpenHashSet(value as Set<VirtualFileUrl>) else value originMap.forEach { (entityId, vfuMap) -> when (vfuMap) { is Map<*, *> -> { vfuMap as Map<String, *> val copiedVfuMap = Object2ObjectOpenHashMap<String, Any>() vfuMap.forEach { copiedVfuMap[it.key] = getVirtualFileUrl(it.value!!) } copiedMap[entityId] = copiedVfuMap } is Pair<*, *> -> { val copiedVfuPair = Pair(vfuMap.first as String, getVirtualFileUrl(vfuMap.second!!)) copiedMap[entityId] = copiedVfuPair } } } return copiedMap } private fun copyVfuMap(originMap: Vfu2EntityId): Vfu2EntityId { val copiedMap = Vfu2EntityId(getHashingStrategy()) originMap.forEach { (key, value) -> copiedMap[key] = Object2LongOpenHashMap(value) } return copiedMap } companion object { private val LOG = logger<MutableVirtualFileIndex>() const val VIRTUAL_FILE_INDEX_ENTITY_SOURCE_PROPERTY = "entitySource" fun from(other: VirtualFileIndex): MutableVirtualFileIndex { if (other is MutableVirtualFileIndex) other.freezed = true return MutableVirtualFileIndex(other.entityId2VirtualFileUrl, other.vfu2EntityId, other.entityId2JarDir) } } } } internal fun getHashingStrategy(): Hash.Strategy<VirtualFileUrl> { val indexSensitivityEnabled = Registry.`is`("ide.new.project.model.index.case.sensitivity", false) if (!indexSensitivityEnabled) return STANDARD_STRATEGY if (!SystemInfoRt.isFileSystemCaseSensitive) return CASE_INSENSITIVE_STRATEGY return STANDARD_STRATEGY } private val STANDARD_STRATEGY: Hash.Strategy<VirtualFileUrl> = object : Hash.Strategy<VirtualFileUrl> { override fun equals(firstVirtualFile: VirtualFileUrl?, secondVirtualFile: VirtualFileUrl?): Boolean { if (firstVirtualFile === secondVirtualFile) return true if (firstVirtualFile == null || secondVirtualFile == null) return false return firstVirtualFile == secondVirtualFile } override fun hashCode(fileUrl: VirtualFileUrl?): Int { if (fileUrl == null) return 0 return fileUrl.hashCode() } } private val CASE_INSENSITIVE_STRATEGY: Hash.Strategy<VirtualFileUrl> = object : Hash.Strategy<VirtualFileUrl> { override fun equals(firstVirtualFile: VirtualFileUrl?, secondVirtualFile: VirtualFileUrl?): Boolean { return StringUtilRt.equal(firstVirtualFile?.url, secondVirtualFile?.url, false) } override fun hashCode(fileUrl: VirtualFileUrl?): Int { if (fileUrl == null) return 0 return Strings.stringHashCodeInsensitive(fileUrl.url) } } //--------------------------------------------------------------------- class VirtualFileUrlProperty<T : ModifiableWorkspaceEntityBase<out WorkspaceEntityBase>> : ReadWriteProperty<T, VirtualFileUrl> { @Suppress("UNCHECKED_CAST") override fun getValue(thisRef: T, property: KProperty<*>): VirtualFileUrl { return ((thisRef.original::class.memberProperties.first { it.name == property.name }) as KProperty1<Any, *>) .get(thisRef.original) as VirtualFileUrl } override fun setValue(thisRef: T, property: KProperty<*>, value: VirtualFileUrl) { if (!thisRef.modifiable.get()) { throw IllegalStateException("Modifications are allowed inside 'addEntity' and 'modifyEntity' methods only!") } val field = thisRef.original.javaClass.getDeclaredField(property.name) field.isAccessible = true field.set(thisRef.original, value) (thisRef.diff as WorkspaceEntityStorageBuilderImpl).indexes.virtualFileIndex.index(thisRef.id, property.name, value) } } //--------------------------------------------------------------------- class VirtualFileUrlNullableProperty<T : ModifiableWorkspaceEntityBase<out WorkspaceEntityBase>> : ReadWriteProperty<T, VirtualFileUrl?> { @Suppress("UNCHECKED_CAST") override fun getValue(thisRef: T, property: KProperty<*>): VirtualFileUrl? { return ((thisRef.original::class.memberProperties.first { it.name == property.name }) as KProperty1<Any, *>) .get(thisRef.original) as VirtualFileUrl? } override fun setValue(thisRef: T, property: KProperty<*>, value: VirtualFileUrl?) { if (!thisRef.modifiable.get()) { throw IllegalStateException("Modifications are allowed inside 'addEntity' and 'modifyEntity' methods only!") } val field = thisRef.original.javaClass.getDeclaredField(property.name) field.isAccessible = true field.set(thisRef.original, value) (thisRef.diff as WorkspaceEntityStorageBuilderImpl).indexes.virtualFileIndex.index(thisRef.id, property.name, value) } } //--------------------------------------------------------------------- class VirtualFileUrlListProperty<T : ModifiableWorkspaceEntityBase<out WorkspaceEntityBase>> : ReadWriteProperty<T, List<VirtualFileUrl>> { @Suppress("UNCHECKED_CAST") override fun getValue(thisRef: T, property: KProperty<*>): List<VirtualFileUrl> { return ((thisRef.original::class.memberProperties.first { it.name == property.name }) as KProperty1<Any, *>) .get(thisRef.original) as List<VirtualFileUrl> } override fun setValue(thisRef: T, property: KProperty<*>, value: List<VirtualFileUrl>) { if (!thisRef.modifiable.get()) { throw IllegalStateException("Modifications are allowed inside 'addEntity' and 'modifyEntity' methods only!") } val field = thisRef.original.javaClass.getDeclaredField(property.name) field.isAccessible = true field.set(thisRef.original, value) (thisRef.diff as WorkspaceEntityStorageBuilderImpl).indexes.virtualFileIndex.index(thisRef.id, property.name, value.toHashSet()) } } /** * This delegate was created specifically for the handling VirtualFileUrls from LibraryRoot */ class VirtualFileUrlLibraryRootProperty<T : ModifiableWorkspaceEntityBase<out WorkspaceEntityBase>> : ReadWriteProperty<T, List<LibraryRoot>> { @Suppress("UNCHECKED_CAST") override fun getValue(thisRef: T, property: KProperty<*>): List<LibraryRoot> { return ((thisRef.original::class.memberProperties.first { it.name == property.name }) as KProperty1<Any, *>) .get(thisRef.original) as List<LibraryRoot> } override fun setValue(thisRef: T, property: KProperty<*>, value: List<LibraryRoot>) { if (!thisRef.modifiable.get()) { throw IllegalStateException("Modifications are allowed inside 'addEntity' and 'modifyEntity' methods only!") } val field = thisRef.original.javaClass.getDeclaredField(property.name) field.isAccessible = true field.set(thisRef.original, value) val jarDirectories = mutableSetOf<VirtualFileUrl>() (thisRef.diff as WorkspaceEntityStorageBuilderImpl).indexes.virtualFileIndex.index(thisRef.id, property.name, value.map { if (it.inclusionOptions != LibraryRoot.InclusionOptions.ROOT_ITSELF) { jarDirectories.add(it.url) } it.url }.toHashSet()) (thisRef.diff as WorkspaceEntityStorageBuilderImpl).indexes.virtualFileIndex.indexJarDirectories(thisRef.id, jarDirectories) } }
apache-2.0
eaa6468ca92ef228499b17c40779aa85
43.679359
203
0.708711
4.63782
false
false
false
false
siosio/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/vfs/CompactVirtualFileSetTest.kt
2
3675
// 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.openapi.vfs import com.intellij.testFramework.fixtures.BareTestFixtureTestCase import com.intellij.testFramework.rules.TempDirectory import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import java.util.concurrent.atomic.AtomicInteger import kotlin.test.assertEquals class CompactVirtualFileSetTest : BareTestFixtureTestCase() { @JvmField @Rule var tempDir = TempDirectory() @Test fun `test empty set`() { val set = CompactVirtualFileSet() assertTrue(set.isEmpty()) assertFalse(set.iterator().hasNext()) } @Test fun `test small set`() { val size = 5 assertTrue(size < CompactVirtualFileSet.INT_SET_LIMIT) assertTrue(size < CompactVirtualFileSet.BIT_SET_LIMIT) doSimpleAddTest(size) } @Test fun `test reasonable set`() { val size = 50 assertTrue(size > CompactVirtualFileSet.INT_SET_LIMIT) assertTrue(size < CompactVirtualFileSet.BIT_SET_LIMIT) doSimpleAddTest(size) } @Test fun `test big set`() { val size = 2000 assertTrue(size > CompactVirtualFileSet.INT_SET_LIMIT) assertTrue(size > CompactVirtualFileSet.BIT_SET_LIMIT) doSimpleAddTest(size) } @Test fun `test addAll()`() { doSimpleAddAllTest(sliceSize = 3) } @Test fun `test reasonable addAll()`() { doSimpleAddAllTest(sliceSize = 50) } @Test fun `test big addAll()`() { doSimpleAddAllTest(sliceSize = 777) } @Test fun `test retainAll() of standard collection`() { } @Test fun `test retainAll() of small CVFSet`() { val size = 5 assertTrue(size < CompactVirtualFileSet.INT_SET_LIMIT) assertTrue(size < CompactVirtualFileSet.BIT_SET_LIMIT) } @Test fun `test retainAll() of reasonable CVFSet`() { val size = 50 assertTrue(size > CompactVirtualFileSet.INT_SET_LIMIT) assertTrue(size < CompactVirtualFileSet.BIT_SET_LIMIT) } @Test fun `test retainAll() of big CVFSet`() { val size = 2000 assertTrue(size > CompactVirtualFileSet.INT_SET_LIMIT) assertTrue(size > CompactVirtualFileSet.BIT_SET_LIMIT) } private fun doSimpleAddAllTest(sliceSize: Int) { val set1 = CompactVirtualFileSet() val set2 = CompactVirtualFileSet() val fileList1 = (0 until sliceSize).map { createFile() } val fileList2 = (0 until sliceSize).map { createFile() } val fileList3 = (0 until sliceSize).map { createFile() } for (virtualFile in fileList1) { set1.add(virtualFile) } for (virtualFile in fileList2) { set1.add(virtualFile) set2.add(virtualFile) } for (virtualFile in fileList3) { set2.add(virtualFile) } assertEquals(2 * sliceSize, set1.size) assertEquals(2 * sliceSize, set2.size) set1.addAll(set2) assertEquals(3 * sliceSize, set1.size) for (file in fileList1 + fileList2 + fileList3) { assertTrue(set1.contains(file)) } } private fun doSimpleAddTest(size: Int) { val set = CompactVirtualFileSet() val fileList = (0 until size).map { createFile() } for (virtualFile in fileList) { set.add(virtualFile) } assertEquals(size, set.size) for (virtualFile in fileList) { assertTrue(set.contains(virtualFile)) } for (virtualFile in set) { assertTrue(fileList.contains(virtualFile)) } } private val counter = AtomicInteger() private fun createFile(): VirtualFile = tempDir.newVirtualFile("file${counter.incrementAndGet()}.txt") }
apache-2.0
0f5794ee0a1d80dfd9e10b5a5ddb8c6c
23.671141
158
0.690612
3.852201
false
true
false
false
JetBrains/xodus
environment/src/main/kotlin/jetbrains/exodus/gc/ComputeUtilizationFromScratchJob.kt
1
3158
/** * 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.gc import jetbrains.exodus.core.dataStructures.hash.LongHashMap import jetbrains.exodus.env.StoreConfig import jetbrains.exodus.env.TransactionBase internal class ComputeUtilizationFromScratchJob(gc: GarbageCollector) : GcJob(gc) { override fun doJob() { val gc = this.gc ?: return val usedSpace = LongHashMap<Long>() val env = gc.environment val location = env.location GarbageCollector.loggingInfo { "Started calculation of log utilization from scratch at $location" } try { val up = gc.utilizationProfile var goon = true while (goon) { env.executeInReadonlyTransaction { txn -> up.clear() // optimistic clearing of files' utilization until no parallel writing transaction happens if (txn.highAddress == env.computeInReadonlyTransaction { tx -> tx.highAddress }) { val log = env.log for (storeName in env.getAllStoreNames(txn) + GarbageCollector.UTILIZATION_PROFILE_STORE_NAME) { // stop if environment is already closed if (this.gc == null) { break } if (env.storeExists(storeName, txn)) { val store = env.openStore(storeName, StoreConfig.USE_EXISTING, txn) val it = (txn as TransactionBase).getTree(store).addressIterator() while (it.hasNext()) { val address = it.next() val loggable = log.read(address) val fileAddress = log.getFileAddress(address) usedSpace[fileAddress] = (usedSpace[fileAddress] ?: 0L) + loggable.length() } } } goon = false } } } // if environment is not closed this.gc?.let { up.setUtilization(usedSpace) up.isDirty = true up.estimateTotalBytesAndWakeGcIfNecessary() } } finally { GarbageCollector.loggingInfo { "Finished calculation of log utilization from scratch at $location" } } } }
apache-2.0
16457dc73ae4d7851685ec5724456eed
44.128571
120
0.541799
5.168576
false
false
false
false
siosio/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/firstStep/BuildSystemTypeSettingComponent.kt
1
5727
// 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.tools.projectWizard.wizard.ui.firstStep import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionButtonLook import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.ActionButtonWithText import com.intellij.openapi.project.DumbAware import icons.OpenapiIcons import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.extensions.gradle.KotlinGradleFacade import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.entity.ValidationResult import org.jetbrains.kotlin.tools.projectWizard.core.entity.isSpecificError import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.DropDownSettingType import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType import org.jetbrains.kotlin.tools.projectWizard.wizard.OnUserSettingChangeStatisticsLogger import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.TitleComponentAlignment import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.IdeaBasedComponentValidator import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.SettingComponent import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.ValidationIndicator import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.awt.Dimension import java.awt.Insets import javax.swing.JComponent class BuildSystemTypeSettingComponent( context: Context ) : SettingComponent<BuildSystemType, DropDownSettingType<BuildSystemType>>( BuildSystemPlugin.type.reference, context ) { private val toolbar by lazy(LazyThreadSafetyMode.NONE) { val buildSystemTypes = read { setting.type.values.filter { setting.type.filter(this, reference, it) } } val actionGroup = DefaultActionGroup(buildSystemTypes.map(::BuildSystemTypeAction)) BuildSystemToolbar(ActionPlaces.UNKNOWN, actionGroup, true) } override val alignment: TitleComponentAlignment get() = TitleComponentAlignment.AlignFormTopWithPadding(6) override val component: JComponent by lazy(LazyThreadSafetyMode.NONE) { toolbar } override val validationIndicator: ValidationIndicator = IdeaBasedComponentValidator(this, component) override fun navigateTo(error: ValidationResult.ValidationError) { if (validationIndicator.validationState.isSpecificError(error)) { component.requestFocus() } } private fun validateBuildSystem(buildSystem: BuildSystemType) = read { setting.validator.validate(this, buildSystem) } private inner class BuildSystemTypeAction( val buildSystemType: BuildSystemType ) : ToggleAction(buildSystemType.text, null, buildSystemType.icon), DumbAware { override fun isSelected(e: AnActionEvent): Boolean = value == buildSystemType override fun setSelected(e: AnActionEvent, state: Boolean) { if (state) { value = buildSystemType OnUserSettingChangeStatisticsLogger.logSettingValueChangedByUser( context.contextComponents.get(), BuildSystemPlugin.type.path, buildSystemType ) } } override fun update(e: AnActionEvent) { super.update(e) val validationResult = validateBuildSystem(buildSystemType) e.presentation.isEnabled = validationResult.isOk e.presentation.description = validationResult.safeAs<ValidationResult.ValidationError>()?.messages?.firstOrNull() } } private inner class BuildSystemToolbar( place: String, actionGroup: ActionGroup, horizontal: Boolean ) : ActionToolbarImplWrapper(place, actionGroup, horizontal) { init { layoutPolicy = ActionToolbar.WRAP_LAYOUT_POLICY } override fun createToolbarButton( action: AnAction, look: ActionButtonLook?, place: String, presentation: Presentation, minimumSize: Dimension ): ActionButton = BuildSystemChooseButton(action as BuildSystemTypeAction, presentation, place, minimumSize) } private inner class BuildSystemChooseButton( action: BuildSystemTypeAction, presentation: Presentation, place: String?, minimumSize: Dimension ) : ActionButtonWithText(action, presentation, place, minimumSize) { override fun getInsets(): Insets = super.getInsets().apply { right += left left = 0 } override fun getPreferredSize(): Dimension { val old = super.getPreferredSize() return Dimension(old.width + LEFT_RIGHT_PADDING * 2, old.height + TOP_BOTTOM_PADDING * 2) } } companion object { private const val LEFT_RIGHT_PADDING = 6 private const val TOP_BOTTOM_PADDING = 2 } } private val BuildSystemType.icon get() = when (this) { BuildSystemType.GradleKotlinDsl -> KotlinIcons.GRADLE_SCRIPT BuildSystemType.GradleGroovyDsl -> KotlinGradleFacade.instance?.gradleIcon ?: KotlinIcons.GRADLE_SCRIPT BuildSystemType.Maven -> OpenapiIcons.RepositoryLibraryLogo BuildSystemType.Jps -> AllIcons.Nodes.Module }
apache-2.0
fd0f7106e0591eb866c328af07404969
41.422222
158
0.731971
5.15018
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionLiteralReturnTypeFix.kt
1
7118
// 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.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.findParentOfType import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument import org.jetbrains.kotlin.resolve.calls.util.getParentResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getValueArgumentForExpression import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import java.util.* class ChangeFunctionLiteralReturnTypeFix( functionLiteralExpression: KtLambdaExpression, type: KotlinType ) : KotlinQuickFixAction<KtLambdaExpression>(functionLiteralExpression) { private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_TYPES_WITH_SHORT_NAMES.renderType(type) private val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES.renderType(type) private val functionLiteralReturnTypeRef: KtTypeReference? get() = element?.functionLiteral?.typeReference private val appropriateQuickFix = createAppropriateQuickFix(functionLiteralExpression, type) private fun createAppropriateQuickFix(functionLiteralExpression: KtLambdaExpression, type: KotlinType): IntentionAction? { val context = functionLiteralExpression.analyze() val functionLiteralType = context.getType(functionLiteralExpression) ?: return null val builtIns = functionLiteralType.constructor.builtIns val functionClass = builtIns.getFunction(functionLiteralType.arguments.size - 1) val functionClassTypeParameters = LinkedList<KotlinType>() for (typeProjection in functionLiteralType.arguments) { functionClassTypeParameters.add(typeProjection.type) } // Replacing return type: functionClassTypeParameters.removeAt(functionClassTypeParameters.size - 1) functionClassTypeParameters.add(type) val eventualFunctionLiteralType = TypeUtils.substituteParameters(functionClass, functionClassTypeParameters) val correspondingProperty = PsiTreeUtil.getParentOfType(functionLiteralExpression, KtProperty::class.java) if (correspondingProperty != null && correspondingProperty.delegate == null && correspondingProperty.initializer?.let { QuickFixUtil.canEvaluateTo(it, functionLiteralExpression) } != false ) { val correspondingPropertyTypeRef = correspondingProperty.typeReference val propertyType = context.get(BindingContext.TYPE, correspondingPropertyTypeRef) return if (propertyType != null && !KotlinTypeChecker.DEFAULT.isSubtypeOf(eventualFunctionLiteralType, propertyType)) ChangeVariableTypeFix(correspondingProperty, eventualFunctionLiteralType) else null } val resolvedCall = functionLiteralExpression.getParentResolvedCall(context, true) if (resolvedCall != null) { val valueArgument = resolvedCall.call.getValueArgumentForExpression(functionLiteralExpression) val correspondingParameter = resolvedCall.getParameterForArgument(valueArgument) if (correspondingParameter != null && correspondingParameter.overriddenDescriptors.size <= 1) { val project = functionLiteralExpression.project val correspondingParameterDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, correspondingParameter) if (correspondingParameterDeclaration is KtParameter) { val correspondingParameterTypeRef = correspondingParameterDeclaration.typeReference val parameterType = context.get(BindingContext.TYPE, correspondingParameterTypeRef) return if (parameterType != null && !KotlinTypeChecker.DEFAULT.isSubtypeOf(eventualFunctionLiteralType, parameterType)) ChangeParameterTypeFix(correspondingParameterDeclaration, eventualFunctionLiteralType) else null } } } val parentFunction = PsiTreeUtil.getParentOfType(functionLiteralExpression, KtFunction::class.java, true) return if (parentFunction != null && QuickFixUtil.canFunctionOrGetterReturnExpression(parentFunction, functionLiteralExpression)) { val parentFunctionReturnTypeRef = parentFunction.typeReference val parentFunctionReturnType = context.get(BindingContext.TYPE, parentFunctionReturnTypeRef) if (parentFunctionReturnType != null && !KotlinTypeChecker.DEFAULT .isSubtypeOf(eventualFunctionLiteralType, parentFunctionReturnType) ) ChangeCallableReturnTypeFix.ForEnclosing(parentFunction, eventualFunctionLiteralType) else null } else null } override fun getText() = appropriateQuickFix?.text ?: KotlinBundle.message("fix.change.return.type.lambda", typePresentation) override fun getFamilyName() = KotlinBundle.message("fix.change.return.type.family") override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = functionLiteralReturnTypeRef != null || appropriateQuickFix != null && appropriateQuickFix.isAvailable( project, editor!!, file ) override fun invoke(project: Project, editor: Editor?, file: KtFile) { functionLiteralReturnTypeRef?.let { val newTypeRef = it.replace(KtPsiFactory(file).createType(typeSourceCode)) as KtTypeReference ShortenReferences.DEFAULT.process(newTypeRef) } if (appropriateQuickFix != null && appropriateQuickFix.isAvailable(project, editor!!, file)) { appropriateQuickFix.invoke(project, editor, file) } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val functionLiteralExpression = diagnostic.psiElement.findParentOfType<KtLambdaExpression>(strict = false) ?: return null return ChangeFunctionLiteralReturnTypeFix(functionLiteralExpression, functionLiteralExpression.builtIns.unitType) } } }
apache-2.0
20d4b7e29749afa8489ab6122f274728
55.047244
158
0.746137
6.057872
false
false
false
false
vovagrechka/fucking-everything
alraune/alraune/src/main/java/alraune/operations/GlobalPopup.kt
1
9963
package alraune.operations import alraune.* import org.eclipse.jface.dialogs.MessageDialog import org.eclipse.jface.viewers.LabelProvider import org.eclipse.jface.viewers.TreeViewer import org.eclipse.swt.layout.FillLayout import org.eclipse.swt.widgets.Shell import org.eclipse.jface.viewers.ITreeContentProvider import org.eclipse.jface.viewers.StructuredSelection import org.eclipse.swt.graphics.Point import vgrechka.* import kotlin.concurrent.thread import org.eclipse.swt.SWT import org.eclipse.swt.events.* import java.io.ObjectOutputStream import java.net.Socket import kotlin.system.exitProcess class GlobalPopup(val onCloseExitProcess: Boolean) { val blah = Blah().attachToFirstOrIgnore() val prevFocusedWindow = XorgViaTools.focusedWindowIDString() var treeView by once<TreeViewer>() var shell by once<Shell>() companion object { var prevShell: Shell? = null class Key(val code: Short, val normal: String? = null, val shifted: String? = null) val vimKeys = listOf( Key(CLib.KEY.BACKSPACE, "<BS>"), Key(CLib.KEY.TAB, "<Tab>"), Key(CLib.KEY.ENTER, "<CR>"), Key(CLib.KEY.ESC, "<Esc>"), Key(CLib.KEY.SPACE, "<Space>"), Key(CLib.KEY.UP, "<Up>"), Key(CLib.KEY.DOWN, "<Down>"), Key(CLib.KEY.LEFT, "<Left>"), Key(CLib.KEY.RIGHT, "<Right>"), Key(CLib.KEY.DELETE, "<Del>"), Key(CLib.KEY.HOME, "<Home>"), Key(CLib.KEY.END, "<End>"), Key(CLib.KEY.BACKSLASH, null, "<Bar>"), Key(CLib.KEY.GRAVE, "`", "~"), Key(CLib.KEY._1, "1", "!"), Key(CLib.KEY._2, "2", "@"), Key(CLib.KEY._3, "3", "#"), Key(CLib.KEY._4, "4", "$"), Key(CLib.KEY._5, "5", "%"), Key(CLib.KEY._6, "6", "^"), Key(CLib.KEY._7, "7", "&"), Key(CLib.KEY._8, "8", "*"), Key(CLib.KEY._9, "9", "("), Key(CLib.KEY._0, "0", ")"), Key(CLib.KEY.MINUS, "-", "_"), Key(CLib.KEY.EQUAL, "=", "+"), Key(CLib.KEY.Q, "q", "Q"), Key(CLib.KEY.W, "w", "W"), Key(CLib.KEY.E, "e", "E"), Key(CLib.KEY.R, "r", "R"), Key(CLib.KEY.T, "t", "T"), Key(CLib.KEY.Y, "y", "Y"), Key(CLib.KEY.U, "u", "U"), Key(CLib.KEY.I, "i", "I"), Key(CLib.KEY.O, "o", "O"), Key(CLib.KEY.P, "p", "P"), Key(CLib.KEY.LEFTBRACE, "[", "{"), Key(CLib.KEY.RIGHTBRACE, "]", "}"), Key(CLib.KEY.BACKSLASH, "\\", "|"), Key(CLib.KEY.A, "a", "A"), Key(CLib.KEY.S, "s", "S"), Key(CLib.KEY.D, "d", "D"), Key(CLib.KEY.F, "f", "F"), Key(CLib.KEY.G, "g", "G"), Key(CLib.KEY.H, "h", "H"), Key(CLib.KEY.J, "j", "J"), Key(CLib.KEY.K, "k", "K"), Key(CLib.KEY.L, "l", "L"), Key(CLib.KEY.SEMICOLON, ";", ":"), Key(CLib.KEY.APOSTROPHE, "'", "\""), Key(CLib.KEY.Z, "z", "Z"), Key(CLib.KEY.X, "x", "X"), Key(CLib.KEY.C, "c", "C"), Key(CLib.KEY.V, "v", "V"), Key(CLib.KEY.B, "b", "B"), Key(CLib.KEY.N, "n", "N"), Key(CLib.KEY.M, "m", "M"), Key(CLib.KEY.COMMA, ",", "<"), Key(CLib.KEY.DOT, ".", ">"), Key(CLib.KEY.SLASH, "/", "?"), Key(CLib.KEY.SPACE, " ") ) } init { SWTPile.display.asyncExec { init0() } } @Synchronized fun init0() { prevShell?.let { if (!it.isDisposed) it.close() } shell = Shell(SWTPile.display, SWT.DIALOG_TRIM) val shellTitle = GlobalPopup::class.simpleName!! shell.text = shellTitle shell.size = Point(500, 500) shell.location = run { val primary = SWTPile.display.primaryMonitor val bounds = primary.bounds val rect = shell.bounds Point(bounds.x + (bounds.width - rect.width) / 2, bounds.y + (bounds.height - rect.height) / 2) } shell.layout = FillLayout() treeView = TreeViewer(shell) treeView.labelProvider = LabelProvider() treeView.contentProvider = MyContentProvider() val root = makeRootItem() treeView.input = root treeView.setSelection(StructuredSelection(l(root.children.first())), true) treeView.tree.addKeyListener(object : KeyListener { override fun keyPressed(e: KeyEvent) { // clog("e.keyCode = ${e.keyCode}") when (e.keyCode) { SWT.ESC.toInt() -> shell.close() SWT.CR.toInt() -> runSelection() } } override fun keyReleased(e: KeyEvent) {} }) treeView.tree.addMouseListener(object : MouseListener { override fun mouseDoubleClick(e: MouseEvent) { runSelection() } override fun mouseDown(e: MouseEvent) {} override fun mouseUp(e: MouseEvent?) {} }) if (onCloseExitProcess) { shell.addShellListener(object : ShellAdapter() { override fun shellClosed(e: ShellEvent?) { exitProcess(0) } }) } SWTPile.bringShellToFrontWhenShown(shell) prevShell = shell shell.open() } fun runSelection() { treeView.structuredSelection.firstElement?.let { (it as PizdaItem).act() } } fun makeRootItem(): PizdaItem { val root = PizdaItem("ROOT", null) fun addItem(x: PizdaItem) { root.children += x x.parent = root } addItem(PizdaItem("Say 'pizda'") { MessageDialog.openInformation(shell, "Read This Shit", "Pizda. Big and rather hairy one :)") shell.close() }) addItem(PizdaItem("val --> by once<>()") { vimType("<BS><BS>rrf:s by once<>()<Esc> xDF>P_") }) if (false) { addItem(PizdaItem("Open another popup") {GlobalPopup(onCloseExitProcess = false)}) addItem(PizdaItem("Throw runtime exception") {bitch("Мне пиздец")}) addItem(PizdaItem("Throw exception") {throw Exception("Я в жопе")}) addItem(PizdaItem("Throw error") {throw Error("Реально вафли")}) } return root } fun vimType(string: String) { // blah.info("prevFocusedWindow = $prevFocusedWindow") XorgViaTools.activateWindowByIDString(prevFocusedWindow) Socket("127.0.0.1", AlCtl_GlobalHotKeys.rootPort).use { val ostm = ObjectOutputStream(it.getOutputStream()) ostm.writeUTF(AlGlobal0.xstream.toXML(object : AlCtl_GlobalHotKeys.RootClient() { override fun dance(keyboard: KeyboardAsLibevdevUinput) { Thread.sleep(100) var i = 0 o@while (i < string.length) { Thread.sleep(10) val sub = string.substring(i) for (key in vimKeys) { var matched: String? = null var shift by once<Boolean>() key.normal?.let { if (sub.startsWith(it)) { matched = it shift = false } } key.shifted?.let { if (sub.startsWith(it)) { matched = it shift = true } } if (matched != null) { i += matched!!.length if (shift) keyboard.emitKeyPress(CLib.KEY.LEFTSHIFT) keyboard.type(key.code) if (shift) keyboard.emitKeyRelease(CLib.KEY.LEFTSHIFT) continue@o } } bitch("I have no fucking idea how to type this: $sub") } } })) ostm.close() } shell.close() } class MyContentProvider : ITreeContentProvider { override fun getElements(inputElement: Any): Array<Any> { return (inputElement as PizdaItem).children.toTypedArray() } override fun getChildren(parentElement: Any): Array<Any> { return getElements(parentElement) } override fun getParent(element: Any?): Any? { return if (element == null) { null } else (element as PizdaItem).parent } override fun hasChildren(element: Any): Boolean { return (element as PizdaItem).children.isNotEmpty() } } class PizdaItem(var title: String, var parent: PizdaItem? = null, val act: () -> Unit = {}) { val children = mutableListOf<PizdaItem>() override fun toString() = title } object Test1 { @JvmStatic fun main(args: Array<String>) { GlobalPopup(onCloseExitProcess = false) } } object Test2 { @JvmStatic fun main(args: Array<String>) { while (true) { Thread.sleep(5000) GlobalPopup(onCloseExitProcess = false) } } } } class AlCtl_GlobalPopup : AlCtlCommand() { override fun dance() { GlobalPopup(onCloseExitProcess = true) } }
apache-2.0
c8c1cef7548ac712bed744906a072d7f
30.643312
107
0.485105
3.963303
false
false
false
false
jwren/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/data/PackagesUpgradesUtils.kt
1
4959
package com.jetbrains.packagesearch.intellij.plugin.data import com.intellij.openapi.module.Module import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ModuleModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackagesToUpgrade import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperationFactory import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.upgradeCandidateVersionOrNull import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.PackageVersionNormalizer import com.jetbrains.packagesearch.intellij.plugin.util.logError import com.jetbrains.packagesearch.packageversionutils.PackageVersionUtils internal suspend fun computePackageUpgrades( installedPackages: List<PackageModel.Installed>, onlyStable: Boolean, normalizer: PackageVersionNormalizer, repos: KnownRepositories.All, nativeModulesMap: Map<ProjectModule, ModuleModel> ): PackagesToUpgrade { val operationFactory = PackageSearchOperationFactory() val updatesByModule = mutableMapOf<Module, MutableSet<PackagesToUpgrade.PackageUpgradeInfo>>() for (installedPackageModel in installedPackages) { val availableVersions = installedPackageModel.getAvailableVersions(onlyStable) if (installedPackageModel.remoteInfo == null || availableVersions.isEmpty()) continue for (usageInfo in installedPackageModel.usageInfo) { val currentVersion = usageInfo.version if (currentVersion !is PackageVersion.Named) continue val normalizedPackageVersion = runCatching { NormalizedPackageVersion.parseFrom(currentVersion, normalizer) } .onFailure { logError(throwable = it) { "Unable to normalize version: $currentVersion" } } .getOrNull() ?: continue val upgradeVersion = PackageVersionUtils.upgradeCandidateVersionOrNull(normalizedPackageVersion, availableVersions) val moduleModel = nativeModulesMap[usageInfo.projectModule] if (upgradeVersion != null && upgradeVersion.originalVersion is PackageVersion.Named && moduleModel != null) { @Suppress("UNCHECKED_CAST") // The if guards us against cast errors updatesByModule.getOrPut(usageInfo.projectModule.nativeModule) { mutableSetOf() } += PackagesToUpgrade.PackageUpgradeInfo( packageModel = installedPackageModel, usageInfo = usageInfo, targetVersion = upgradeVersion as NormalizedPackageVersion<PackageVersion.Named>, computeUpgradeOperationsForSingleModule = computeUpgradeOperationsForSingleModule( packageModel = installedPackageModel, targetModule = moduleModel, knownRepositoriesInTargetModules = repos.filterOnlyThoseUsedIn(TargetModules.One(moduleModel)), onlyStable = onlyStable, operationFactory = operationFactory ) ) } } } return PackagesToUpgrade(updatesByModule) } internal suspend inline fun computeUpgradeOperationsForSingleModule( packageModel: PackageModel.Installed, targetModule: ModuleModel, knownRepositoriesInTargetModules: KnownRepositories.InTargetModules, onlyStable: Boolean, operationFactory: PackageSearchOperationFactory = PackageSearchOperationFactory() ): List<PackageSearchOperation<*>> { val availableVersions = packageModel.getAvailableVersions(onlyStable) val upgradeVersion = when { availableVersions.isNotEmpty() -> { val currentVersion = packageModel.latestInstalledVersion PackageVersionUtils.upgradeCandidateVersionOrNull(currentVersion, availableVersions) } else -> null } return upgradeVersion?.let { operationFactory.computeUpgradeActionsFor( project = targetModule.projectModule.nativeModule.project, packageModel = packageModel, moduleModel = targetModule, knownRepositories = knownRepositoriesInTargetModules, targetVersion = it ) } ?: emptyList() }
apache-2.0
6db1ce6061d78a4bd5d88edff3383c93
54.1
127
0.739262
6.040195
false
false
false
false
anibyl/slounik
main/src/main/java/org/anibyl/slounik/dialogs/AboutDialog.kt
1
1732
package org.anibyl.slounik.dialogs import android.app.Dialog import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v4.app.DialogFragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import android.widget.Button import android.widget.TextView import org.anibyl.slounik.BuildConfig import org.anibyl.slounik.R /** * About information dialog. * * @author Usievaład Kimajeŭ * @created 26.12.2016 */ class AboutDialog : DialogFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view: View = inflater.inflate(R.layout.about, container, false) val version: TextView = view.findViewById(R.id.about_dialog_version) val homepageButton = view.findViewById(R.id.about_dialog_homepage_button) as Button val betaParticipationButton = view.findViewById(R.id.about_dialog_beta_participation_button) as Button val closeButton = view.findViewById(R.id.about_dialog_close_button) as Button version.text = BuildConfig.VERSION_NAME homepageButton.setOnClickListener { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(resources.getString(R.string.homepage)))) } betaParticipationButton.setOnClickListener { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(resources.getString(R.string.beta_participation_page)))) } closeButton.setOnClickListener { dismiss() } isCancelable = true return view } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) return dialog } }
gpl-3.0
d7fce5fecdc878937b39c61224c6a336
28.322034
113
0.788439
3.752711
false
false
false
false
youdonghai/intellij-community
platform/configuration-store-impl/src/FileBasedStorage.kt
1
11142
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.notification.Notifications import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.components.TrackingPathMacroSubstitutor import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.fileEditor.impl.LoadTextUtil import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtil import com.intellij.util.LineSeparator import com.intellij.util.io.delete import com.intellij.util.io.exists import com.intellij.util.io.readChars import com.intellij.util.io.systemIndependentPath import com.intellij.util.loadElement import org.jdom.Element import org.jdom.JDOMException import org.jdom.Parent import java.io.IOException import java.nio.ByteBuffer import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path import java.nio.file.attribute.BasicFileAttributes open class FileBasedStorage(file: Path, fileSpec: String, rootElementName: String?, pathMacroManager: TrackingPathMacroSubstitutor? = null, roamingType: RoamingType? = null, provider: StreamProvider? = null) : XmlElementStorage(fileSpec, rootElementName, pathMacroManager, roamingType, provider) { private @Volatile var cachedVirtualFile: VirtualFile? = null private var lineSeparator: LineSeparator? = null private var blockSavingTheContent = false @Volatile var file = file private set init { if (ApplicationManager.getApplication().isUnitTestMode && file.toString().startsWith('$')) { throw AssertionError("It seems like some macros were not expanded for path: $file") } } protected open val isUseXmlProlog: Boolean = false // we never set io file to null fun setFile(virtualFile: VirtualFile?, ioFileIfChanged: Path?) { cachedVirtualFile = virtualFile if (ioFileIfChanged != null) { file = ioFileIfChanged } } override fun createSaveSession(states: StateMap) = FileSaveSession(states, this) protected open class FileSaveSession(storageData: StateMap, storage: FileBasedStorage) : XmlElementStorage.XmlElementStorageSaveSession<FileBasedStorage>(storageData, storage) { override fun save() { if (!storage.blockSavingTheContent) { super.save() } } override fun saveLocally(element: Element?) { if (storage.lineSeparator == null) { storage.lineSeparator = if (storage.isUseXmlProlog) LineSeparator.LF else LineSeparator.getSystemLineSeparator() } val virtualFile = storage.virtualFile if (element == null) { deleteFile(storage.file, this, virtualFile) storage.cachedVirtualFile = null } else { storage.cachedVirtualFile = writeFile(storage.file, this, virtualFile, element, if (storage.isUseXmlProlog) storage.lineSeparator!! else LineSeparator.LF, storage.isUseXmlProlog) } } } val virtualFile: VirtualFile? get() { var result = cachedVirtualFile if (result == null) { result = LocalFileSystem.getInstance().findFileByPath(file.systemIndependentPath) cachedVirtualFile = result } return cachedVirtualFile } override fun loadLocalData(): Element? { blockSavingTheContent = false try { // use VFS to load module file because it is refreshed and loaded into VFS in any case if (fileSpec != StoragePathMacros.MODULE_FILE) { return loadLocalDataUsingIo() } val file = virtualFile if (file == null || file.isDirectory || !file.isValid) { LOG.debug { "Document was not loaded for $fileSpec, not a file" } } else if (file.length == 0L) { processReadException(null) } else { val charBuffer = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(file.contentsToByteArray())) lineSeparator = detectLineSeparators(charBuffer, if (isUseXmlProlog) null else LineSeparator.LF) return JDOMUtil.loadDocument(charBuffer).detachRootElement() } return null } catch (e: JDOMException) { processReadException(e) } catch (e: IOException) { processReadException(e) } return null } private fun loadLocalDataUsingIo(): Element? { val attributes: BasicFileAttributes? try { attributes = Files.readAttributes(file, BasicFileAttributes::class.java) } catch (e: NoSuchFileException) { LOG.debug { "Document was not loaded for $fileSpec, doesn't exist" } return null } if (!attributes.isRegularFile) { LOG.debug { "Document was not loaded for $fileSpec, not a file" } } else if (attributes.size() == 0L) { processReadException(null) } else { val data = file.readChars() lineSeparator = detectLineSeparators(data, if (isUseXmlProlog) null else LineSeparator.LF) return loadElement(data) } return null } private fun processReadException(e: Exception?) { val contentTruncated = e == null blockSavingTheContent = !contentTruncated && (PROJECT_FILE == fileSpec || fileSpec.startsWith(PROJECT_CONFIG_DIR) || fileSpec == StoragePathMacros.MODULE_FILE || fileSpec == StoragePathMacros.WORKSPACE_FILE) if (!ApplicationManager.getApplication().isUnitTestMode && !ApplicationManager.getApplication().isHeadlessEnvironment) { if (e != null) { LOG.info(e) } Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, "Load Settings", "Cannot load settings from file '$file': ${if (contentTruncated) "content truncated" else e!!.message}\n${if (blockSavingTheContent) "Please correct the file content" else "File content will be recreated"}", NotificationType.WARNING) .notify(null) } } override fun toString() = file.systemIndependentPath } fun writeFile(file: Path?, requestor: Any, virtualFile: VirtualFile?, element: Element, lineSeparator: LineSeparator, prependXmlProlog: Boolean): VirtualFile { val result = if (file != null && (virtualFile == null || !virtualFile.isValid)) { getOrCreateVirtualFile(requestor, file) } else { virtualFile!! } if (LOG.isDebugEnabled || ApplicationManager.getApplication().isUnitTestMode) { val content = element.toBufferExposingByteArray(lineSeparator.separatorString) if (isEqualContent(result, lineSeparator, content, prependXmlProlog)) { throw IllegalStateException("Content equals, but it must be handled not on this level: ${result.name}") } else if (DEBUG_LOG != null && ApplicationManager.getApplication().isUnitTestMode) { DEBUG_LOG = "${result.path}:\n$content\nOld Content:\n${LoadTextUtil.loadText(result)}" } } doWrite(requestor, result, element, lineSeparator, prependXmlProlog) return result } private val XML_PROLOG = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>".toByteArray() private fun isEqualContent(result: VirtualFile, lineSeparator: LineSeparator, content: BufferExposingByteArrayOutputStream, prependXmlProlog: Boolean): Boolean { val headerLength = if (!prependXmlProlog) 0 else XML_PROLOG.size + lineSeparator.separatorBytes.size if (result.length.toInt() != (headerLength + content.size())) { return false } val oldContent = result.contentsToByteArray() if (prependXmlProlog && (!ArrayUtil.startsWith(oldContent, XML_PROLOG) || !ArrayUtil.startsWith(oldContent, XML_PROLOG.size, lineSeparator.separatorBytes))) { return false } return (headerLength..oldContent.size - 1).all { oldContent[it] == content.internalBuffer[it - headerLength] } } private fun doWrite(requestor: Any, file: VirtualFile, content: Any, lineSeparator: LineSeparator, prependXmlProlog: Boolean) { LOG.debug { "Save ${file.presentableUrl}" } if (!file.isWritable) { // may be element is not long-lived, so, we must write it to byte array val byteArray = (content as? Element)?.toBufferExposingByteArray(lineSeparator.separatorString) ?: content as BufferExposingByteArrayOutputStream throw ReadOnlyModificationException(file, StateStorage.SaveSession { doWrite(requestor, file, byteArray, lineSeparator, prependXmlProlog) }) } runWriteAction { file.getOutputStream(requestor).use { out -> if (prependXmlProlog) { out.write(XML_PROLOG) out.write(lineSeparator.separatorBytes) } if (content is Element) { JDOMUtil.writeParent(content, out, lineSeparator.separatorString) } else { (content as BufferExposingByteArrayOutputStream).writeTo(out) } } } } internal fun Parent.toBufferExposingByteArray(lineSeparator: String = "\n"): BufferExposingByteArrayOutputStream { val out = BufferExposingByteArrayOutputStream(512) JDOMUtil.writeParent(this, out, lineSeparator) return out } internal fun detectLineSeparators(chars: CharSequence, defaultSeparator: LineSeparator?): LineSeparator { for (c in chars) { if (c == '\r') { return LineSeparator.CRLF } else if (c == '\n') { // if we are here, there was no \r before return LineSeparator.LF } } return defaultSeparator ?: LineSeparator.getSystemLineSeparator() } private fun deleteFile(file: Path, requestor: Any, virtualFile: VirtualFile?) { if (virtualFile == null) { LOG.warn("Cannot find virtual file $file") } if (virtualFile == null) { if (file.exists()) { file.delete() } } else if (virtualFile.exists()) { if (virtualFile.isWritable) { deleteFile(requestor, virtualFile) } else { throw ReadOnlyModificationException(virtualFile, StateStorage.SaveSession { deleteFile(requestor, virtualFile) }) } } } internal fun deleteFile(requestor: Any, virtualFile: VirtualFile) { runWriteAction { virtualFile.delete(requestor) } } internal class ReadOnlyModificationException(val file: VirtualFile, val session: StateStorage.SaveSession?) : RuntimeException("File is read-only: "+file)
apache-2.0
bdae7d0aac4fb0c1b4a70b2cff9ad83b
36.772881
215
0.717824
4.800517
false
false
false
false
GunoH/intellij-community
platform/script-debugger/protocol/protocol-reader-runtime/src/org/jetbrains/jsonProtocol/OutMessage.kt
2
6455
// 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.jsonProtocol import com.google.gson.stream.JsonWriter import io.netty.buffer.ByteBuf import io.netty.buffer.ByteBufAllocator import io.netty.buffer.ByteBufUtf8Writer import io.netty.buffer.ByteBufUtil import it.unimi.dsi.fastutil.ints.IntList import it.unimi.dsi.fastutil.ints.IntSet import org.jetbrains.io.JsonUtil open class OutMessage { val buffer: ByteBuf = ByteBufAllocator.DEFAULT.buffer() val writer: JsonWriter = JsonWriter(ByteBufUtf8Writer(buffer)) private var finalized: Boolean = false init { writer.beginObject() } open fun beginArguments() { } fun writeMap(name: String, value: Map<String, String>? = null) { if (value == null) return beginArguments() writer.name(name) writer.beginObject() for ((key, value1) in value) { writer.name(key).value(value1) } writer.endObject() } protected fun writeLongArray(name: String, value: LongArray) { beginArguments() writer.name(name) writer.beginArray() for (v in value) { writer.value(v) } writer.endArray() } fun writeDoubleArray(name: String, value: DoubleArray) { beginArguments() writer.name(name) writer.beginArray() for (v in value) { writer.value(v) } writer.endArray() } fun writeIntArray(name: String, value: IntArray? = null) { if (value == null) { return } beginArguments() writer.name(name) writer.beginArray() for (v in value) { writer.value(v.toLong()) } writer.endArray() } fun writeIntSet(name: String, value: IntSet) { beginArguments() writer.name(name) writer.beginArray() val iterator = value.iterator() while (iterator.hasNext()) { writer.value(iterator.nextInt().toLong()) } writer.endArray() } fun writeIntList(name: String, value: IntList) { beginArguments() writer.name(name) writer.beginArray() for (i in 0 until value.size) { writer.value(value.getInt(i).toLong()) } writer.endArray() } fun writeSingletonIntArray(name: String, value: Int) { beginArguments() writer.name(name) writer.beginArray() writer.value(value.toLong()) writer.endArray() } fun <E : OutMessage> writeList(name: String, value: List<E>?) { if (value.isNullOrEmpty()) { return } beginArguments() writer.name(name) writer.beginArray() var isNotFirst = false for (item in value) { try { if (isNotFirst) { buffer.writeByte(','.code).writeByte(' '.code) } else { isNotFirst = true } if (!item.finalized) { item.finalized = true try { item.writer.endObject() } catch (e: IllegalStateException) { if ("Nesting problem." == e.message) { throw RuntimeException(item.buffer.toString(Charsets.UTF_8) + "\nparent:\n" + buffer.toString(Charsets.UTF_8), e) } else { throw e } } } buffer.writeBytes(item.buffer) } finally { if (item.buffer.refCnt() > 0) { item.buffer.release() } } } writer.endArray() } fun writeStringList(name: String, value: Collection<String>?) { if (value == null) return beginArguments() JsonWriters.writeStringList(writer, name, value) } fun writeEnumList(name: String, values: Collection<Enum<*>>) { beginArguments() writer.name(name).beginArray() for (item in values) { writer.value(item.toString()) } writer.endArray() } fun writeMessage(name: String, value: OutMessage?) { if (value == null) { return } try { beginArguments() prepareWriteRaw(this, name) if (!value.finalized) { value.close() } buffer.writeBytes(value.buffer) } finally { if (value.buffer.refCnt() > 0) { value.buffer.release() } } } fun close() { assert(!finalized) finalized = true writer.endObject() writer.close() } protected fun writeLong(name: String, value: Long) { beginArguments() writer.name(name).value(value) } fun writeString(name: String, value: String?) { if (value != null) { writeNullableString(name, value) } } fun writeNullableString(name: String, value: CharSequence?) { beginArguments() writer.name(name).value(value?.toString()) } } fun prepareWriteRaw(message: OutMessage, name: String) { message.writer.name(name).nullValue() val itemBuffer = message.buffer itemBuffer.writerIndex(itemBuffer.writerIndex() - "null".length) } fun doWriteRaw(message: OutMessage, rawValue: String) { ByteBufUtil.writeUtf8(message.buffer, rawValue) } fun OutMessage.writeEnum(name: String, value: Enum<*>?, defaultValue: Enum<*>?) { if (value != null && value != defaultValue) { writeEnum(name, value) } } fun OutMessage.writeEnum(name: String, value: Enum<*>) { beginArguments() writer.name(name).value(value.toString()) } fun OutMessage.writeString(name: String, value: CharSequence?, defaultValue: CharSequence?) { if (value != null && value != defaultValue) { writeString(name, value) } } fun OutMessage.writeString(name: String, value: CharSequence) { beginArguments() prepareWriteRaw(this, name) JsonUtil.escape(value, buffer) } fun OutMessage.writeInt(name: String, value: Int, defaultValue: Int) { if (value != defaultValue) { writeInt(name, value) } } fun OutMessage.writeInt(name: String, value: Int?) { if (value != null) { beginArguments() writer.name(name).value(value.toLong()) } } fun OutMessage.writeBoolean(name: String, value: Boolean, defaultValue: Boolean) { if (value != defaultValue) { writeBoolean(name, value) } } fun OutMessage.writeBoolean(name: String, value: Boolean?) { if (value != null) { beginArguments() writer.name(name).value(value) } } fun OutMessage.writeDouble(name: String, value: Double?, defaultValue: Double?) { if (value != null && value != defaultValue) { writeDouble(name, value) } } fun OutMessage.writeDouble(name: String, value: Double) { beginArguments() writer.name(name).value(value) }
apache-2.0
0e0c6d63adf0ae0108a69347f01eed5a
22.819188
140
0.633927
3.933577
false
false
false
false
GunoH/intellij-community
java/execution/impl/src/com/intellij/execution/vmOptions/VMOptionsParser.kt
2
2755
// 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.vmOptions internal object VMOptionsParser { internal fun parseXXOptions(text: String) : List<VMOption> { val lines = text.lineSequence().drop(1) val options = lines.mapNotNull { val lbraceIndex = it.indexOf("{") if (lbraceIndex == -1) return@mapNotNull null val rbraceIndex = it.indexOf("}") if (rbraceIndex == -1) return@mapNotNull null val kind = it.substring(lbraceIndex, rbraceIndex) val optionKind = if (kind.contains("product")) { VMOptionKind.Product } else if (kind.contains("experimental")) { VMOptionKind.Experimental } else if (kind.contains("diagnostic")) { VMOptionKind.Diagnostic } else { return@mapNotNull null } val fragments = it.split(" ").filter { part -> part.isNotBlank() } if (fragments.isEmpty()) return@mapNotNull null val indexOfEq = fragments.indexOf("=") val maybeDefault = fragments.getOrNull(indexOfEq + 1) ?: return@mapNotNull null val default = if (maybeDefault.startsWith("{")) { null } else { maybeDefault } VMOption(fragments[1], fragments[0], default, optionKind, null, VMOptionVariant.XX) }.toList() return options } internal fun parseXOptions(stderr: String): List<VMOption>? { val options = ArrayList<VMOption>() var currentOption: OptionBuilder? = null val tailIndex = stderr.indexOf("These extra options are subject to change without notice.") if (tailIndex == -1) return null for (line in stderr.trimStart().substring(0, tailIndex).lines()) { val trimmed = line.trim() if (trimmed.startsWith("-X")) { if (currentOption != null) { options.add(currentOption.build()) } val indexOfSpace = trimmed.indexOf(' ') if (indexOfSpace != -1) { currentOption = OptionBuilder(trimmed.substring(2, indexOfSpace)) currentOption.doc.add(trimmed.substring(indexOfSpace).trim()) } else { currentOption = OptionBuilder(trimmed.substring(2)) } } else { currentOption?.doc?.add(trimmed) } } if (currentOption != null) { options.add(currentOption.build()) } return options } private class OptionBuilder(name: String) { val name = name.split("<")[0] val doc = ArrayList<String>() fun build(): VMOption { return VMOption(name, type = null, defaultValue = null, kind = VMOptionKind.Product, doc.joinToString(separator = " ") { it }, VMOptionVariant.X) } } }
apache-2.0
587ae528d7341af55256e1571a786af2
33.024691
132
0.625771
4.212538
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/util/ideBuiltInsUtils.kt
7
2476
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.caches.resolve.util import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.base.projectStructure.IdeBuiltInsLoadingState import org.jetbrains.kotlin.idea.base.projectStructure.isCoreKotlinLibrary import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.IdeaModuleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.LibraryInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.SdkInfo import org.jetbrains.kotlin.idea.caches.project.* internal interface ModuleFilters { fun sdkFacadeFilter(module: IdeaModuleInfo): Boolean fun libraryFacadeFilter(module: IdeaModuleInfo): Boolean fun moduleFacadeFilter(module: IdeaModuleInfo): Boolean } private object ClassLoaderBuiltInsModuleFilters : ModuleFilters { override fun sdkFacadeFilter(module: IdeaModuleInfo): Boolean = module is SdkInfo override fun libraryFacadeFilter(module: IdeaModuleInfo): Boolean = module is LibraryInfo override fun moduleFacadeFilter(module: IdeaModuleInfo): Boolean = !module.isLibraryClasses() } private class DependencyBuiltinsModuleFilters(private val project: Project) : ModuleFilters { override fun sdkFacadeFilter(module: IdeaModuleInfo): Boolean = module is SdkInfo || module is LibraryInfo && module.isCoreKotlinLibrary(project) override fun libraryFacadeFilter(module: IdeaModuleInfo): Boolean = module is LibraryInfo && !module.isCoreKotlinLibrary(project) override fun moduleFacadeFilter(module: IdeaModuleInfo): Boolean = !module.isLibraryClasses() } internal class GlobalFacadeModuleFilters(project: Project) : ModuleFilters { private val impl = when (IdeBuiltInsLoadingState.state) { IdeBuiltInsLoadingState.IdeBuiltInsLoading.FROM_CLASSLOADER -> ClassLoaderBuiltInsModuleFilters IdeBuiltInsLoadingState.IdeBuiltInsLoading.FROM_DEPENDENCIES_JVM -> DependencyBuiltinsModuleFilters(project) } override fun sdkFacadeFilter(module: IdeaModuleInfo): Boolean = impl.sdkFacadeFilter(module) override fun libraryFacadeFilter(module: IdeaModuleInfo): Boolean = impl.libraryFacadeFilter(module) override fun moduleFacadeFilter(module: IdeaModuleInfo): Boolean = impl.moduleFacadeFilter(module) }
apache-2.0
07b912f207baa01c7f8c9db025b228ff
51.702128
116
0.811389
4.981891
false
false
false
false
jwren/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/BooleanCommitOption.kt
2
2235
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui import com.intellij.ide.ui.UISettings import com.intellij.openapi.options.UnnamedConfigurable import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.checkin.CheckinHandlerUtil.disableWhenDumb import com.intellij.openapi.vcs.configurable.CommitOptionsConfigurable import com.intellij.openapi.vcs.ui.RefreshableOnComponent import com.intellij.ui.components.JBCheckBox import com.intellij.vcs.commit.isNonModalCommit import org.jetbrains.annotations.Nls import java.util.function.Consumer import javax.swing.JComponent import kotlin.reflect.KMutableProperty0 open class BooleanCommitOption( private val checkinPanel: CheckinProjectPanel, @Nls text: String, disableWhenDumb: Boolean, private val getter: () -> Boolean, private val setter: Consumer<Boolean> ) : RefreshableOnComponent, UnnamedConfigurable { constructor(panel: CheckinProjectPanel, @Nls text: String, disableWhenDumb: Boolean, property: KMutableProperty0<Boolean>) : this(panel, text, disableWhenDumb, { property.get() }, Consumer { property.set(it) }) protected val checkBox = JBCheckBox(text).apply { isFocusable = isInSettings || isInNonModalOptionsPopup || UISettings.shadowInstance.disableMnemonicsInControls if (disableWhenDumb && !isInSettings) disableWhenDumb(checkinPanel.project, this, VcsBundle.message("changes.impossible.until.indices.are.up.to.date")) } private val isInSettings get() = checkinPanel is CommitOptionsConfigurable.CheckinPanel private val isInNonModalOptionsPopup get() = checkinPanel.isNonModalCommit override fun saveState() { setter.accept(checkBox.isSelected) } override fun restoreState() { checkBox.isSelected = getter() } override fun getComponent(): JComponent = checkBox override fun createComponent() = component override fun isModified() = checkBox.isSelected != getter() override fun apply() = saveState() override fun reset() = restoreState() }
apache-2.0
e67e4083cdd52e6bb2573ee38259fe57
38.928571
140
0.773154
4.65625
false
true
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/internal/ui/GridLayoutTestAction.kt
1
15835
// 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.internal.ui import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.components.JBList import com.intellij.ui.components.JBTabbedPane import com.intellij.ui.dsl.gridLayout.* import com.intellij.ui.dsl.gridLayout.builders.RowsGridBuilder import java.awt.Color import java.awt.Component import java.awt.Dimension import javax.swing.* import javax.swing.border.Border import kotlin.random.Random class GridLayoutTestAction : DumbAwareAction("Show GridLayout Test") { override fun actionPerformed(e: AnActionEvent) { object : DialogWrapper(e.project, null, true, IdeModalityType.IDE, false) { init { title = "GridLayout Test" init() } override fun createContentPaneBorder(): Border? { return null } override fun createCenterPanel(): JComponent { val result = JBTabbedPane() result.minimumSize = Dimension(300, 200) result.preferredSize = Dimension(800, 600) result.addTab("TODO", createTodoPanel()) result.addTab( "NoResizableCells", createTabPanel("No resizable cells", createPanelLabels(3, 4) { _, _, _ -> null }) ) result.addTab("ResizableCell[1, 1]", createResizableCell11Panel()) result.addTab("CellAlignments", createCellAlignmentsPanel()) result.addTab("SubGrid", createSubGridPanel()) result.addTab("JointCells", createJointCellsPanel()) result.addTab("Gaps", createGapsPanel()) result.addTab("Col/row gaps", createColRowGapsPanel()) result.addTab("VisualPaddings", createVisualPaddingsPanel()) result.addTab("Baseline", createBaselinePanel()) return result } }.show() } fun createTodoPanel(): JPanel { val result = JPanel() val todo = listOf( "Implement cells which occupies all remaining columns", "Resize non resizable cells when there is no enough space", "Tests", "visualPaddings can depend on component size? E.g. checkBox", "SubGrids: visibility, visualPaddings" ) result.add( JLabel("<html>TODO list<br><br>&bull " + todo.joinToString("<br>&bull ")) ) return result } fun createBaselinePanel(): JPanel { fun RowsGridBuilder.label(verticalAlign: VerticalAlign, size: Int): RowsGridBuilder { val label = JLabel("${verticalAlign.name} $size") label.font = label.font.deriveFont(size.toFloat()) cell(label, verticalAlign = verticalAlign) return this } fun RowsGridBuilder.title(text: String): RowsGridBuilder { val label = JLabel(text) label.preferredSize = Dimension(150, 40) label.verticalAlignment = SwingConstants.TOP cell(label, verticalAlign = VerticalAlign.FILL) return this } val panel = JPanel(GridLayout()) val builder = RowsGridBuilder(panel) .defaultBaselineAlign(true) builder .title("Vertical align: TOP") .label(VerticalAlign.TOP, 14) .label(VerticalAlign.TOP, 10) .label(VerticalAlign.TOP, 16) .row() .title("Vertical align: CENTER") .label(VerticalAlign.CENTER, 12) .label(VerticalAlign.CENTER, 14) .label(VerticalAlign.CENTER, 16) .row() .title("Vertical align: BOTTOM") .label(VerticalAlign.BOTTOM, 12) .label(VerticalAlign.BOTTOM, 10) .label(VerticalAlign.BOTTOM, 16) .row() .title("Vertical align: mixed") .label(VerticalAlign.TOP, 12) .label(VerticalAlign.CENTER, 10) .label(VerticalAlign.BOTTOM, 14) .label(VerticalAlign.CENTER, 16) .label(VerticalAlign.TOP, 14) .label(VerticalAlign.BOTTOM, 10) .row() builder .subGridBuilder(width = 7) .title("sub-panels") .label(VerticalAlign.CENTER, 14) .subGridBuilder(verticalAlign = VerticalAlign.CENTER) .label(VerticalAlign.CENTER, 12) .subGridBuilder(verticalAlign = VerticalAlign.CENTER) .label(VerticalAlign.CENTER, 16) .label(VerticalAlign.CENTER, 10) return createTabPanel("Labels are aligned by baseline", panel) } fun createVisualPaddingsPanel(): JPanel { val layoutManager = GridLayout() val rootGrid = layoutManager.rootGrid rootGrid.resizableColumns.add(1) rootGrid.resizableRows.add(2) val panel = JPanel(layoutManager) fillGridByLabels(panel, rootGrid, 3, 4) { grid, x, y -> if (x == 0 && y == 1) { Constraints(grid, x, y, visualPaddings = Gaps(10, 10, 10, 10)) } else if (x == 1 && y == 2) { Constraints( grid, x, y, horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL, visualPaddings = Gaps(10, 10, 10, 10) ) } else { null } } return createTabPanel("Every second cell has own Gaps", panel) } fun createGapsPanel(): JPanel { val panel = createPanelLabels(4, 4) { grid, x, y -> Constraints( grid, x, y, horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL, gaps = if ((x + y) % 2 == 0) Gaps.EMPTY else Gaps(y * 20, x * 20, y * 30, x * 30) ) } val grid = (panel.layout as GridLayout).rootGrid grid.resizableColumns.addAll(0..HorizontalAlign.values().size) grid.resizableRows.addAll(0..VerticalAlign.values().size) return createTabPanel("Every second cell has own Gaps", panel) } fun createColRowGapsPanel(): JPanel { val layoutManager = GridLayout() val grid = layoutManager.rootGrid grid.resizableColumns.addAll(0..4) grid.resizableRows.addAll(0..3) grid.columnsGaps.addAll((0..4).map { HorizontalGaps(it * 20, it * 20 + 10) }) grid.rowsGaps.addAll((0..3).map { VerticalGaps(it * 5 + 5, it * 5 + 15) }) val panel = JPanel(layoutManager) fillGridByCompoundLabels(panel, grid) return createTabPanel("Different distances between columns/rows", panel) } fun createJointCellsPanel(): JPanel { val layoutManager = GridLayout() val grid = layoutManager.rootGrid grid.resizableColumns.add(1) grid.resizableRows.add(1) val panel = JPanel(layoutManager) fun addLabel(x: Int, y: Int, width: Int = 1, height: Int = 1) { panel.addLabel( Constraints( grid, x, y, width = width, height = height, horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL ) ) } addLabel(0, 0, height = 2) addLabel(1, 0, width = 3) addLabel(4, 0, height = 3) addLabel(1, 1) val constraints = Constraints( grid, 2, 1, width = 2, height = 2, horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL ) panel.add( JLabel( "<html>HighLabel<br>Label<br>Label<br>Label<br>Label<br>Label<br>Label<br>${ constraintsToHtmlString( constraints ) }" ), constraints ) addLabel(0, 2, width = 2, height = 2) addLabel(2, 3, width = 3) return createTabPanel("Cells have different shapes", panel) } fun createCellAlignmentsPanel(): JPanel { val panel = createPanelLabels(HorizontalAlign.values().size, VerticalAlign.values().size) { grid, x, y -> Constraints( grid, x, y, horizontalAlign = HorizontalAlign.values()[x], verticalAlign = VerticalAlign.values()[y] ) } val grid = (panel.layout as GridLayout).rootGrid grid.resizableColumns.addAll(0..HorizontalAlign.values().size) grid.resizableRows.addAll(0..VerticalAlign.values().size) return createTabPanel("Cells size is equal, component layouts have different alignments", panel) } fun createResizableCell11Panel(): JPanel { val panel = createPanelLabels(3, 4) { grid, x, y -> if (x == 1 && y == 1) Constraints(grid, x, y, horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL) else null } val grid = (panel.layout as GridLayout).rootGrid grid.resizableColumns.add(1) grid.resizableRows.add(1) return createTabPanel("One column and row are resizable", panel) } fun createSubGridPanel(): JPanel { val layoutManager = GridLayout() layoutManager.rootGrid.resizableColumns.add(1) layoutManager.rootGrid.resizableRows.add(1) val panel = JPanel(layoutManager) val subGrid = layoutManager.addLayoutSubGrid( Constraints( layoutManager.rootGrid, 1, 1, horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL ) ) subGrid.resizableColumns.add(1) subGrid.resizableRows.add(1) fillGridByLabels(panel, subGrid, 3, 3) { grid, x, y -> if (x == 1 && y == 1) Constraints(grid, x, y, horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL) else null } RowsGridBuilder(panel) .cell(label(0, 0)) .cell(label(1, 0)) .cell(label(2, 0)) .row() .cell(label(0, 1)) .skip() .cell(label(2, 1)) .row() .cell(label(0, 2)) .cell(label(1, 2)) .cell(label(2, 2)) return createTabPanel("cell[1, 1] contains another grid inside", panel) } fun createPanelLabels( width: Int, height: Int, constraintFactory: (grid: Grid, x: Int, y: Int) -> Constraints? ): JPanel { val layoutManager = GridLayout() val result = JPanel(layoutManager) fillGridByLabels(result, layoutManager.rootGrid, width, height, constraintFactory) return result } fun fillGridByLabels( container: JComponent, grid: Grid, width: Int, height: Int, constraintFactory: (grid: Grid, x: Int, y: Int) -> Constraints? ) { for (x in 0 until width) { for (y in 0 until height) { val constraints = constraintFactory.invoke(grid, x, y) ?: Constraints(grid, x, y) container.addLabel(constraints, longLabel = x == y) } } } fun fillGridByCompoundLabels( container: JComponent, grid: Grid ) { fun addLabel(x: Int, y: Int, width: Int = 1, height: Int = 1) { container.addLabel( Constraints( grid, x, y, width = width, height = height, horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL ) ) } addLabel(0, 0, height = 2) addLabel(1, 0, width = 3) addLabel(4, 0, height = 3) addLabel(1, 1) val constraints = Constraints( grid, 2, 1, width = 2, height = 2, horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL ) container.add( JLabel( "<html>HighLabel<br>Label<br>Label<br>Label<br>Label<br>Label<br>Label<br>${ constraintsToHtmlString( constraints ) }" ), constraints ) addLabel(0, 2, width = 2, height = 2) addLabel(2, 3, width = 3) } fun label(constraints: Constraints, longLabel: Boolean = false): JLabel { val text = if (longLabel) "Very very very very very long label" else "Label" return JLabel("<html>$text<br>${constraintsToHtmlString(constraints)}") } fun constraintsToHtmlString(constraints: Constraints): String { var result = "x = ${constraints.x}, y = ${constraints.y}<br>" + "width = ${constraints.width}, height = ${constraints.height}<br>" + "hAlign = ${constraints.horizontalAlign}, vAlign = ${constraints.verticalAlign}<br>" if (constraints.gaps != Gaps.EMPTY) { result += "gaps = ${constraints.gaps}<br>" } if (constraints.visualPaddings != Gaps.EMPTY) { result += "visualPaddings = ${constraints.visualPaddings}<br>" } return result } fun gridToHtmlString(grid: Grid): String { val result = mutableListOf<String>() if (grid.resizableColumns.isNotEmpty()) { result.add("resizableColumns = ${grid.resizableColumns.joinToString()}") } if (grid.resizableRows.isNotEmpty()) { result.add("resizableRows = ${grid.resizableRows.joinToString()}") } if (grid.columnsGaps.isNotEmpty()) { result.add("<br>columnsGaps = ${grid.columnsGaps.joinToString()}") } if (grid.rowsGaps.isNotEmpty()) { result.add("<br>rowsGaps = ${grid.rowsGaps.joinToString()}") } return result.joinToString() } fun label(x: Int, y: Int, longLabel: Boolean = false): JLabel { val text = if (longLabel) "Very very very very very long label" else "Label" return JLabel("$text [x = $x, y = $y]") } fun JComponent.addLabel(constraints: Constraints, longLabel: Boolean = false) { val label = label(constraints, longLabel) add(label, constraints) } fun createTabPanel(title: String, content: JComponent): JPanel { val layoutManager = GridLayout() val rootGrid = layoutManager.rootGrid val result = JPanel(layoutManager) rootGrid.resizableColumns.add(0) rootGrid.resizableRows.add(1) val label = JLabel("<html>$title<br>${gridToHtmlString((content.layout as GridLayout).rootGrid)}") label.background = Color.LIGHT_GRAY label.isOpaque = true result.add(label, Constraints(rootGrid, 0, 0, width = 2, horizontalAlign = HorizontalAlign.FILL)) result.add( content, Constraints( rootGrid, 0, 1, verticalAlign = VerticalAlign.FILL, horizontalAlign = HorizontalAlign.FILL ) ) val controlGrid = layoutManager.addLayoutSubGrid( Constraints( rootGrid, 1, 1, verticalAlign = VerticalAlign.FILL ) ) createControls(result, content, controlGrid) return result } fun createControls(container: JComponent, content: JComponent, grid: Grid) { val cbHighlight = JCheckBox("Highlight components") cbHighlight.addActionListener { for (component in content.components) { if (component is JLabel) { component.background = if (cbHighlight.isSelected) Color(Random.nextInt()) else null component.isOpaque = cbHighlight.isSelected } } } cbHighlight.doClick() val list = JBList(content.components.filterIsInstance<JLabel>()) val btnHide = JButton("Hide") val btnShow = JButton("Show") list.cellRenderer = object : DefaultListCellRenderer() { override fun getListCellRendererComponent( list: JList<*>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean ): Component { val label = value as JLabel val result = super.getListCellRendererComponent( list, label.text, index, isSelected, cellHasFocus ) as DefaultListCellRenderer result.foreground = if (label.isVisible) Color.BLACK else Color.LIGHT_GRAY return result } } btnHide.addActionListener { list.selectedValuesList.forEach { it.isVisible = false } list.updateUI() } btnShow.addActionListener { list.selectedValuesList.forEach { it.isVisible = true } list.updateUI() } grid.resizableColumns.addAll(0..1) grid.resizableRows.add(0) container.add( JScrollPane(list), Constraints( grid, 0, 0, width = 2, horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL ) ) container.add(btnHide, Constraints(grid, 0, 1, horizontalAlign = HorizontalAlign.CENTER)) container.add(btnShow, Constraints(grid, 1, 1, horizontalAlign = HorizontalAlign.CENTER)) container.add(cbHighlight, Constraints(grid, 0, 2, width = 2)) } }
apache-2.0
cea13bc6ba8a3ae945147b73f3616c16
31.582305
158
0.645153
4.152898
false
false
false
false
7449/Album
compat/src/main/java/com/gallery/compat/Gallery.kt
1
2046
package com.gallery.compat import android.content.Intent import android.os.Parcelable import androidx.activity.result.ActivityResultLauncher import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import com.gallery.compat.activity.args.GalleryCompatArgs import com.gallery.compat.activity.args.GalleryCompatArgs.Companion.putArgs import com.gallery.core.GalleryBundle open class Gallery( activity: FragmentActivity? = null, fragment: Fragment? = null, private val launcher: ActivityResultLauncher<Intent>, private val args: GalleryCompatArgs, private val clz: Class<*>, ) { companion object { fun newInstance( activity: FragmentActivity? = null, fragment: Fragment? = null, launcher: ActivityResultLauncher<Intent>, bundle: GalleryBundle = GalleryBundle(), customBundle: Parcelable? = null, clz: Class<*>, ): Gallery { return Gallery( activity, fragment, launcher, GalleryCompatArgs(bundle, customBundle), clz ) } } private val fragmentActivity: FragmentActivity init { when { fragment != null -> { fragmentActivity = fragment.requireActivity() startFragment() } activity != null -> { fragmentActivity = activity startActivity() } else -> throw KotlinNullPointerException("fragment and activity == null") } } private fun launchIntent(): Intent { return Intent(fragmentActivity, clz).apply { putExtras(args.putArgs()) } } private fun startActivity() { launcher.launch(launchIntent()) } private fun startFragment() { launcher.launch(launchIntent()) } }
mpl-2.0
1e2af227830bfb734e53b0860263c117
28.567164
85
0.572825
5.636364
false
false
false
false
aosp-mirror/platform_frameworks_support
jetifier/jetifier/core/src/test/kotlin/com/android/tools/build/jetifier/core/type/TypesMapTest.kt
1
2128
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.build.jetifier.core.type import com.google.common.truth.Truth import org.junit.Test class TypesMapTest { @Test fun typesMap_mapSimpleType() { testRewrites( map = listOf( "test.Class" to "test2.Class2" ), from = "test.Class", expected = "test2.Class2" ) } @Test fun typesMap_mapNestedType() { testRewrites( map = listOf( "test.Class" to "test2.Class2" ), from = "test.Class\$Inner", expected = "test2.Class2\$Inner" ) } @Test fun typesMap_mapDoubleNestedType() { testRewrites( map = listOf( "test.Class" to "test2.Class2" ), from = "test.Class\$Inner\$1", expected = "test2.Class2\$Inner\$1" ) } @Test fun typesMap_mapNotFound_returnsNull() { val typesMap = TypesMap.EMPTY val result = typesMap.mapType(JavaType.fromDotVersion("test.Class")) Truth.assertThat(result).isNull() } private fun testRewrites(map: List<Pair<String, String>>, from: String, expected: String) { val typesMap = TypesMap(map .map { JavaType.fromDotVersion(it.first) to JavaType.fromDotVersion(it.second) } .toMap()) val result = typesMap.mapType(JavaType.fromDotVersion(from)) Truth.assertThat(result).isEqualTo(JavaType.fromDotVersion(expected)) } }
apache-2.0
f6e94fa90bc8e3b8fdf6ab12df0d9e22
30.776119
95
0.617951
4.108108
false
true
false
false
fossasia/rp15
app/src/test/java/org/fossasia/openevent/general/AppLinkUtilsTest.kt
1
1283
package org.fossasia.openevent.general import org.fossasia.openevent.general.utils.EVENT_IDENTIFIER import org.fossasia.openevent.general.utils.RESET_PASSWORD_TOKEN import org.fossasia.openevent.general.utils.AppLinkUtils import org.fossasia.openevent.general.utils.VERIFICATION_TOKEN import org.fossasia.openevent.general.utils.AppLinkData import org.junit.Test import org.junit.Assert.assertEquals class AppLinkUtilsTest { @Test fun `should get event link`() { val uri = "https://eventyay.com/e/5f6d3feb" assertEquals(AppLinkData(R.id.eventDetailsFragment, EVENT_IDENTIFIER, "5f6d3feb"), AppLinkUtils.getData(uri)) } @Test fun `should get reset password link`() { val uri = "https://eventyay.com/reset-password?token=822980340478781748445098077144" assertEquals(AppLinkData(R.id.eventsFragment, RESET_PASSWORD_TOKEN, "822980340478781748445098077144"), AppLinkUtils.getData(uri)) } @Test fun `should get verify email link`() { val uri = "https://eventyay.com/verify?token=WyJsaXZlLmhhcnNoaXRAaG" assertEquals(AppLinkData(R.id.profileFragment, VERIFICATION_TOKEN, "WyJsaXZlLmhhcnNoaXRAaG"), AppLinkUtils.getData(uri)) } }
apache-2.0
243d3f91237e7e6c039324c26482b468
34.638889
92
0.713952
3.603933
false
true
false
false
Nicologies/Hedwig
hedwig-server/src/main/java/com/nicologis/teamcity/ParameterNames.kt
2
356
package com.nicologis.teamcity object ParameterNames { val SlackWebHookURL = "system.hedwig.slack.webhook_url" val SlackBotName = "system.hedwig.slack.bot_name" val HipChatToken = "system.hedwig.hipchat.token" val ExcludeMessage = "system.hedwig.exclude_message" val NotifyParticipants = "system.hedwig.notify_participants" }
mit
66820d9dcc0badc8f08988dd2cd3ed2d
37.555556
64
0.741573
3.490196
false
false
false
false
seventhroot/elysium
bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/database/table/RPKCharacterProfessionChangeCooldownTable.kt
1
8156
/* * Copyright 2019 Ren Binden * * 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.rpkit.professions.bukkit.database.table import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.professions.bukkit.RPKProfessionsBukkit import com.rpkit.professions.bukkit.database.jooq.rpkit.Tables.RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN import com.rpkit.professions.bukkit.profession.RPKCharacterProfessionChangeCooldown import org.ehcache.config.builders.CacheConfigurationBuilder import org.ehcache.config.builders.ResourcePoolsBuilder import org.jooq.impl.DSL.constraint import org.jooq.impl.SQLDataType import java.sql.Timestamp class RPKCharacterProfessionChangeCooldownTable( database: Database, val plugin: RPKProfessionsBukkit ): Table<RPKCharacterProfessionChangeCooldown>( database, RPKCharacterProfessionChangeCooldown::class ) { private val cache = if (plugin.config.getBoolean("caching.rpkit_character_profession_change_cooldown.id.enabled")) { database.cacheManager.createCache("rpk-professions-bukkit.rpkit_character_profession_change_cooldown.id", CacheConfigurationBuilder .newCacheConfigurationBuilder(Int::class.javaObjectType, RPKCharacterProfessionChangeCooldown::class.java, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_character_profession_change_cooldown.id.size"))).build()) } else { null } private val characterCache = if (plugin.config.getBoolean("caching.rpkit_character_profession_change_cooldown.character_id.enabled")) { database.cacheManager.createCache("rpk-professions-bukkit.rpkit_character_profession_change_cooldown.character_id", CacheConfigurationBuilder .newCacheConfigurationBuilder(Int::class.javaObjectType, RPKCharacterProfessionChangeCooldown::class.java, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_character_profession_change_cooldown.character_id.size"))).build()) } else { null } override fun create() { database.create .createTableIfNotExists(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN) .column(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.ID, SQLDataType.INTEGER.identity(true)) .column(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.CHARACTER_ID, SQLDataType.INTEGER) .column(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.COOLDOWN_END_TIME, SQLDataType.TIMESTAMP) .constraints( constraint("pk_rpkit_character_profession_change_cooldown").primaryKey(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.ID) ) .execute() } override fun applyMigrations() { if (database.getTableVersion(this) == null) { database.setTableVersion(this, "1.7.0") } } override fun insert(entity: RPKCharacterProfessionChangeCooldown): Int { database.create .insertInto( RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN, RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.CHARACTER_ID, RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.COOLDOWN_END_TIME ) .values( entity.character.id, Timestamp.valueOf(entity.cooldownEndTime) ) .execute() val id = database.create.lastID().toInt() entity.id = id cache?.put(id, entity) characterCache?.put(entity.character.id, entity) return id } override fun update(entity: RPKCharacterProfessionChangeCooldown) { database.create .update(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN) .set(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.CHARACTER_ID, entity.character.id) .set(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.COOLDOWN_END_TIME, Timestamp.valueOf(entity.cooldownEndTime)) .where(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.ID.eq(entity.id)) .execute() cache?.put(entity.id, entity) characterCache?.put(entity.character.id, entity) } override fun get(id: Int): RPKCharacterProfessionChangeCooldown? { if (cache?.containsKey(id) == true) { return cache[id] } val result = database.create .select( RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.CHARACTER_ID, RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.COOLDOWN_END_TIME ) .from(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN) .where(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.ID.eq(id)) .fetchOne() ?: return null val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val character = characterProvider.getCharacter(result[RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.CHARACTER_ID]) if (character == null) { database.create .deleteFrom(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN) .where(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.ID.eq(id)) .execute() cache?.remove(id) characterCache?.remove(result[RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.CHARACTER_ID]) return null } val characterProfessionChangeCooldown = RPKCharacterProfessionChangeCooldown( id, character, result[RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.COOLDOWN_END_TIME].toLocalDateTime() ) cache?.put(id, characterProfessionChangeCooldown) characterCache?.put(characterProfessionChangeCooldown.character.id, characterProfessionChangeCooldown) return characterProfessionChangeCooldown } fun get(character: RPKCharacter): RPKCharacterProfessionChangeCooldown? { if (characterCache?.containsKey(character.id) == true) { return characterCache[character.id] } val result = database.create .select( RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.ID, RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.COOLDOWN_END_TIME ) .from(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN) .where(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.CHARACTER_ID.eq(character.id)) .fetchOne() ?: return null val characterProfessionChangeCooldown = RPKCharacterProfessionChangeCooldown( result[RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.ID], character, result[RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.COOLDOWN_END_TIME].toLocalDateTime() ) cache?.put(result[RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.ID], characterProfessionChangeCooldown) characterCache?.put(character.id, characterProfessionChangeCooldown) return characterProfessionChangeCooldown } override fun delete(entity: RPKCharacterProfessionChangeCooldown) { database.create .deleteFrom(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN) .where(RPKIT_CHARACTER_PROFESSION_CHANGE_COOLDOWN.ID.eq(entity.id)) .execute() cache?.remove(entity.id) characterCache?.remove(entity.character.id) } }
apache-2.0
59d86b9b05c0b97af56f4a0e14a4b4b2
47.547619
154
0.67668
4.634091
false
true
false
false
google/audio-to-tactile
extras/android/java/com/google/audio_to_tactile/TimeSeriesPlot.kt
1
4119
/* Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.audio_to_tactile import android.animation.TimeAnimator import android.graphics.Canvas import android.graphics.ColorFilter import android.graphics.Paint import android.graphics.PixelFormat import android.graphics.drawable.Drawable import androidx.annotation.ColorInt /** * Animated Drawable that plots a scrolling time series. Timestamps are UTC milliseconds from the * epoch as returned by `System.currentTimeMillis()`. */ class TimeSeriesPlot( val timeSeries: TimeSeries, var currentTimeMs: Long, @ColorInt lineColor: Int, @ColorInt bgColor: Int, @ColorInt gridColor: Int ) : Drawable(), TimeAnimator.TimeListener { /** Paint object for drawing the plot line, having color `lineColor`. */ private val linePaint = Paint().apply { color = lineColor strokeWidth = 5f isAntiAlias = true } /** Paint for filling the plot box background. */ private val bgPaint = Paint().apply { color = bgColor style = Paint.Style.FILL } /** Paint for drawing vertical grid lines. */ private val gridPaint = Paint().apply { color = gridColor strokeWidth = 3f isAntiAlias = true } /** Number of grid lines to draw, which are spaced one second apart. */ private val numGridLines = 1 + timeSeries.windowDurationMs / 1000 init { TimeAnimator().apply { setTimeListener(this@TimeSeriesPlot) start() } } /** On every frame, update `currentTime` to scroll the plot and call `invalidateSelf()`. */ override fun onTimeUpdate(animation: TimeAnimator?, totalTimeMs: Long, deltaTimeMs: Long) { currentTimeMs += deltaTimeMs // The time series data is generated on the wearable, which does not have an accurate clock. // timeSeries makes timing adjustments to force the data to be spaced with a presumed sample // period, and consequently, there can be clock drift where timeSeries is ahead of real time. // // We account for this by adding a couple milliseconds per frame as needed to make gradual // corrections. ADJUST_MS the adjustment increment, which should be small enough to avoid // visually obvious jumps but large enough to make timing corrections. Supposing 60 frames per // second, adding 2 ms per frame can correct up to 120 ms per second, which is more than enough. val ADJUST_MS = 2L if (timeSeries.currentTimeMs - currentTimeMs >= ADJUST_MS) { currentTimeMs += ADJUST_MS } invalidateSelf() // Indicate that plot needs to be redrawn. } /** Draws the plot. */ override fun draw(canvas: Canvas) { val width = bounds.width().toFloat() val height = bounds.height().toFloat() val timeLeftEdgeMs = currentTimeMs - timeSeries.windowDurationMs val xScale = width / timeSeries.windowDurationMs val yScale = height val lines = timeSeries.getLines { point -> val x = xScale * (point.timeMs - timeLeftEdgeMs).toFloat() val y = yScale * (1.0f - point.value) Pair(x, y) } // Fill plot background rectangle. canvas.drawRect(0f, 0f, width, height, bgPaint) // Draw grid lines spaced one second apart. val phase = 1000 - timeLeftEdgeMs % 1000 for (i in 0 until numGridLines) { val x = xScale * (phase + i * 1000).toFloat() canvas.drawLine(x, 0f, x, height, gridPaint) } // Plot the time series data. canvas.drawLines(lines, linePaint) } override fun setAlpha(alpha: Int) {} override fun setColorFilter(colorFilter: ColorFilter?) {} override fun getOpacity(): Int = PixelFormat.OPAQUE }
apache-2.0
93d9aeadb00dd17ca9e235fde84fe719
35.776786
100
0.710367
4.228953
false
false
false
false
DR-YangLong/spring-boot-kotlin-demo
src/main/kotlin/site/yanglong/promotion/service/impl/ResourcesServiceImpl.kt
1
3892
package site.yanglong.promotion.service.impl import com.baomidou.mybatisplus.service.impl.ServiceImpl import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.springframework.util.CollectionUtils import site.yanglong.promotion.config.shiro.authentication.ShiroRealm import site.yanglong.promotion.mapper.ResourcesMapper import site.yanglong.promotion.model.Resources import site.yanglong.promotion.model.dto.UriPermissions import site.yanglong.promotion.service.ResourcesService /** * * * 服务实现类 * * * @author Dr.YangLong * @since 2017-11-01 */ @Service class ResourcesServiceImpl : ServiceImpl<ResourcesMapper, Resources>(), ResourcesService { @Autowired val shiroRealm: ShiroRealm? = null override fun listDefinitions(): List<UriPermissions> { //return baseMapper.selectDefinitions() val roles = baseMapper.selectRoles() val perms = baseMapper.selectPerms() if (roles.isEmpty()) { return perms } if (perms.isEmpty()) { return roles } val roleMap = HashMap<Long?, UriPermissions>(roles.size) val permMap = HashMap<Long?, UriPermissions>(perms.size) roles.forEach { k -> roleMap.put(k.id, k) } perms.forEach { k -> permMap.put(k.id, k) } if (roles.size <= perms.size) { roleMap.forEach { t, u -> //向大的map汇总 val k = permMap[t] if (k != null) { k.roles = u.roles } else { permMap.put(t, u) } } } else { permMap.forEach { t, u -> val k = roleMap[t] if (k != null) { k.perms = u.perms } else { roleMap.put(t, u) } } } if (roleMap.size <= permMap.size) { val definitions = ArrayList<UriPermissions>(perms.size) permMap.forEach { _, u -> definitions.add(u) } return definitions } val definitions = ArrayList<UriPermissions>(roles.size) roleMap.forEach { _, u -> definitions.add(u) } return definitions } override fun definitionsMap(): LinkedHashMap<String, String>? { val definitions = listDefinitions() if (definitions.isNotEmpty()) { val map = LinkedHashMap<String, String>(definitions.size) for (i in definitions.indices) { val d = definitions[i] val build = StringBuilder() if (!CollectionUtils.isEmpty(d.roles)) { val roles = d.roles build.append(shiroRealm?.roles_in_map_key).append("[") for (k in roles!!.indices) { if (k == 0) { build.append(roles[k]) } else { build.append(",").append(roles[k]) } } build.append("]") } if (!CollectionUtils.isEmpty(d.perms)) { val perms = d.perms if(build.isNotEmpty())build.append(",") build.append(shiroRealm?.perms_in_map_key).append("[") for (k in perms!!.indices) { if (i == 0) { build.append(perms[k]) } else { build.append(",").append(perms[k]) } } build.append("]") } val uri = d.uri if (uri != null) map.put(uri, build.toString()) } return map } return null } }
apache-2.0
2b6269ba712c6a3906ca68160d662e7c
34.2
90
0.502324
4.648259
false
false
false
false
eurofurence/ef-app_android
app/src/main/kotlin/org/eurofurence/connavigator/ui/fragments/DealerListFragment.kt
1
7763
@file:Suppress("MemberVisibilityCanBePrivate") package org.eurofurence.connavigator.ui.fragments import android.os.Bundle import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.firebase.perf.metrics.AddTrace import com.pawegio.kandroid.runDelayed import com.pawegio.kandroid.textWatcher import io.swagger.client.model.DealerRecord import org.eurofurence.connavigator.R import org.eurofurence.connavigator.database.HasDb import org.eurofurence.connavigator.database.lazyLocateDb import org.eurofurence.connavigator.ui.adapter.DealerRecyclerAdapter import org.eurofurence.connavigator.util.extensions.recycler import org.eurofurence.connavigator.util.extensions.setFAIcon import org.jetbrains.anko.* import org.jetbrains.anko.support.v4.UI import org.jetbrains.anko.support.v4.act /** * Created by David on 15-5-2016. */ class DealerListFragment : Fragment(), HasDb, AnkoLogger { override val db by lazyLocateDb() val ui by lazy { DealersUi() } val layoutManager get() = ui.dealerList?.layoutManager private var effectiveDealers = emptyList<DealerRecord>() var searchText = "" var searchCategory = "" override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = UI { ui.createView(this) }.view override fun onViewCreated(view: View, savedInstanceState: Bundle?) { effectiveDealers = sortDealers(dealers.items) info { "Rendering ${effectiveDealers.size} dealers out of ${db.dealers.items.size}" } ui.dealerList?.adapter = DealerRecyclerAdapter(effectiveDealers, db, this) ui.dealerList?.layoutManager = LinearLayoutManager(activity) ui.dealerList?.itemAnimator = DefaultItemAnimator() val distinctCategories = dealers.items .map { it.categories ?: emptyList() } .fold(emptyList<String>()) { a, b -> a.plus(b).distinct() } .sorted() ui.categorySpinner.adapter = ArrayAdapter<String>(this.act, android.R.layout.simple_spinner_dropdown_item, listOf("All Categories").plus(distinctCategories)) ui.categorySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { } override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { searchCategory = if (position == 0) { "" } else { parent.getItemAtPosition(position) as String } updateFilter() } } ui.search.textWatcher { afterTextChanged { text -> searchText = text.toString(); updateFilter() } } } override fun onResume() { super.onResume() activity?.apply { this.findViewById<Toolbar>(R.id.toolbar).apply { this.menu.clear() this.inflateMenu(R.menu.dealer_list_menu) this.context?.let { this.menu.setFAIcon(it, R.id.action_search, R.string.fa_search_solid, white = true) } this.setOnMenuItemClickListener { when (it.itemId) { R.id.action_search -> onSearchButtonClick() } true } } } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) layoutManager?.also { lm -> outState.putParcelable("lm_key", lm.onSaveInstanceState()) } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) layoutManager?.also { lm -> runDelayed(200) { savedInstanceState ?.getParcelable<Parcelable>("lm_key") ?.let(lm::onRestoreInstanceState) } } } override fun onPause() { super.onPause() activity?.apply { this.findViewById<Toolbar>(R.id.toolbar).menu.clear() } } override fun onDestroy() { super.onDestroy() activity?.apply { this.findViewById<Toolbar>(R.id.toolbar).menu.clear() } } @AddTrace(name = "DealerListFragment:search", enabled = true) fun updateFilter() { info { "Filtering dealers for text=$searchText, category=$searchCategory" } effectiveDealers = db.dealers.items.toList() if (!searchText.isEmpty()) effectiveDealers = effectiveDealers.filter { it.displayName.contains(searchText, true) or it.attendeeNickname.contains(searchText, true) } if (!searchCategory.isEmpty()) effectiveDealers = effectiveDealers.filter { it.categories?.contains(searchCategory) ?: false } ui.dealerList?.adapter = DealerRecyclerAdapter(sortDealers(effectiveDealers), db, this).also { it.notifyDataSetChanged() } } private fun sortDealers(dealers: Iterable<DealerRecord>): List<DealerRecord> = dealers.sortedBy { (if (it.displayName != "") it.displayName else it.attendeeNickname).toLowerCase() } fun onSearchButtonClick() { if (ui.searchLayout.visibility == View.GONE) { info { "Showing search bar" } ui.searchLayout.visibility = View.VISIBLE ui.search.requestFocus() } else { info { "Hiding search bar" } ui.searchLayout.visibility = View.GONE searchText = "" updateFilter() } } } class DealersUi : AnkoComponent<Fragment> { var dealerList: RecyclerView? = null lateinit var search: EditText lateinit var searchLayout: LinearLayout lateinit var categorySpinner: Spinner override fun createView(ui: AnkoContext<Fragment>) = with(ui) { verticalLayout { lparams(matchParent, matchParent) backgroundResource = R.color.backgroundGrey verticalLayout { // Search widgets padding = dip(10) linearLayout { // Filter types weightSum = 100F textView { textResource = R.string.misc_show leftPadding = dip(5) }.lparams(dip(0), wrapContent, 20F) categorySpinner = spinner { prompt = resources.getString(R.string.misc_filter) }.lparams(dip(0), wrapContent, 80F) } searchLayout = linearLayout { weightSum = 100F visibility = View.GONE textView { textResource = R.string.misc_find leftPadding = dip(5) }.lparams(dip(0), wrapContent, 20F) search = editText { singleLine = true }.lparams(dip(0), wrapContent, 80F) } } dealerList = recycler { lparams(matchParent, matchParent) verticalPadding = dip(10) clipToPadding = false backgroundResource = R.color.lightBackground } } } }
mit
f93b0f0b398a334b65743a046e17b607
33.816143
150
0.602989
4.900884
false
false
false
false