repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
androidx/androidx
compose/foundation/foundation/samples/src/main/java/androidx/compose/foundation/samples/SnapFlingBehaviorSample.kt
3
3289
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.samples import androidx.annotation.Sampled import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.gestures.snapping.SnapLayoutInfoProvider import androidx.compose.foundation.gestures.snapping.rememberSnapFlingBehavior import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @OptIn(ExperimentalFoundationApi::class) @Sampled @Composable fun SnapFlingBehaviorSimpleSample() { val state = rememberLazyListState() LazyRow( modifier = Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically, state = state, flingBehavior = rememberSnapFlingBehavior(lazyListState = state) ) { items(200) { Box( modifier = Modifier .height(400.dp) .width(200.dp) .padding(8.dp) .background(Color.Gray), contentAlignment = Alignment.Center ) { Text(it.toString(), fontSize = 32.sp) } } } } @OptIn(ExperimentalFoundationApi::class) @Sampled @Composable fun SnapFlingBehaviorCustomizedSample() { val state = rememberLazyListState() // If you'd like to customize either the snap behavior or the layout provider val snappingLayout = remember(state) { SnapLayoutInfoProvider(state) } val flingBehavior = rememberSnapFlingBehavior(snappingLayout) LazyRow( modifier = Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically, state = state, flingBehavior = flingBehavior ) { items(200) { Box( modifier = Modifier .height(400.dp) .width(200.dp) .padding(8.dp) .background(Color.Gray), contentAlignment = Alignment.Center ) { Text(it.toString(), fontSize = 32.sp) } } } }
apache-2.0
4eeda581fb7b629d6117358a86687b8c
33.270833
81
0.689571
4.894345
false
false
false
false
DemonWav/StatCraft
src/main/kotlin/com/demonwav/statcraft/listeners/ToolsBrokenListener.kt
1
1188
/* * StatCraft Bukkit Plugin * * Copyright (c) 2016 Kyle Wood (DemonWav) * https://www.demonwav.com * * MIT License */ package com.demonwav.statcraft.listeners import com.demonwav.statcraft.StatCraft import com.demonwav.statcraft.querydsl.QToolsBroken import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.Listener import org.bukkit.event.player.PlayerItemBreakEvent class ToolsBrokenListener(private val plugin: StatCraft) : Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) fun onToolBreak(event: PlayerItemBreakEvent) { val uuid = event.player.uniqueId val worldName = event.player.world.name val item = event.brokenItem.type.id.toShort() plugin.threadManager.schedule<QToolsBroken>( uuid, worldName, { t, clause, id, worldId -> clause.columns(t.id, t.worldId, t.item, t.amount).values(id, worldId, item, 1).execute() }, { t, clause, id, worldId -> clause.where(t.id.eq(id), t.worldId.eq(worldId), t.item.eq(item)).set(t.amount, t.amount.add(1)).execute() } ) } }
mit
5d8a99315ee025ec72b6238f001336c5
32.942857
122
0.677609
3.84466
false
false
false
false
google/android-auto-companion-android
trustagent/tests/unit/src/com/google/android/libraries/car/trustagent/blemessagestream/FakeBluetoothConnectionManager.kt
1
3112
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.car.trustagent.blemessagestream import android.bluetooth.BluetoothDevice import java.util.concurrent.CopyOnWriteArrayList import org.robolectric.shadow.api.Shadow /** A fake implementation. */ // Open to be spied on by tests. open class FakeBluetoothConnectionManager() : BluetoothConnectionManager() { public override val connectionCallbacks = CopyOnWriteArrayList<ConnectionCallback>() public override val messageCallbacks = CopyOnWriteArrayList<MessageCallback>() override val maxWriteSize: Int = 512 override val bluetoothDevice: BluetoothDevice = Shadow.newInstanceOf(BluetoothDevice::class.java) override val deviceName: String? = "FakeBluetoothConnectionManager" /** Stores messages by [sendMessage]. */ val sentMessages = mutableListOf<ByteArray>() /** * Determines the callback of [connect]. * * Invokes [ConnectionCallback.onConnected] if this is true; * [ConnectionCallback.onConnectionFailed] otherwise. */ var isConnectionSuccessful: Boolean = true /** * Connects to remote device. * * Makes connection callback depending on [isConnectionSuccessful]. */ override fun connect() { for (callback in connectionCallbacks) { if (isConnectionSuccessful) { callback.onConnected() } else { callback.onConnectionFailed() } } } /** * Connects to remote device. * * Always succeeds. */ override suspend fun connectToDevice(): Boolean = true /** No-op. */ override fun disconnect() {} /** * Sends [message] to a connected device. * * Always returns `true`. Out-going messages can be viewed by [sendMessages]. * * To fake a successful message delivery, manually invoke [MessageCallback.onMessageSent]. */ override fun sendMessage(message: ByteArray): Boolean { sentMessages.add(message) return true } override fun registerConnectionCallback(callback: ConnectionCallback) { check(connectionCallbacks.add(callback)) { "Could not add connection callback." } } override fun unregisterConnectionCallback(callback: ConnectionCallback) { check(connectionCallbacks.remove(callback)) { "Did not remove callback." } } override fun registerMessageCallback(callback: MessageCallback) { check(messageCallbacks.add(callback)) { "Could not add message callback." } } override fun unregisterMessageCallback(callback: MessageCallback) { check(messageCallbacks.remove(callback)) { "Did not remove callback." } } }
apache-2.0
db55439e5e5bf6f2620d95527d845ca4
31.757895
99
0.732648
4.743902
false
false
false
false
SimpleMobileTools/Simple-Calculator
app/src/main/kotlin/com/simplemobiletools/calculator/databases/CalculatorDatabase.kt
1
1113
package com.simplemobiletools.calculator.databases import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.simplemobiletools.calculator.interfaces.CalculatorDao import com.simplemobiletools.calculator.models.History @Database(entities = [History::class], version = 1) abstract class CalculatorDatabase : RoomDatabase() { abstract fun CalculatorDao(): CalculatorDao companion object { private var db: CalculatorDatabase? = null fun getInstance(context: Context): CalculatorDatabase { if (db == null) { synchronized(CalculatorDatabase::class) { if (db == null) { db = Room.databaseBuilder(context.applicationContext, CalculatorDatabase::class.java, "calculator.db") .build() db!!.openHelper.setWriteAheadLoggingEnabled(true) } } } return db!! } fun destroyInstance() { db = null } } }
gpl-3.0
7f3074384a24e314347ed0cb4a154b3e
30.8
126
0.616352
5.3
false
false
false
false
ThomasVadeSmileLee/cyls
src/main/kotlin/com/github/salomonbrys/kotson/GsonBuilder.kt
1
9552
package com.github.salomonbrys.kotson import com.google.gson.GsonBuilder import com.google.gson.InstanceCreator import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import com.google.gson.TypeAdapter import com.google.gson.reflect.TypeToken import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonWriter import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import java.lang.reflect.WildcardType @Suppress("PROTECTED_CALL_FROM_PUBLIC_INLINE") inline fun <reified T : Any> gsonTypeToken(): Type = object : TypeToken<T>() {}.type fun ParameterizedType.isWildcard(): Boolean { var hasAnyWildCard = false var hasBaseWildCard = false var hasSpecific = false val cls = this.rawType as Class<*> cls.typeParameters.forEachIndexed { i, variable -> val argument = actualTypeArguments[i] if (argument is WildcardType) { val hit = variable.bounds.firstOrNull { it in argument.upperBounds } if (hit != null) { if (hit == Any::class.java) hasAnyWildCard = true else hasBaseWildCard = true } else hasSpecific = true } else hasSpecific = true } if (hasAnyWildCard && hasSpecific) throw IllegalArgumentException("Either none or all type parameters can be wildcard in $this") return hasAnyWildCard || (hasBaseWildCard && !hasSpecific) } fun removeTypeWildcards(type: Type): Type { if (type is ParameterizedType) { val arguments = type.actualTypeArguments .map { if (it is WildcardType) it.upperBounds[0] else it } .map { removeTypeWildcards(it) } .toTypedArray() return TypeToken.getParameterized(type.rawType, *arguments).type } return type } @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") inline fun <reified T : Any> typeToken(): Type { val type = gsonTypeToken<T>() if (type is ParameterizedType && type.isWildcard()) return type.rawType return removeTypeWildcards(type) } data class SerializerArg<out T>( val src: T, val type: Type, val context: SerializerArg.Context ) { class Context(val gsonContext: JsonSerializationContext) : JsonSerializationContext by gsonContext { inline fun <reified T : Any> typedSerialize(src: T) = gsonContext.serialize(src, typeToken<T>()) } } data class DeserializerArg( val json: JsonElement, val type: Type, val context: DeserializerArg.Context ) { class Context(val gsonContext: JsonDeserializationContext) : JsonDeserializationContext by gsonContext { inline fun <reified T : Any> deserialize(json: JsonElement) = gsonContext.deserialize<T>(json, typeToken<T>()) } } fun <T : Any> jsonSerializer(serializer: (arg: SerializerArg<T>) -> JsonElement): JsonSerializer<T> = JsonSerializer { src, type, context -> serializer(SerializerArg(src, type, SerializerArg.Context(context))) } fun <T : Any> jsonDeserializer(deserializer: (arg: DeserializerArg) -> T?): JsonDeserializer<T> = JsonDeserializer<T> { json, type, context -> deserializer(DeserializerArg(json, type, DeserializerArg.Context(context))) } fun <T : Any> instanceCreator(creator: (type: Type) -> T): InstanceCreator<T> = InstanceCreator { creator(it) } interface TypeAdapterBuilder<out T : Any, in R : T?> { fun read(function: JsonReader.() -> R) fun write(function: JsonWriter.(value: T) -> Unit) } internal class TypeAdapterBuilderImpl<T : Any, R : T?>( init: TypeAdapterBuilder<T, R>.() -> Unit ) : TypeAdapterBuilder<T, R> { private var _readFunction: (JsonReader.() -> R)? = null private var _writeFunction: (JsonWriter.(value: T) -> Unit)? = null override fun read(function: JsonReader.() -> R) { _readFunction = function } override fun write(function: JsonWriter.(value: T) -> Unit) { _writeFunction = function } fun build(): TypeAdapter<T> = object : TypeAdapter<T>() { override fun read(reader: JsonReader) = _readFunction!!.invoke(reader) override fun write(writer: JsonWriter, value: T) = _writeFunction!!.invoke(writer, value) } init { init() if (_readFunction == null || _writeFunction == null) throw IllegalArgumentException("You must define both a read and a write function") } } fun <T : Any> typeAdapter(init: TypeAdapterBuilder<T, T>.() -> Unit): TypeAdapter<T> = TypeAdapterBuilderImpl(init).build() fun <T : Any> nullableTypeAdapter(init: TypeAdapterBuilder<T, T?>.() -> Unit): TypeAdapter<T> = TypeAdapterBuilderImpl<T, T?>(init).build().nullSafe() inline fun <reified T : Any> GsonBuilder.registerTypeAdapter(typeAdapter: Any): GsonBuilder = this.registerTypeAdapter(typeToken<T>(), typeAdapter) inline fun <reified T : Any> GsonBuilder.registerTypeAdapter(serializer: JsonSerializer<T>): GsonBuilder = this.registerTypeAdapter<T>(serializer as Any) inline fun <reified T : Any> GsonBuilder.registerTypeAdapter(deserializer: JsonDeserializer<T>): GsonBuilder = this.registerTypeAdapter<T>(deserializer as Any) inline fun <reified T : Any> GsonBuilder.registerTypeHierarchyAdapter(typeAdapter: Any): GsonBuilder = this.registerTypeHierarchyAdapter(T::class.java, typeAdapter) interface RegistrationBuilder<T : Any, in R : T?> : TypeAdapterBuilder<T, R> { fun serialize(serializer: (arg: SerializerArg<T>) -> JsonElement) fun deserialize(deserializer: (DeserializerArg) -> T?) fun createInstances(creator: (type: Type) -> T) } internal open class RegistrationBuilderImpl<T : Any>( val registeredType: Type, init: RegistrationBuilder<T, T>.() -> Unit, protected val register: (typeAdapter: Any) -> Unit ) : RegistrationBuilder<T, T> { protected enum class _API { SD, RW } private var _api: _API? = null private var _readFunction: (JsonReader.() -> T)? = null private var _writeFunction: (JsonWriter.(value: T) -> Unit)? = null private fun _checkApi(api: _API) { if (_api != null && _api != api) throw IllegalArgumentException("You cannot use serialize/deserialize and read/write for the same type") _api = api } override fun serialize(serializer: (arg: SerializerArg<T>) -> JsonElement) { _checkApi(_API.SD) register(jsonSerializer(serializer)) } override fun deserialize(deserializer: (DeserializerArg) -> T?) { _checkApi(_API.SD) register(jsonDeserializer(deserializer)) } override fun createInstances(creator: (type: Type) -> T) = register(instanceCreator(creator)) private fun _registerTypeAdapter() { _checkApi(_API.RW) val readFunction = _readFunction val writeFunction = _writeFunction if (readFunction == null || writeFunction == null) return register(typeAdapter<T> { read(readFunction); write(writeFunction) }) _readFunction = null _writeFunction = null } override fun read(function: JsonReader.() -> T) { _readFunction = function _registerTypeAdapter() } override fun write(function: JsonWriter.(value: T) -> Unit) { _writeFunction = function _registerTypeAdapter() } init { init() if (_readFunction != null) throw IllegalArgumentException("You cannot define a read function without a write function") if (_writeFunction != null) throw IllegalArgumentException("You cannot define a write function without a read function") } } fun <T : Any> GsonBuilder.registerTypeAdapterBuilder(type: Type, init: RegistrationBuilder<T, T>.() -> Unit): GsonBuilder { RegistrationBuilderImpl(type, init) { registerTypeAdapter(type, it) } return this } inline fun <reified T : Any> GsonBuilder.registerTypeAdapter(noinline init: RegistrationBuilder<T, T>.() -> Unit): GsonBuilder = registerTypeAdapterBuilder(typeToken<T>(), init) fun <T : Any> GsonBuilder.registerNullableTypeAdapterBuilder(type: Type, init: TypeAdapterBuilder<T, T?>.() -> Unit): GsonBuilder { registerTypeAdapter(type, nullableTypeAdapter(init)) return this } inline fun <reified T : Any> GsonBuilder.registerNullableTypeAdapter(noinline init: TypeAdapterBuilder<T, T?>.() -> Unit): GsonBuilder = registerNullableTypeAdapterBuilder(typeToken<T>(), init) fun <T : Any> GsonBuilder.registerTypeHierarchyAdapterBuilder(type: Class<T>, init: RegistrationBuilder<T, T>.() -> Unit): GsonBuilder { RegistrationBuilderImpl(type, init) { registerTypeHierarchyAdapter(type, it) } return this } inline fun <reified T : Any> GsonBuilder.registerTypeHierarchyAdapter(noinline init: RegistrationBuilder<T, T>.() -> Unit): GsonBuilder = registerTypeHierarchyAdapterBuilder(T::class.java, init) fun <T : Any> GsonBuilder.registerNullableTypeHierarchyAdapterBuilder(type: Class<T>, init: TypeAdapterBuilder<T, T?>.() -> Unit): GsonBuilder { registerTypeHierarchyAdapter(type, nullableTypeAdapter(init)) return this } inline fun <reified T : Any> GsonBuilder.registerNullableTypeHierarchyAdapter(noinline init: TypeAdapterBuilder<T, T?>.() -> Unit): GsonBuilder = registerNullableTypeHierarchyAdapterBuilder(T::class.java, init)
mit
48cb6047cd249dc9e5f629f035acbb58
37.829268
150
0.68593
4.499293
false
false
false
false
bastman/kotlin-spring-jpa-examples
src/main/kotlin/com/example/demo/api/realestate/domain/jpa/entities/Broker.kt
1
2926
package com.example.demo.api.realestate.domain.jpa.entities import com.example.demo.jpa.JpaTypes import com.example.demo.logging.AppLogger import org.hibernate.annotations.Type import org.hibernate.validator.constraints.Email import org.hibernate.validator.constraints.NotBlank import org.springframework.validation.annotation.Validated import java.time.Instant import java.util.* import javax.persistence.* import javax.validation.constraints.NotNull @Entity data class Broker( @Id @Type(type = JpaTypes.UUID) @Column(name = "id", nullable = false) @get: [NotNull] val id: UUID, @Version @Column(name = "version", nullable = false) @get: [NotNull] val version: Int = -1, @Column(name = "created_at", nullable = false) private var created: Instant, @Column(name = "modified_at", nullable = false) private var modified: Instant, @Column(name = "company_name", nullable = false) @get:[NotNull NotBlank] val companyName: String, @Column(name = "first_name", nullable = false) @get:[NotNull NotBlank] val firstName: String, @Column(name = "last_name", nullable = false) @get:[NotNull NotBlank] val lastName: String, @Column(name = "email", nullable = false) @get:[NotNull Email] val email: String, @Column(name = "phone_number", nullable = false) @get:[NotNull] // can be blank val phoneNumber: String, @Column(name = "comment", nullable = false) @get:[NotNull] // can be blank val comment: String, @Embedded @get:[NotNull] val address: BrokerAddress ) { fun getCreatedAt(): Instant = created fun getModifiedAt(): Instant = modified @PreUpdate @Validated private fun beforeUpdate() { this.modified = Instant.now() LOG.info("beforeUpdate $this") } @PrePersist @Validated private fun beforeInsert() { created = Instant.now() modified = Instant.now() LOG.info("beforeInsert $this") } companion object { private val LOG = AppLogger(this::class) } } @Embeddable data class BrokerAddress( @Column(name = "address_country", nullable = false) @get:[NotNull] val country: String, @Column(name = "address_state", nullable = false) @get:[NotNull] val state: String, @Column(name = "address_city", nullable = false) @get:[NotNull] val city: String, @Column(name = "address_street", nullable = false) @get:[NotNull] val street: String, @Column(name = "address_number", nullable = false) @get:[NotNull] val number: String ) { companion object { val EMPTY = BrokerAddress(country = "", state = "", city = "", street = "", number = "") } }
mit
799b2a2afdecb3ae4bf7faf7fe28d5ba
26.87619
96
0.609023
4.115331
false
false
false
false
world-federation-of-advertisers/virtual-people-common
src/test/kotlin/org/wfanet/virtualpeople/common/fieldfilter/InFilterTest.kt
1
15720
// Copyright 2022 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.virtualpeople.common.fieldfilter import java.lang.IllegalStateException import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.virtualpeople.common.FieldFilterProto.Op import org.wfanet.virtualpeople.common.fieldFilterProto import org.wfanet.virtualpeople.common.test.* @RunWith(JUnit4::class) class InFilterTest { @Test fun `filter without name should fail`() { val fieldFilter = fieldFilterProto { op = Op.IN value = "1,2,1" } val exception = assertFailsWith<IllegalStateException> { FieldFilter.create(TestProto.getDescriptor(), fieldFilter) } assertTrue(exception.message!!.contains("Name must be set")) } @Test fun `filter with repeated field should fail`() { val fieldFilter = fieldFilterProto { name = "a.b.int32_values" op = Op.IN value = "1,2,1" } val exception = assertFailsWith<IllegalStateException> { FieldFilter.create(TestProto.getDescriptor(), fieldFilter) } assertTrue(exception.message!!.contains("Repeated field is not allowed")) } @Test fun `filter with repeated field in the path should fail`() { val fieldFilter = fieldFilterProto { name = "repeated_proto_a.b.int32_value" op = Op.IN value = "1,2,1" } val exception = assertFailsWith<IllegalStateException> { FieldFilter.create(TestProto.getDescriptor(), fieldFilter) } assertTrue(exception.message!!.contains("Repeated field is not allowed in the path")) } @Test fun `filter without value should fail`() { val fieldFilter = fieldFilterProto { name = "a.b.int32_value" op = Op.IN } val exception = assertFailsWith<IllegalStateException> { FieldFilter.create(TestProto.getDescriptor(), fieldFilter) } assertTrue(exception.message!!.contains("Value must be set")) } @Test fun `int32 in`() { val fieldFilter = fieldFilterProto { name = "a.b.int32_value" op = Op.IN value = "1,2,1" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto1 = testProto { a = testProtoA { b = testProtoB { int32Value = 1 } } } assertTrue(filter.matches(testProto1)) assertTrue(filter.matches(testProto1.toBuilder())) val testProto2 = testProto { a = testProtoA { b = testProtoB { int32Value = 2 } } } assertTrue(filter.matches(testProto2)) assertTrue(filter.matches(testProto2.toBuilder())) val testProto3 = testProto { a = testProtoA { b = testProtoB { int32Value = 3 } } } assertFalse(filter.matches(testProto3)) assertFalse(filter.matches(testProto3.toBuilder())) } @Test fun `int32 not set`() { val fieldFilter = fieldFilterProto { name = "a.b.int32_value" op = Op.IN value = "0" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto = testProto {} /** Return false when the field is not set. */ assertFalse(filter.matches(testProto)) assertFalse(filter.matches(testProto.toBuilder())) } @Test fun `int32 invalid value`() { val fieldFilter = fieldFilterProto { name = "a.b.int32_value" op = Op.IN value = "1,a,1" } assertFailsWith<NumberFormatException> { FieldFilter.create(TestProto.getDescriptor(), fieldFilter) } } @Test fun `int64 in`() { val fieldFilter = fieldFilterProto { name = "a.b.int64_value" op = Op.IN value = "1,2,1" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto1 = testProto { a = testProtoA { b = testProtoB { int64Value = 1 } } } assertTrue(filter.matches(testProto1)) assertTrue(filter.matches(testProto1.toBuilder())) val testProto2 = testProto { a = testProtoA { b = testProtoB { int64Value = 2 } } } assertTrue(filter.matches(testProto2)) assertTrue(filter.matches(testProto2.toBuilder())) val testProto3 = testProto { a = testProtoA { b = testProtoB { int64Value = 3 } } } assertFalse(filter.matches(testProto3)) assertFalse(filter.matches(testProto3.toBuilder())) } @Test fun `int64 not set`() { val fieldFilter = fieldFilterProto { name = "a.b.int64_value" op = Op.IN value = "0" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto = testProto {} /** Return false when the field is not set. */ assertFalse(filter.matches(testProto)) assertFalse(filter.matches(testProto.toBuilder())) } @Test fun `int64 invalid value`() { val fieldFilter = fieldFilterProto { name = "a.b.int64_value" op = Op.IN value = "1,a,1" } assertFailsWith<NumberFormatException> { FieldFilter.create(TestProto.getDescriptor(), fieldFilter) } } @Test fun `uint32 in`() { val fieldFilter = fieldFilterProto { name = "a.b.uint32_value" op = Op.IN value = "1,2,1" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto1 = testProto { a = testProtoA { b = testProtoB { uint32Value = 1 } } } assertTrue(filter.matches(testProto1)) assertTrue(filter.matches(testProto1.toBuilder())) val testProto2 = testProto { a = testProtoA { b = testProtoB { uint32Value = 2 } } } assertTrue(filter.matches(testProto2)) assertTrue(filter.matches(testProto2.toBuilder())) val testProto3 = testProto { a = testProtoA { b = testProtoB { uint32Value = 3 } } } assertFalse(filter.matches(testProto3)) assertFalse(filter.matches(testProto3.toBuilder())) } @Test fun `uint32 not set`() { val fieldFilter = fieldFilterProto { name = "a.b.uint32_value" op = Op.IN value = "0" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto = testProto {} /** Return false when the field is not set. */ assertFalse(filter.matches(testProto)) assertFalse(filter.matches(testProto.toBuilder())) } @Test fun `uint32 invalid value`() { val fieldFilter = fieldFilterProto { name = "a.b.uint32_value" op = Op.IN value = "1,a,1" } assertFailsWith<NumberFormatException> { FieldFilter.create(TestProto.getDescriptor(), fieldFilter) } } @Test fun `uint64 in`() { val fieldFilter = fieldFilterProto { name = "a.b.uint64_value" op = Op.IN value = "1,2,1" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto1 = testProto { a = testProtoA { b = testProtoB { uint64Value = 1 } } } assertTrue(filter.matches(testProto1)) assertTrue(filter.matches(testProto1.toBuilder())) val testProto2 = testProto { a = testProtoA { b = testProtoB { uint64Value = 2 } } } assertTrue(filter.matches(testProto2)) assertTrue(filter.matches(testProto2.toBuilder())) val testProto3 = testProto { a = testProtoA { b = testProtoB { uint64Value = 3 } } } assertFalse(filter.matches(testProto3)) assertFalse(filter.matches(testProto3.toBuilder())) } @Test fun `uint64 not set`() { val fieldFilter = fieldFilterProto { name = "a.b.uint64_value" op = Op.IN value = "0" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto = testProto {} /** Return false when the field is not set. */ assertFalse(filter.matches(testProto)) assertFalse(filter.matches(testProto.toBuilder())) } @Test fun `uint64 invalid value`() { val fieldFilter = fieldFilterProto { name = "a.b.uint64_value" op = Op.IN value = "1,a,1" } assertFailsWith<NumberFormatException> { FieldFilter.create(TestProto.getDescriptor(), fieldFilter) } } @Test fun `boolean in`() { val fieldFilter = fieldFilterProto { name = "a.b.bool_value" op = Op.IN value = "true,true" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto1 = testProto { a = testProtoA { b = testProtoB { boolValue = true } } } assertTrue(filter.matches(testProto1)) assertTrue(filter.matches(testProto1.toBuilder())) val testProto2 = testProto { a = testProtoA { b = testProtoB { boolValue = false } } } assertFalse(filter.matches(testProto2)) assertFalse(filter.matches(testProto2.toBuilder())) } @Test fun `boolean not set`() { val fieldFilter = fieldFilterProto { name = "a.b.bool_value" op = Op.IN value = "false" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto = testProto {} /** Return false when the field is not set. */ assertFalse(filter.matches(testProto)) assertFalse(filter.matches(testProto.toBuilder())) } @Test fun `boolean invalid value`() { val fieldFilter = fieldFilterProto { name = "a.b.bool_value" op = Op.IN value = "true,a" } val exception = assertFailsWith<IllegalArgumentException> { FieldFilter.create(TestProto.getDescriptor(), fieldFilter) } assertTrue(exception.message!!.contains("The string doesn't represent a boolean value")) } @Test fun `enum name in`() { val fieldFilter = fieldFilterProto { name = "a.b.enum_value" op = Op.IN value = "TEST_ENUM_1,TEST_ENUM_2,TEST_ENUM_1" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto1 = testProto { a = testProtoA { b = testProtoB { enumValue = TestProtoB.TestEnum.TEST_ENUM_1 } } } assertTrue(filter.matches(testProto1)) assertTrue(filter.matches(testProto1.toBuilder())) val testProto2 = testProto { a = testProtoA { b = testProtoB { enumValue = TestProtoB.TestEnum.TEST_ENUM_2 } } } assertTrue(filter.matches(testProto2)) assertTrue(filter.matches(testProto2.toBuilder())) val testProto3 = testProto { a = testProtoA { b = testProtoB { enumValue = TestProtoB.TestEnum.TEST_ENUM_3 } } } assertFalse(filter.matches(testProto3)) assertFalse(filter.matches(testProto3.toBuilder())) } @Test fun `enum number in`() { val fieldFilter = fieldFilterProto { name = "a.b.enum_value" op = Op.IN value = "1,2,1" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto1 = testProto { a = testProtoA { b = testProtoB { enumValue = TestProtoB.TestEnum.TEST_ENUM_1 } } } assertTrue(filter.matches(testProto1)) assertTrue(filter.matches(testProto1.toBuilder())) val testProto2 = testProto { a = testProtoA { b = testProtoB { enumValue = TestProtoB.TestEnum.TEST_ENUM_2 } } } assertTrue(filter.matches(testProto2)) assertTrue(filter.matches(testProto2.toBuilder())) val testProto3 = testProto { a = testProtoA { b = testProtoB { enumValue = TestProtoB.TestEnum.TEST_ENUM_3 } } } assertFalse(filter.matches(testProto3)) assertFalse(filter.matches(testProto3.toBuilder())) } @Test fun `enum name and number mixed in`() { val fieldFilter = fieldFilterProto { name = "a.b.enum_value" op = Op.IN value = "TEST_ENUM_1,2,1,TEST_ENUM_2" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto1 = testProto { a = testProtoA { b = testProtoB { enumValue = TestProtoB.TestEnum.TEST_ENUM_1 } } } assertTrue(filter.matches(testProto1)) assertTrue(filter.matches(testProto1.toBuilder())) val testProto2 = testProto { a = testProtoA { b = testProtoB { enumValue = TestProtoB.TestEnum.TEST_ENUM_2 } } } assertTrue(filter.matches(testProto2)) assertTrue(filter.matches(testProto2.toBuilder())) val testProto3 = testProto { a = testProtoA { b = testProtoB { enumValue = TestProtoB.TestEnum.TEST_ENUM_3 } } } assertFalse(filter.matches(testProto3)) assertFalse(filter.matches(testProto3.toBuilder())) } @Test fun `enum not set`() { val fieldFilter = fieldFilterProto { name = "a.b.enum_value" op = Op.IN value = "INVALID" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto = testProto {} /** Return false when the field is not set. */ assertFalse(filter.matches(testProto)) assertFalse(filter.matches(testProto.toBuilder())) } @Test fun `enum invalid value`() { val fieldFilter = fieldFilterProto { name = "a.b.enum_value" op = Op.IN value = "1,a,1" } val exception = assertFailsWith<IllegalStateException> { FieldFilter.create(TestProto.getDescriptor(), fieldFilter) } assertTrue(exception.message!!.contains("Not a valid enum name or integer")) } @Test fun `string in`() { val fieldFilter = fieldFilterProto { name = "a.b.string_value" op = Op.IN value = "a,b,a" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto1 = testProto { a = testProtoA { b = testProtoB { stringValue = "a" } } } assertTrue(filter.matches(testProto1)) assertTrue(filter.matches(testProto1.toBuilder())) val testProto2 = testProto { a = testProtoA { b = testProtoB { stringValue = "b" } } } assertTrue(filter.matches(testProto2)) assertTrue(filter.matches(testProto2.toBuilder())) val testProto3 = testProto { a = testProtoA { b = testProtoB { stringValue = "c" } } } assertFalse(filter.matches(testProto3)) assertFalse(filter.matches(testProto3.toBuilder())) val testProto4 = testProto {} assertFalse(filter.matches(testProto4)) assertFalse(filter.matches(testProto4.toBuilder())) } @Test fun `quota string in`() { val fieldFilter = fieldFilterProto { name = "a.b.string_value" op = Op.IN value = "\"" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto1 = testProto { a = testProtoA { b = testProtoB { stringValue = "\"" } } } assertTrue(filter.matches(testProto1)) assertTrue(filter.matches(testProto1.toBuilder())) val testProto2 = testProto { a = testProtoA { b = testProtoB { stringValue = "a" } } } assertFalse(filter.matches(testProto2)) assertFalse(filter.matches(testProto2.toBuilder())) val testProto3 = testProto {} assertFalse(filter.matches(testProto3)) assertFalse(filter.matches(testProto3.toBuilder())) } @Test fun `string not set`() { val fieldFilter = fieldFilterProto { name = "a.b.string_value" op = Op.IN value = "" } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto = testProto {} /** Return false when the field is not set. */ assertFalse(filter.matches(testProto)) assertFalse(filter.matches(testProto.toBuilder())) } }
apache-2.0
4c02d7981c292de69451270d7480e6b1
29.763209
92
0.662341
4.149947
false
true
false
false
android/views-widgets-samples
ViewPager2/app/src/main/java/androidx/viewpager2/integration/testapp/BrowseActivity.kt
1
3313
/* * 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 androidx.viewpager2.integration.testapp import android.app.ListActivity import android.content.Intent import android.os.Bundle import android.view.View import android.widget.ListView import android.widget.SimpleAdapter /** * This activity lists all the activities in this application. */ class BrowseActivity : ListActivity() { public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) listAdapter = SimpleAdapter(this, getData(), android.R.layout.simple_list_item_1, arrayOf("title"), intArrayOf(android.R.id.text1)) } private fun getData(): List<Map<String, Any>> { val myData = mutableListOf<Map<String, Any>>() myData.add(mapOf("title" to "ViewPager2 with Views", "intent" to activityToIntent(CardViewActivity::class.java.name))) myData.add(mapOf("title" to "ViewPager2 with Fragments", "intent" to activityToIntent(CardFragmentActivity::class.java.name))) myData.add(mapOf("title" to "ViewPager2 with a Mutable Collection (Views)", "intent" to activityToIntent(MutableCollectionViewActivity::class.java.name))) myData.add(mapOf("title" to "ViewPager2 with a Mutable Collection (Fragments)", "intent" to activityToIntent(MutableCollectionFragmentActivity::class.java.name))) myData.add(mapOf("title" to "ViewPager2 with a TabLayout (Views)", "intent" to activityToIntent(CardViewTabLayoutActivity::class.java.name))) myData.add(mapOf("title" to "ViewPager2 with Fake Dragging", "intent" to activityToIntent(FakeDragActivity::class.java.name))) myData.add(mapOf("title" to "ViewPager2 with PageTransformers", "intent" to activityToIntent(PageTransformerActivity::class.java.name))) myData.add(mapOf("title" to "ViewPager2 with a Preview of Next/Prev Page", "intent" to activityToIntent(PreviewPagesActivity::class.java.name))) myData.add(mapOf("title" to "ViewPager2 with Nested RecyclerViews", "intent" to activityToIntent(ParallelNestedScrollingActivity::class.java.name))) return myData } private fun activityToIntent(activity: String): Intent = Intent(Intent.ACTION_VIEW).setClassName(this.packageName, activity) override fun onListItemClick(listView: ListView, view: View, position: Int, id: Long) { val map = listView.getItemAtPosition(position) as Map<*, *> val intent = Intent(map["intent"] as Intent) intent.addCategory(Intent.CATEGORY_SAMPLE_CODE) startActivity(intent) } }
apache-2.0
1becf90de01b33710992b199320292ae
43.77027
98
0.697253
4.569655
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/ui/layout/VerticalDragLayout.kt
2
4294
package org.stepik.android.view.ui.layout import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.view.ViewConfiguration import android.widget.FrameLayout import kotlin.math.abs /** * Allow listen vertical drag motions. */ internal class VerticalDragLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { var draggingIsEnabled = true set(value) { field = value reset() } private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop // null - not detect move, true - vertical, false - horizontal private var isDetectedVerticalMove: Boolean? = null private var startX = 0f private var startY = 0f private var startInnerMoveY = 0f private var onDragListener: (dy: Float) -> Unit = {} private var onReleaseDragListener: (dy: Float) -> Unit = {} fun setOnDragListener(listener: (dy: Float) -> Unit) { onDragListener = listener } fun setOnReleaseDragListener(listener: (dy: Float) -> Unit) { onReleaseDragListener = listener } private fun reset() { isDetectedVerticalMove = null startX = 0f startY = 0f startInnerMoveY = 0f } override fun dispatchTouchEvent(ev: MotionEvent): Boolean { when (ev.action) { MotionEvent.ACTION_DOWN -> { if (ev.pointerCount == 1) { startX = ev.x startY = ev.y } else { isDetectedVerticalMove = null startX = 0f startY = 0f } } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { isDetectedVerticalMove = null startX = 0f startY = 0f } MotionEvent.ACTION_MOVE -> { if (draggingIsEnabled && isDetectedVerticalMove == null && ev.pointerCount == 1 && abs(startY - ev.y) > touchSlop ) { val direction = getDirection(ev, startX, startY) isDetectedVerticalMove = (direction == Direction.UP || direction == Direction.DOWN) } } } return super.dispatchTouchEvent(ev) } override fun onInterceptTouchEvent(ev: MotionEvent): Boolean = ev.pointerCount == 1 && ev.action == MotionEvent.ACTION_MOVE && isDetectedVerticalMove == true override fun onTouchEvent(ev: MotionEvent): Boolean { when (ev.action) { MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { if (ev.pointerCount == 1) { onReleaseDragListener(startInnerMoveY - ev.y) } startInnerMoveY = 0f } MotionEvent.ACTION_MOVE -> { if (startInnerMoveY == 0f) { startInnerMoveY = ev.y } onDragListener(startInnerMoveY - ev.y) } } return true } private fun getDirection(ev: MotionEvent, x: Float, y: Float) = Direction[getAngle(x, y, ev.x, ev.y)] private fun getAngle(x1: Float, y1: Float, x2: Float, y2: Float): Double { val rad = Math.atan2((y1 - y2).toDouble(), (x2 - x1).toDouble()) + Math.PI return (rad * 180 / Math.PI + 180) % 360 } private enum class Direction { UP, DOWN, LEFT, RIGHT; companion object { private const val V_ANGLE = 30F operator fun get(angle: Double): Direction = when { inRange(angle, 90f - V_ANGLE, 90f + V_ANGLE) -> UP inRange(angle, 0f, 90f - V_ANGLE) || inRange(angle, 270f + V_ANGLE, 360f) -> RIGHT inRange(angle, 270f - V_ANGLE, 270f + V_ANGLE) -> DOWN else -> LEFT } private fun inRange(angle: Double, init: Float, end: Float) = angle >= init && angle < end } } }
apache-2.0
8cb2ccce18871b9152793920f32f8eb7
29.678571
103
0.534001
4.808511
false
false
false
false
jiaminglu/kotlin-native
shared/src/main/kotlin/org/jetbrains/kotlin/konan/target/Properties.kt
1
1914
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.konan.properties import org.jetbrains.kotlin.konan.file.* typealias Properties = java.util.Properties fun File.loadProperties(): Properties { val properties = java.util.Properties() this.bufferedReader().use { reader -> properties.load(reader) } return properties } fun loadProperties(path: String): Properties = File(path).loadProperties() fun File.saveProperties(properties: Properties) { this.outputStream().use { properties.store(it, null) } } fun Properties.saveToFile(file: File) = file.saveProperties(this) fun Properties.propertyString(key: String, suffix: String? = null): String? = this.getProperty(key.suffix(suffix)) /** * TODO: this method working with suffixes should be replaced with * functionality borrowed from def file parser and unified for interop tool * and kotlin compiler. */ fun Properties.propertyList(key: String, suffix: String? = null): List<String> { val value = this.getProperty(key.suffix(suffix)) ?: this.getProperty(key) return value?.split(' ') ?: emptyList() } fun Properties.hasProperty(key: String, suffix: String? = null): Boolean = this.getProperty(key.suffix(suffix)) != null fun String.suffix(suf: String?): String = if (suf == null) this else "${this}.$suf"
apache-2.0
9a5c79f81814548da65820636ab91d0f
30.377049
80
0.719958
3.995825
false
false
false
false
mtransitapps/parser
src/main/java/org/mtransit/parser/mt/data/MSpec.kt
1
2603
package org.mtransit.parser.mt.data import org.mtransit.commons.toIntTimestampSec import org.mtransit.parser.MTLog import org.mtransit.parser.db.DBUtils import java.text.SimpleDateFormat import java.util.ArrayList import java.util.Locale import java.util.TreeMap import java.util.concurrent.TimeUnit @Suppress("MemberVisibilityCanBePrivate") data class MSpec( val agencies: ArrayList<MAgency>, val stops: ArrayList<MStop>, val routes: ArrayList<MRoute>, val trips: ArrayList<MTrip>, val tripStops: ArrayList<MTripStop>, val serviceDates: ArrayList<MServiceDate>, val routeFrequencies: TreeMap<Long, ArrayList<MFrequency>>, val firstTimestamp: Long, val lastTimestamp: Long, ) { var schedules: Collection<MSchedule>? = null val isValid: Boolean get() = (hasAgencies() && hasServiceDates() && hasRoutes() && hasTrips() && hasTripStops() && hasStops() // && (hasStopSchedules() || hasRouteFrequencies())) fun hasAgencies(): Boolean { return agencies.size > 0 } val firstAgency: MAgency get() { if (agencies.isEmpty()) { throw MTLog.Fatal("No 1st agency '%s'!", agencies) } return agencies[0] } fun hasStops(): Boolean { return stops.size > 0 } fun hasRoutes(): Boolean { return routes.size > 0 } val firstRoute: MRoute get() { if (routes.isEmpty()) { throw MTLog.Fatal("No 1st route '%s'!", routes) } return routes[0] } fun hasTrips(): Boolean { return trips.size > 0 } fun hasTripStops(): Boolean { return tripStops.size > 0 } fun hasServiceDates(): Boolean { return serviceDates.size > 0 } fun hasStopSchedules(): Boolean { return this.schedules?.isNotEmpty() ?: (DBUtils.countSchedule() > 0) } fun hasRouteFrequencies(): Boolean { return routeFrequencies.size > 0 } // TODO later max integer = 2147483647 = Tuesday, January 19, 2038 3:14:07 AM GMT val firstTimestampInSeconds: Int get() = TimeUnit.MILLISECONDS.toSeconds(firstTimestamp).toIntTimestampSec() val lastTimestampInSeconds: Int get() = TimeUnit.MILLISECONDS.toSeconds(lastTimestamp).toIntTimestampSec() companion object { @JvmStatic val newTimeFormatInstance: SimpleDateFormat get() = SimpleDateFormat("HHmmss", Locale.ENGLISH) } }
apache-2.0
0f331cb1bc01579b1d63cb2aea75befa
26.626374
115
0.611986
4.37479
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/extension/model/Extension.kt
1
2239
package eu.kanade.tachiyomi.extension.model import android.graphics.drawable.Drawable import eu.kanade.domain.source.model.SourceData import eu.kanade.tachiyomi.source.Source sealed class Extension { abstract val name: String abstract val pkgName: String abstract val versionName: String abstract val versionCode: Long abstract val lang: String? abstract val isNsfw: Boolean abstract val hasReadme: Boolean abstract val hasChangelog: Boolean data class Installed( override val name: String, override val pkgName: String, override val versionName: String, override val versionCode: Long, override val lang: String, override val isNsfw: Boolean, override val hasReadme: Boolean, override val hasChangelog: Boolean, val pkgFactory: String?, val sources: List<Source>, val icon: Drawable?, val hasUpdate: Boolean = false, val isObsolete: Boolean = false, val isUnofficial: Boolean = false, ) : Extension() data class Available( override val name: String, override val pkgName: String, override val versionName: String, override val versionCode: Long, override val lang: String, override val isNsfw: Boolean, override val hasReadme: Boolean, override val hasChangelog: Boolean, val sources: List<AvailableSources>, val apkName: String, val iconUrl: String, ) : Extension() data class Untrusted( override val name: String, override val pkgName: String, override val versionName: String, override val versionCode: Long, val signatureHash: String, override val lang: String? = null, override val isNsfw: Boolean = false, override val hasReadme: Boolean = false, override val hasChangelog: Boolean = false, ) : Extension() } data class AvailableSources( val id: Long, val lang: String, val name: String, val baseUrl: String, ) { fun toSourceData(): SourceData { return SourceData( id = this.id, lang = this.lang, name = this.name, ) } }
apache-2.0
28cbd69123a34865437d75bc67b68283
28.853333
51
0.642251
4.804721
false
false
false
false
gurleensethi/LiteUtilities
liteutils/src/main/java/com/thetechnocafe/gurleensethi/liteutils/RecyclerUtils.kt
1
5831
package com.thetechnocafe.gurleensethi.liteutils import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup /** * Created by gurleensethi on 30/07/17. * Convenient RecyclerAdapter with generic data type list. * Create an instance and specify the type of data being passed. * Implement callbacks to handle the required functions * * Motivation: Create a recycler adapter in minimal lines of code yet * providing high customisation and complete control */ open class RecyclerAdapterUtil<T>( val context: Context, //This list will serve as the main data list for the Recycler Adapter val itemList: List<T>, //The id of layout resource that is to be inflated when onCreateViewHolder is called val viewHolderLayoutRecourse: Int) : RecyclerView.Adapter<RecyclerAdapterUtil<T>.ViewHolder>() { /** * List containing all the views that are contained in the single item layout file * There are retained before hand to improve performance and avoiding unnecessary calls * to findViewById every time data is bound * */ private var mViewsList: List<Int> = mutableListOf() /** * Listener to bind the data with the single item view. * The View and item of type T provided by the user are passed as the arguments * Any view contained in the single view of the RecyclerView can be obtained * from itemView, and the required data can be set from item **/ private var mOnDataBindListener: ((itemView: View, item: T, position: Int, innerViews: Map<Int, View>) -> Unit)? = null /** * Lambda for handling the onClick callback for a view. * The position of click and the corresponding item of type T from the itemList * are passed as arguments * */ private var mOnClickListener: ((item: T, position: Int) -> Unit)? = null /** * Lambda for handling the onLongClick callback for a view. * The position of long click and the corresponding item of type T from the itemList * are passed as arguments * */ private var mOnLongClickListener: ((item: T, position: Int) -> Unit)? = null /** * Setters for views list * */ fun addViewsList(vararg viewsList: Int) { mViewsList = viewsList.asList() } fun addViewsList(viewsList: List<Int>) { mViewsList = viewsList; } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder { val view = LayoutInflater.from(context).inflate(viewHolderLayoutRecourse, parent, false) return ViewHolder(view) } override fun getItemCount(): Int = itemList.size override fun onBindViewHolder(holder: ViewHolder?, position: Int) { holder?.bindData(position) } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener, View.OnLongClickListener { /** * Mutable Map holding all the bindings to inner views provided by the user * */ private var viewMap: MutableMap<Int, View> = mutableMapOf() init { itemView.setOnClickListener(this) itemView.setOnLongClickListener(this) for (view in mViewsList) { viewMap[view] = itemView.findViewById(view) } } fun bindData(position: Int) { mOnDataBindListener?.invoke(itemView, itemList[position], position, viewMap) } override fun onClick(view: View?) { mOnClickListener?.invoke(itemList[adapterPosition], adapterPosition) } override fun onLongClick(view: View?): Boolean { mOnLongClickListener?.invoke(itemList[adapterPosition], adapterPosition) return true } } fun addOnDataBindListener(listener: (itemView: View, item: T, position: Int, innerViews: Map<Int, View>) -> Unit) { mOnDataBindListener = listener } fun addOnClickListener(listener: (item: T, position: Int) -> Unit) { mOnClickListener = listener } fun addOnLongClickListener(listener: (item: T, position: Int) -> Unit) { mOnLongClickListener = listener } /** * Builder class for setting up recycler adapter */ class Builder<T>(context: Context, itemList: List<T>, viewHolderLayoutRecourse: Int) { private var mRecyclerAdapter: RecyclerAdapterUtil<T> = RecyclerAdapterUtil(context, itemList, viewHolderLayoutRecourse) fun bindView(listener: (itemView: View, item: T, position: Int, innerViews: Map<Int, View>) -> Unit): Builder<T> { mRecyclerAdapter.addOnDataBindListener(listener) return this } fun addClickListener(listener: (item: T, position: Int) -> Unit): Builder<T> { mRecyclerAdapter.addOnClickListener(listener) return this } fun addLongClickListener(listener: (item: T, position: Int) -> Unit): Builder<T> { mRecyclerAdapter.addOnLongClickListener(listener) return this } fun viewsList(viewsList: List<Int>): Builder<T> { mRecyclerAdapter.addViewsList(viewsList) return this } fun viewsList(vararg viewsList: Int): Builder<T> { mRecyclerAdapter.addViewsList(viewsList.asList()) return this } /* * Return the created adapter * */ fun build(): RecyclerAdapterUtil<T> = mRecyclerAdapter /* * Set the adapter to the recycler view * */ fun into(recyclerView: RecyclerView) { recyclerView.adapter = mRecyclerAdapter } } } class ViewItem<T : View>(val viewId: Int)
mit
1d92b7cbfd0f1e1fbc45700065fbdcce
33.508876
127
0.653576
4.79129
false
false
false
false
esqr/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/pojo/ConversationsListResponse.kt
1
690
package io.github.feelfreelinux.wykopmobilny.models.pojo import com.squareup.moshi.Json data class ConversationsListResponse( @Json(name = "last_update") val lastUpdate : String, @Json(name = "author") val author : String, @Json(name = "author_avatar") val authorAvatar : String, @Json(name = "author_avatar_med") val authorAvatarMed : String, @Json(name = "author_avatar_lo") val authorAvatarLo : String, @Json(name = "author_group") val authorGroup : Int, @Json(name = "author_sex") val authorSex : String, @Json(name = "status") val status : String )
mit
1190f9f2f7f126ee2e15364b24232613
22.827586
56
0.592754
3.988439
false
false
false
false
exponentjs/exponent
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/permissions/requesters/BackgroundLocationRequester.kt
2
3744
package abi42_0_0.expo.modules.permissions.requesters import android.Manifest import android.os.Build import android.os.Bundle import androidx.annotation.RequiresApi import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponse import abi42_0_0.expo.modules.interfaces.permissions.PermissionsStatus class BackgroundLocationRequester : PermissionRequester { override fun parseAndroidPermissions(permissionsResponse: Map<String, PermissionsResponse>) = when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> parseAndroidPermissionsForAndroidR(permissionsResponse) Build.VERSION.SDK_INT == Build.VERSION_CODES.Q -> parseAndroidPermissionsForAndroidQ(permissionsResponse) else -> parseAndroidPermissionsForLegacyAndroids(permissionsResponse) } override fun getAndroidPermissions(): List<String> { return when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> { listOf( Manifest.permission.ACCESS_BACKGROUND_LOCATION ) } Build.VERSION.SDK_INT == Build.VERSION_CODES.Q -> { listOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION ) } else -> { listOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ) } } } @RequiresApi(Build.VERSION_CODES.R) private fun parseAndroidPermissionsForAndroidR(permissionsResponse: Map<String, PermissionsResponse>): Bundle { return Bundle().apply { val backgroundLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_BACKGROUND_LOCATION) val permissionsStatus = backgroundLocation.status putString(PermissionsResponse.STATUS_KEY, permissionsStatus.status) putString(PermissionsResponse.EXPIRES_KEY, PermissionsResponse.PERMISSION_EXPIRES_NEVER) putBoolean(PermissionsResponse.CAN_ASK_AGAIN_KEY, backgroundLocation.canAskAgain) putBoolean(PermissionsResponse.GRANTED_KEY, permissionsStatus == PermissionsStatus.GRANTED) } } @RequiresApi(Build.VERSION_CODES.Q) private fun parseAndroidPermissionsForAndroidQ(permissionsResponse: Map<String, PermissionsResponse>): Bundle { return Bundle().apply { val accessFineLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_FINE_LOCATION) val accessCoarseLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_COARSE_LOCATION) val accessBackgroundLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_BACKGROUND_LOCATION) val canAskAgain = accessFineLocation.canAskAgain && accessCoarseLocation.canAskAgain && accessBackgroundLocation.canAskAgain val statuses = listOf(accessFineLocation.status, accessCoarseLocation.status, accessBackgroundLocation.status) val status = when { statuses.all { it == PermissionsStatus.GRANTED } -> { PermissionsStatus.GRANTED } statuses.all { it == PermissionsStatus.DENIED } -> { PermissionsStatus.DENIED } else -> { PermissionsStatus.UNDETERMINED } } val isGranted = status == PermissionsStatus.GRANTED putString(PermissionsResponse.STATUS_KEY, status.status) putString(PermissionsResponse.EXPIRES_KEY, PermissionsResponse.PERMISSION_EXPIRES_NEVER) putBoolean(PermissionsResponse.CAN_ASK_AGAIN_KEY, canAskAgain) putBoolean(PermissionsResponse.GRANTED_KEY, isGranted) } } private fun parseAndroidPermissionsForLegacyAndroids(permissionsResponse: Map<String, PermissionsResponse>): Bundle { return parseBasicLocationPermissions(permissionsResponse) } }
bsd-3-clause
55183a15fa2af69e1d4d7e6d1d11edc1
41.067416
130
0.748932
5.221757
false
false
false
false
Jumpaku/JumpakuOthello
api/src/main/kotlin/jumpaku/othello/selectors/InputSelector.kt
1
875
package jumpaku.othello.selectors import jumpaku.commons.control.result import jumpaku.othello.game.Phase import jumpaku.othello.game.Move import jumpaku.othello.game.Pos import java.io.InputStream import java.util.* class InputSelector(input: InputStream) : Selector { private val scanner = Scanner(input) override fun select(phase: Phase): Move { require(phase is Phase.InProgress) val ms = phase.availableMoves if (ms.any { it is Move.Pass }) return Move.Pass while (true) { val l = scanner.nextLine() if (l.length != 2) continue return result { val r = l.drop(1).toInt() - 1 val c = l.take(1).toInt() - 1 Move.Place(Pos(r, c)) }.value().filter { it.pos in ms.map { (it as Move.Place).pos } }.orNull() ?: continue } } }
bsd-2-clause
5daa0dc4319e47829c3e263e44602c20
29.206897
97
0.604571
3.90625
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LALR1/grammar/codegen/Codegen.kt
1
4810
package com.bajdcc.LALR1.grammar.codegen import com.bajdcc.LALR1.grammar.runtime.* import com.bajdcc.LALR1.grammar.symbol.SymbolTable import com.bajdcc.LALR1.grammar.tree.Func import com.bajdcc.util.HashListMap import com.bajdcc.util.intervalTree.Interval /** * 【中间代码】中间代码接口实现 * * @author bajdcc */ class Codegen(symbol: SymbolTable) : ICodegen, ICodegenBlock, ICodegenByteWriter { private val symbolList = symbol.manageDataService.symbolList private val funcMap = HashListMap<Func>() private val data = CodegenData() private val info = RuntimeDebugInfo() private val insts = mutableListOf<Byte>() private val itvList = mutableListOf<Interval<Any>>() val codeString: String get() { val sb = StringBuilder() sb.append("#### 中间代码 ####") sb.append(System.lineSeparator()) var idx = 0 data.insts.forEach { sb.append(String.format("%03d\t%s", idx, it.toString("\t"))) idx += it.advanceLength sb.append(System.lineSeparator()) } return sb.toString() } init { for (funcs in symbol.manageDataService.funcMap.toList()) { for (func in funcs) { funcMap.add(func) } } } override fun getFuncIndex(func: Func): Int { return funcMap.indexOf(func) } /** * 产生中间代码 */ fun gencode() { genCode(RuntimeInst.iopena) genCodeWithFuncWriteBack(RuntimeInst.ipush, 0) genCode(RuntimeInst.icall) genCode(RuntimeInst.ipop) genCode(RuntimeInst.ihalt) genCode(RuntimeInst.inop) funcMap.forEach { func -> if (func.isExtern) { info.addExports(func.realName, data.codeIndex) info.addExternalFunc(func.realName, RuntimeDebugExec(paramsDoc = func.params.joinToString(separator = ",", transform = { it.toRealString() }))) } func.genCode(this) } } /** * 产生代码页 * * @return 代码页 */ fun genCodePage(): RuntimeCodePage { val objs = symbolList.toList() data.callsToWriteBack.forEach { unary -> unary.op1 = data.funcEntriesMap[funcMap.get(unary.op1).refName]!! } for (inst in data.insts) { inst.gen(this) } return RuntimeCodePage(objs, insts.toByteArray(), info, itvList) } override fun genFuncEntry(funcName: String) { data.pushFuncEntry(funcName) info.addFunc(funcName, data.codeIndex) } override fun genCode(inst: RuntimeInst): RuntimeInstNon { val i = RuntimeInstNon(inst) data.pushCode(i) return i } override fun genCode(inst: RuntimeInst, op1: Int): RuntimeInstUnary { val i = RuntimeInstUnary(inst, op1) data.pushCode(i) return i } override fun genCodeWithFuncWriteBack(inst: RuntimeInst, op1: Int): RuntimeInstUnary { val i = RuntimeInstUnary(inst, op1) data.pushCodeWithFuncWriteBack(i) return i } override fun genCode(inst: RuntimeInst, op1: Int, op2: Int): RuntimeInstBinary { val i = RuntimeInstBinary(inst, op1, op2) data.pushCode(i) return i } override fun genDebugInfo(start: Int, end: Int, info: Any) { itvList.add(Interval((start - 1).toLong(), (end + 1).toLong(), info)) } override val blockService: ICodegenBlock get() { return this } override fun genBreak(): RuntimeInstUnary { val block = data.block val i = RuntimeInstUnary(RuntimeInst.ijmp, block.breakId) data.pushCode(i) return i } override fun genContinue(): RuntimeInstUnary { val block = data.block val i = RuntimeInstUnary(RuntimeInst.ijmp, block.continueId) data.pushCode(i) return i } override fun enterBlockEntry(block: CodegenBlock) { data.enterBlockEntry(block) } override fun leaveBlockEntry() { data.leaveBlockEntry() } override val isInBlock: Boolean get() { return data.hasBlock() } override fun genDataRef(obj: Any): Int { return symbolList.put(obj) } override val codeIndex: Int get() { return data.codeIndex } override fun toString(): String { return codeString } override fun genInst(inst: RuntimeInst) { insts.add(inst.ordinal.toByte()) } override fun genOp(op: Int) { for (i in 0..3) { insts.add((op shr 8 * i and 0xFF).toByte()) } } }
mit
0d4305afb445757230d81e67b9631f09
26.264368
131
0.587057
4.154116
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/impl/textedit/transformation/DeleteCharacter.kt
1
3025
package org.hexworks.zircon.internal.component.impl.textedit.transformation import org.hexworks.zircon.internal.component.impl.textedit.EditableTextBuffer import org.hexworks.zircon.internal.component.impl.textedit.TextBufferTransformation import org.hexworks.zircon.internal.component.impl.textedit.cursor.Cursor import org.hexworks.zircon.internal.component.impl.textedit.transformation.DeleteCharacter.DeleteKind.BACKSPACE import org.hexworks.zircon.internal.component.impl.textedit.transformation.DeleteCharacter.DeleteKind.DEL class DeleteCharacter(private val deleteKind: DeleteKind) : TextBufferTransformation { override fun applyTo(buffer: EditableTextBuffer) { val cursor = buffer.cursor val cursorRow = buffer.getRow(cursor.rowIdx) when { cursor.isAtTheStartOfTheFirstRow() -> { if (deleteKind == DEL) { deleteFirstCharOfRow(buffer, cursor) } } cursor.isAtTheStartOfARow() -> { when (deleteKind) { DEL -> { deleteFirstCharOfRow(buffer, cursor) } BACKSPACE -> { // the cursor is at the start of **a** row (not the first) // so we delete the row and add it to the previous row val prevRow = buffer.getRow(cursor.rowIdx - 1) val prevRowLength = prevRow.size // we add the next row to the previous row prevRow.addAll(buffer.deleteRow(cursor.rowIdx)) // we fix the cursor buffer.cursor = cursor.withRelativeRow(-1).withRelativeColumn(prevRowLength) } } } else -> { when (deleteKind) { DEL -> { val deleteIdx = cursor.colIdx if (buffer.getLastColumnIdxForRow(cursor.rowIdx) >= deleteIdx) { cursorRow.removeAt(deleteIdx) } } BACKSPACE -> { val deleteIdx = cursor.colIdx - 1 // we delete the character at the cursor position // note that the cursor is always **after** the character, thus the - 1 above cursorRow.removeAt(deleteIdx) buffer.cursor = cursor.withRelativeColumn(-1) } } } } } private fun deleteFirstCharOfRow(buffer: EditableTextBuffer, cursor: Cursor) { val cursorRow = buffer.getRow(cursor.rowIdx) if (cursorRow.isEmpty() && buffer.rowCount() > 1) { buffer.deleteRow(cursor.rowIdx) } else if (cursorRow.isNotEmpty()) { cursorRow.removeAt(0) } } enum class DeleteKind { DEL, BACKSPACE } }
apache-2.0
b05e1fcd8e8e9e4520498972a2496cca
40.438356
111
0.544463
5.179795
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/model/data/remote/api/forum/ForumApi.kt
1
2550
package forpdateam.ru.forpda.model.data.remote.api.forum import forpdateam.ru.forpda.entity.remote.forum.* import forpdateam.ru.forpda.model.data.remote.IWebClient import forpdateam.ru.forpda.model.data.remote.api.NetworkRequest import java.util.* /** * Created by radiationx on 15.02.17. */ class ForumApi( private val webClient: IWebClient, private val forumParser: ForumParser ) { fun getForums(): ForumItemTree { val response = webClient.get("https://4pda.to/forum/index.php?act=search") return forumParser.parseForums(response.body) } fun getRules(): ForumRules { val response = webClient.get("https://4pda.to/forum/index.php?act=boardrules") return forumParser.parseRules(response.body) } fun getAnnounce(id: Int, forumId: Int): Announce { val response = webClient.get("https://4pda.to/forum/index.php?act=announce&f=$forumId&st=$id") return forumParser.parseAnnounce(response.body) } fun markAllRead(): Any { webClient.request(NetworkRequest.Builder().url("https://4pda.to/forum/index.php?act=auth&action=markboard").withoutBody().build()) return Any() } fun markRead(id: Int): Any { webClient.request(NetworkRequest.Builder().url("https://4pda.to/forum/index.php?act=auth&action=markforum&f=$id&fromforum=$id").withoutBody().build()) return Any() } fun transformToList(list: MutableList<IForumItemFlat>, rootForum: ForumItemTree) { rootForum.forums?.forEach { list.add(ForumItemFlat(it)) transformToList(list, it) } } fun transformToTree(list: Collection<IForumItemFlat>, rootForum: ForumItemTree) { val parentsList = ArrayList<ForumItemTree>() var lastParent = rootForum parentsList.add(lastParent) for (item in list) { val newItem = ForumItemTree(item) if (item.level <= lastParent.level) { //Удаление элементов, учитывая случай с резким скачком уровня вложенности for (i in 0 until lastParent.level - item.level + 1) parentsList.removeAt(parentsList.size - 1) lastParent = parentsList[parentsList.size - 1] } lastParent.addForum(newItem) if (item.level > lastParent.level) { lastParent = newItem parentsList.add(lastParent) } } parentsList.clear() } }
gpl-3.0
7afcb0600502f993f752faa8eb54bd86
34.542857
158
0.643087
4.085386
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinUsageContextDataFlowPanelBase.kt
1
4778
// 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.slicer import com.intellij.analysis.AnalysisScope import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.psi.PsiElement import com.intellij.slicer.DuplicateMap import com.intellij.slicer.SliceAnalysisParams import com.intellij.slicer.SlicePanel import com.intellij.slicer.SliceRootNode import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewBundle import com.intellij.usages.PsiElementUsageTarget import com.intellij.usages.UsageContextPanel import com.intellij.usages.UsageView import com.intellij.usages.UsageViewPresentation import com.intellij.usages.impl.UsageContextPanelBase import com.intellij.usages.impl.UsageViewImpl import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.psi.KtDeclaration import java.awt.BorderLayout import javax.swing.JLabel import javax.swing.JPanel import javax.swing.SwingConstants sealed class KotlinUsageContextDataFlowPanelBase( project: Project, presentation: UsageViewPresentation, private val isInflow: Boolean ) : UsageContextPanelBase(project, presentation) { private var panel: JPanel? = null abstract class ProviderBase : UsageContextPanel.Provider { override fun isAvailableFor(usageView: UsageView): Boolean { val target = (usageView as UsageViewImpl).targets.firstOrNull() ?: return false val element = (target as? PsiElementUsageTarget)?.element return element is KtDeclaration && element.isValid } } private fun createParams(element: PsiElement): SliceAnalysisParams { return SliceAnalysisParams().apply { scope = AnalysisScope(element.project) dataFlowToThis = isInflow showInstanceDereferences = true } } protected fun createPanel(element: PsiElement, dataFlowToThis: Boolean): JPanel { val toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.FIND) ?: error("Can't find ToolWindowId.FIND") val params = createParams(element) val rootNode = SliceRootNode(myProject, DuplicateMap(), KotlinSliceUsage(element, params)) return object : SlicePanel(myProject, dataFlowToThis, rootNode, false, toolWindow) { override fun isToShowAutoScrollButton() = false override fun isToShowPreviewButton() = false override fun isAutoScroll() = false override fun setAutoScroll(autoScroll: Boolean) {} override fun isPreview() = false override fun setPreview(preview: Boolean) {} } } public override fun updateLayoutLater(infos: List<UsageInfo>?) { if (infos.isNullOrEmpty()) { removeAll() val title = UsageViewBundle.message("select.the.usage.to.preview") add(JLabel(title, SwingConstants.CENTER), BorderLayout.CENTER) } else { val element = infos.firstOrNull()?.element ?: return if (panel != null) { Disposer.dispose(panel as Disposable) } val panel = createPanel(element, isInflow) Disposer.register(this, panel as Disposable) removeAll() add(panel, BorderLayout.CENTER) this.panel = panel } revalidate() } override fun dispose() { super.dispose() panel = null } } class KotlinUsageContextDataInflowPanel( project: Project, presentation: UsageViewPresentation ) : KotlinUsageContextDataFlowPanelBase(project, presentation, true) { class Provider : ProviderBase() { override fun create(usageView: UsageView): UsageContextPanel { return KotlinUsageContextDataInflowPanel((usageView as UsageViewImpl).project, usageView.getPresentation()) } override fun getTabTitle() = KotlinBundle.message("slicer.title.dataflow.to.here") } } class KotlinUsageContextDataOutflowPanel( project: Project, presentation: UsageViewPresentation ) : KotlinUsageContextDataFlowPanelBase(project, presentation, false) { class Provider : ProviderBase() { override fun create(usageView: UsageView): UsageContextPanel { return KotlinUsageContextDataOutflowPanel((usageView as UsageViewImpl).project, usageView.getPresentation()) } override fun getTabTitle() = KotlinBundle.message("slicer.title.dataflow.from.here") } }
apache-2.0
a0216603e8bbe34d68e1c20115c1c6ab
37.232
158
0.719339
5.029474
false
false
false
false
ingokegel/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/PlatformModules.kt
1
14663
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") package org.jetbrains.intellij.build.impl import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.ProductModulesLayout import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.w3c.dom.Element import java.nio.file.Files import java.util.* import javax.xml.parsers.DocumentBuilderFactory private const val UTIL_JAR = "util.jar" private const val UTIL_RT_JAR = "util_rt.jar" private val PLATFORM_API_MODULES: List<String> = java.util.List.of( "intellij.platform.analysis", "intellij.platform.builtInServer", "intellij.platform.core", "intellij.platform.diff", "intellij.platform.vcs.dvcs", "intellij.platform.editor", "intellij.platform.externalSystem", "intellij.platform.externalSystem.dependencyUpdater", "intellij.platform.codeStyle", "intellij.platform.indexing", "intellij.platform.jps.model", "intellij.platform.lang.core", "intellij.platform.lang", "intellij.platform.lvcs", "intellij.platform.ml", "intellij.platform.ide", "intellij.platform.ide.core", "intellij.platform.projectModel", "intellij.platform.remote.core", "intellij.platform.remoteServers.agent.rt", "intellij.platform.remoteServers", "intellij.platform.tasks", "intellij.platform.usageView", "intellij.platform.vcs.core", "intellij.platform.vcs", "intellij.platform.vcs.log", "intellij.platform.vcs.log.graph", "intellij.platform.execution", "intellij.platform.debugger", "intellij.xml.analysis", "intellij.xml", "intellij.xml.psi", "intellij.xml.structureView", "intellij.platform.concurrency", ) /** * List of modules which are included into lib/app.jar in all IntelliJ based IDEs. */ private val PLATFORM_IMPLEMENTATION_MODULES: List<String> = java.util.List.of( "intellij.platform.analysis.impl", "intellij.platform.builtInServer.impl", "intellij.platform.core.impl", "intellij.platform.ide.core.impl", "intellij.platform.diff.impl", "intellij.platform.editor.ex", "intellij.platform.codeStyle.impl", "intellij.platform.indexing.impl", "intellij.platform.elevation", "intellij.platform.elevation.client", "intellij.platform.elevation.common", "intellij.platform.elevation.daemon", "intellij.platform.externalProcessAuthHelper", "intellij.platform.refactoring", "intellij.platform.inspect", "intellij.platform.lang.impl", "intellij.platform.workspaceModel.storage", "intellij.platform.workspaceModel.jps", "intellij.platform.lvcs.impl", "intellij.platform.ide.impl", "intellij.platform.projectModel.impl", "intellij.platform.macro", "intellij.platform.execution.impl", "intellij.platform.wsl.impl", "intellij.platform.externalSystem.impl", "intellij.platform.scriptDebugger.protocolReaderRuntime", "intellij.regexp", "intellij.platform.remoteServers.impl", "intellij.platform.scriptDebugger.backend", "intellij.platform.scriptDebugger.ui", "intellij.platform.smRunner", "intellij.platform.smRunner.vcs", "intellij.platform.structureView.impl", "intellij.platform.tasks.impl", "intellij.platform.testRunner", "intellij.platform.debugger.impl", "intellij.platform.configurationStore.impl", "intellij.platform.serviceContainer", "intellij.platform.objectSerializer", "intellij.platform.diagnostic", "intellij.platform.diagnostic.telemetry", "intellij.platform.core.ui", "intellij.platform.credentialStore", "intellij.platform.credentialStore.ui", "intellij.platform.rd.community", "intellij.platform.ml.impl", "intellij.remoteDev.util", "intellij.platform.feedback", "intellij.platform.warmup", "intellij.platform.buildScripts.downloader", "intellij.idea.community.build.dependencies", "intellij.platform.usageView.impl", "intellij.platform.ml.impl", ) object PlatformModules { const val PRODUCT_JAR = "product.jar" val CUSTOM_PACK_MODE: Map<String, LibraryPackMode> = linkedMapOf( // jna uses native lib "jna" to LibraryPackMode.STANDALONE_MERGED, "lz4-java" to LibraryPackMode.STANDALONE_MERGED, "jetbrains-annotations-java5" to LibraryPackMode.STANDALONE_SEPARATE_WITHOUT_VERSION_NAME, "intellij-coverage" to LibraryPackMode.STANDALONE_SEPARATE, "github.jnr.ffi" to LibraryPackMode.STANDALONE_SEPARATE, ) fun collectPlatformModules(to: MutableCollection<String>) { to.addAll(PLATFORM_API_MODULES) to.addAll(PLATFORM_IMPLEMENTATION_MODULES) } fun hasPlatformCoverage(productLayout: ProductModulesLayout, enabledPluginModules: Set<String>, context: BuildContext): Boolean { val modules = LinkedHashSet<String>() modules.addAll(productLayout.getIncludedPluginModules(enabledPluginModules)) modules.addAll(PLATFORM_API_MODULES) modules.addAll(PLATFORM_IMPLEMENTATION_MODULES) modules.addAll(productLayout.productApiModules) modules.addAll(productLayout.productImplementationModules) modules.addAll(productLayout.additionalPlatformJars.values()) val coverageModuleName = "intellij.platform.coverage" if (modules.contains(coverageModuleName)) { return true } for (moduleName in modules) { var contains = false JpsJavaExtensionService.dependencies(context.findRequiredModule(moduleName)) .productionOnly() .processModules { module -> if (!contains && module.name == coverageModuleName) { contains = true } } if (contains) { return true } } return false } fun jar(relativeJarPath: String, moduleNames: Collection<String>, productLayout: ProductModulesLayout, layout: PlatformLayout) { for (moduleName in moduleNames) { if (!productLayout.excludedModuleNames.contains(moduleName)) { layout.withModule(moduleName, relativeJarPath) } } } private fun addModule(moduleName: String, productLayout: ProductModulesLayout, layout: PlatformLayout) { if (!productLayout.excludedModuleNames.contains(moduleName)) { layout.withModule(moduleName) } } private fun addModule(moduleName: String, relativeJarPath: String, productLayout: ProductModulesLayout, layout: PlatformLayout) { if (!productLayout.excludedModuleNames.contains(moduleName)) { layout.withModule(moduleName, relativeJarPath) } } @JvmStatic fun createPlatformLayout(productLayout: ProductModulesLayout, hasPlatformCoverage: Boolean, additionalProjectLevelLibraries: SortedSet<ProjectLibraryData>, context: BuildContext): PlatformLayout { val layout = PlatformLayout() // used only in modules that packed into Java layout.withoutProjectLibrary("jps-javac-extension") layout.withoutProjectLibrary("Eclipse") for (platformLayoutCustomizer in productLayout.platformLayoutCustomizers) { platformLayoutCustomizer.accept(layout, context) } val alreadyPackedModules = HashSet<String>() for (entry in productLayout.additionalPlatformJars.entrySet()) { jar(entry.key, entry.value, productLayout, layout) alreadyPackedModules.addAll(entry.value) } for (moduleName in PLATFORM_API_MODULES) { // intellij.platform.core is used in Kotlin and Scala JPS plugins (PathUtil) https://youtrack.jetbrains.com/issue/IDEA-292483 if (!productLayout.excludedModuleNames.contains(moduleName) && moduleName != "intellij.platform.core") { layout.withModule(moduleName, if (moduleName == "intellij.platform.jps.model") "jps-model.jar" else BaseLayout.APP_JAR) } } jar(BaseLayout.APP_JAR, productLayout.productApiModules, productLayout, layout) for (module in productLayout.productImplementationModules) { if (!productLayout.excludedModuleNames.contains(module) && !alreadyPackedModules.contains(module)) { val isRelocated = module == "intellij.xml.dom.impl" || module == "intellij.platform.structuralSearch" || // todo why intellij.tools.testsBootstrap is included to RM? module == "intellij.tools.testsBootstrap" || module == "intellij.platform.duplicates.analysis" if (isRelocated) { layout.withModule(module, BaseLayout.APP_JAR) } else if (!context.productProperties.useProductJar || module.startsWith("intellij.platform.commercial")) { layout.withModule(module, productLayout.mainJarName) } else { layout.withModule(module, PRODUCT_JAR) } } } for (entry in productLayout.moduleExcludes.entrySet()) { layout.moduleExcludes.putValues(entry.key, entry.value) } jar(UTIL_RT_JAR, listOf( "intellij.platform.util.rt", ), productLayout, layout) jar(UTIL_JAR, listOf( "intellij.platform.util.rt.java8", "intellij.platform.util.zip", "intellij.platform.util.classLoader", "intellij.platform.bootstrap", "intellij.platform.util", "intellij.platform.util.text.matching", "intellij.platform.util.base", "intellij.platform.util.diff", "intellij.platform.util.xmlDom", "intellij.platform.util.jdom", "intellij.platform.extensions", "intellij.platform.tracing.rt", "intellij.platform.core", // GeneralCommandLine is used by Scala in JPS plugin "intellij.platform.ide.util.io", "intellij.platform.boot", ), productLayout, layout) jar("externalProcess-rt.jar", listOf( "intellij.platform.externalProcessAuthHelper.rt" ), productLayout, layout) jar(BaseLayout.APP_JAR, PLATFORM_IMPLEMENTATION_MODULES, productLayout, layout) // util.jar is loaded by JVM classloader as part of loading our custom PathClassLoader class - reduce file size jar(BaseLayout.APP_JAR, listOf( "intellij.platform.util.ui", "intellij.platform.util.ex", "intellij.platform.ide.util.io.impl", "intellij.platform.ide.util.netty", ), productLayout, layout) jar(BaseLayout.APP_JAR, listOf( "intellij.relaxng", "intellij.json", "intellij.spellchecker", "intellij.xml.analysis.impl", "intellij.xml.psi.impl", "intellij.xml.structureView.impl", "intellij.xml.impl", "intellij.platform.vcs.impl", "intellij.platform.vcs.dvcs.impl", "intellij.platform.vcs.log.graph.impl", "intellij.platform.vcs.log.impl", "intellij.platform.collaborationTools", "intellij.platform.collaborationTools.auth", "intellij.platform.markdown.utils", "intellij.platform.icons", "intellij.platform.resources", "intellij.platform.resources.en", "intellij.platform.colorSchemes", ), productLayout, layout) jar("stats.jar", listOf( "intellij.platform.statistics", "intellij.platform.statistics.uploader", "intellij.platform.statistics.config", ), productLayout, layout) layout.excludedModuleLibraries.putValue("intellij.platform.credentialStore", "dbus-java") addModule("intellij.platform.statistics.devkit", productLayout, layout) addModule("intellij.platform.objectSerializer.annotations", productLayout, layout) addModule("intellij.java.guiForms.rt", productLayout, layout) addModule("intellij.platform.jps.model.serialization", "jps-model.jar", productLayout, layout) addModule("intellij.platform.jps.model.impl", "jps-model.jar", productLayout, layout) addModule("intellij.platform.externalSystem.rt", "external-system-rt.jar", productLayout, layout) addModule("intellij.platform.cdsAgent", "cds/classesLogAgent.jar", productLayout, layout) if (hasPlatformCoverage) { addModule("intellij.platform.coverage", BaseLayout.APP_JAR, productLayout, layout) } for (libraryName in productLayout.projectLibrariesToUnpackIntoMainJar) { layout.withProjectLibraryUnpackedIntoJar(libraryName, productLayout.mainJarName) } val productPluginSourceModuleName = context.productProperties.applicationInfoModule for (name in getProductPluginContentModules(context, productPluginSourceModuleName)) { layout.withModule(name, BaseLayout.APP_JAR) } layout.projectLibrariesToUnpack.putValue(UTIL_JAR, "Trove4j") layout.projectLibrariesToUnpack.putValue(UTIL_RT_JAR, "ion") for (item in additionalProjectLevelLibraries) { val name = item.libraryName if (!productLayout.projectLibrariesToUnpackIntoMainJar.contains(name) && !layout.projectLibrariesToUnpack.values().contains(name) && !layout.excludedProjectLibraries.contains(name)) { layout.includedProjectLibraries.add(item) } } layout.collectProjectLibrariesFromIncludedModules(context) { lib, module -> val name = lib.name if (module.name == "intellij.platform.buildScripts.downloader" && name == "zstd-jni") { return@collectProjectLibrariesFromIncludedModules } layout.includedProjectLibraries .addOrGet(ProjectLibraryData(name, CUSTOM_PACK_MODE.getOrDefault(name, LibraryPackMode.MERGED))) .dependentModules.computeIfAbsent("core") { mutableListOf() }.add(module.name) } return layout } // result _must_ consistent, do not use Set.of or HashSet here fun getProductPluginContentModules(buildContext: BuildContext, productPluginSourceModuleName: String): Set<String> { var file = buildContext.findFileInModuleSources(productPluginSourceModuleName, "META-INF/plugin.xml") if (file == null) { file = buildContext.findFileInModuleSources(productPluginSourceModuleName, "META-INF/${buildContext.productProperties.platformPrefix}Plugin.xml") if (file == null) { buildContext.messages.warning("Cannot find product plugin descriptor in '$productPluginSourceModuleName' module") return emptySet() } } Files.newInputStream(file).use { val contentList = DocumentBuilderFactory.newDefaultInstance() .newDocumentBuilder() .parse(it, file.toString()) .documentElement .getElementsByTagName("content") if (contentList.length == 0) { return emptySet() } val modules = (contentList.item(0) as Element).getElementsByTagName("module") val result = LinkedHashSet<String>(modules.length) for (i in 0 until modules.length) { result.add((modules.item(i) as Element).getAttribute("name")) } return result } } }
apache-2.0
ea7cfd7512bf64264fe74360f25e898d
37.691293
131
0.717043
4.432588
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/kotlin/KotlinPlugin.kt
1
10825
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle import org.jetbrains.kotlin.tools.projectWizard.Versions import org.jetbrains.kotlin.tools.projectWizard.core.* import org.jetbrains.kotlin.tools.projectWizard.core.entity.* import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.Property import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting import org.jetbrains.kotlin.tools.projectWizard.core.service.* import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildFileIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.RepositoryIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.withIrs import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.ModuleConfigurator import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.buildSystemType import org.jetbrains.kotlin.tools.projectWizard.plugins.pomIR import org.jetbrains.kotlin.tools.projectWizard.plugins.projectPath import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.* import java.nio.file.Path class KotlinPlugin(context: Context) : Plugin(context) { override val path = pluginPath companion object : PluginSettingsOwner() { override val pluginPath = "kotlin" private val moduleDependenciesValidator = settingValidator<List<Module>> { modules -> val allModules = modules.withAllSubModules(includeSourcesets = true).toSet() val allModulePaths = allModules.map(Module::path).toSet() allModules.flatMap { module -> module.dependencies.map { dependency -> val isValidModule = when (dependency) { is ModuleReference.ByPath -> dependency.path in allModulePaths is ModuleReference.ByModule -> dependency.module in allModules } ValidationResult.create(isValidModule) { KotlinNewProjectWizardBundle.message( "plugin.kotlin.setting.modules.error.duplicated.modules", dependency, module.path ) } } }.fold() } val version by property( // todo do not hardcode kind & repository WizardKotlinVersion( Versions.KOTLIN, KotlinVersionKind.M, Repositories.KOTLIN_EAP_MAVEN_CENTRAL, KotlinVersionProviderService.getBuildSystemPluginRepository( KotlinVersionKind.M, devRepository = Repositories.JETBRAINS_KOTLIN_DEV ) ) ) val initKotlinVersions by pipelineTask(GenerationPhase.PREPARE_GENERATION) { title = KotlinNewProjectWizardBundle.message("plugin.kotlin.downloading.kotlin.versions") withAction { val version = service<KotlinVersionProviderService>().getKotlinVersion(projectKind.settingValue) KotlinPlugin.version.update { version.asSuccess() } } } val projectKind by enumSetting<ProjectKind>( KotlinNewProjectWizardBundle.message("plugin.kotlin.setting.project.kind"), GenerationPhase.FIRST_STEP, ) private fun List<Module>.findDuplicatesByName() = groupingBy { it.name }.eachCount().filter { it.value > 1 } val modules by listSetting( KotlinNewProjectWizardBundle.message("plugin.kotlin.setting.modules"), GenerationPhase.SECOND_STEP, Module.parser, ) { validate { value -> val allModules = value.withAllSubModules() val duplicatedModules = allModules.findDuplicatesByName() if (duplicatedModules.isEmpty()) ValidationResult.OK else ValidationResult.ValidationError( KotlinNewProjectWizardBundle.message( "plugin.kotlin.setting.modules.error.duplicated.modules", duplicatedModules.values.first(), duplicatedModules.keys.first() ) ) } validate { value -> value.withAllSubModules().filter { it.kind == ModuleKind.multiplatform }.map { module -> val duplicatedModules = module.subModules.findDuplicatesByName() if (duplicatedModules.isEmpty()) ValidationResult.OK else ValidationResult.ValidationError( KotlinNewProjectWizardBundle.message( "plugin.kotlin.setting.modules.error.duplicated.targets", duplicatedModules.values.first(), duplicatedModules.keys.first() ) ) }.fold() } validate(moduleDependenciesValidator) } val createModules by pipelineTask(GenerationPhase.PROJECT_GENERATION) { runBefore(BuildSystemPlugin.createModules) runAfter(StructurePlugin.createProjectDir) withAction { BuildSystemPlugin.buildFiles.update { val modules = modules.settingValue val (buildFiles) = createBuildFiles(modules) buildFiles.map { it.withIrs(RepositoryIR(DefaultRepository.MAVEN_CENTRAL)) }.asSuccess() } } } val createPluginRepositories by pipelineTask(GenerationPhase.PROJECT_GENERATION) { runBefore(BuildSystemPlugin.createModules) withAction { val version = version.propertyValue if (version.kind.isStable) return@withAction UNIT_SUCCESS val pluginRepository = version.buildSystemPluginRepository(buildSystemType) ?: return@withAction UNIT_SUCCESS BuildSystemPlugin.pluginRepositoreis.addValues(pluginRepository) andThen updateBuildFiles { buildFile -> buildFile.withIrs(RepositoryIR(version.repository)).asSuccess() } } } val createResourceDirectories by booleanSetting("Generate Resource Folders", GenerationPhase.PROJECT_GENERATION) { defaultValue = value(true) } val createSourcesetDirectories by pipelineTask(GenerationPhase.PROJECT_GENERATION) { runAfter(createModules) withAction { fun Path?.createKotlinAndResourceDirectories(moduleConfigurator: ModuleConfigurator): TaskResult<Unit> { if (this == null) return UNIT_SUCCESS return with(service<FileSystemWizardService>()) { createDirectory(this@createKotlinAndResourceDirectories / moduleConfigurator.kotlinDirectoryName) andThen if (createResourceDirectories.settingValue) { createDirectory(this@createKotlinAndResourceDirectories / moduleConfigurator.resourcesDirectoryName) } else { UNIT_SUCCESS } } } forEachModule { moduleIR -> moduleIR.sourcesets.mapSequenceIgnore { sourcesetIR -> sourcesetIR.path.createKotlinAndResourceDirectories(moduleIR.originalModule.configurator) } } } } private fun Writer.createBuildFiles(modules: List<Module>): TaskResult<List<BuildFileIR>> = with( ModulesToIRsConverter( ModulesToIrConversionData( modules, projectPath, StructurePlugin.name.settingValue, version.propertyValue, buildSystemType, pomIR() ) ) ) { createBuildFiles() } } override val settings: List<PluginSetting<*, *>> = listOf( projectKind, modules, createResourceDirectories, ) override val pipelineTasks: List<PipelineTask> = listOf( initKotlinVersions, createModules, createPluginRepositories, createSourcesetDirectories ) override val properties: List<Property<*>> = listOf(version) } enum class ProjectKind( @Nls override val text: String, val supportedBuildSystems: Set<BuildSystemType>, val shortName: String = text, val message: String? = null, ) : DisplayableSettingItem { Singleplatform( KotlinNewProjectWizardBundle.message("project.kind.singleplatform"), supportedBuildSystems = BuildSystemType.values().toSet() ), Multiplatform(KotlinNewProjectWizardBundle.message("project.kind.multiplatform"), supportedBuildSystems = BuildSystemType.ALL_GRADLE), Android(KotlinNewProjectWizardBundle.message("project.kind.android"), supportedBuildSystems = BuildSystemType.ALL_GRADLE), Js(KotlinNewProjectWizardBundle.message("project.kind.kotlin.js"), supportedBuildSystems = BuildSystemType.ALL_GRADLE), COMPOSE( KotlinNewProjectWizardBundle.message("project.kind.compose"), supportedBuildSystems = setOf(BuildSystemType.GradleKotlinDsl), shortName = KotlinNewProjectWizardBundle.message("project.kind.compose.short.name"), message = "uses Kotlin ${Versions.KOTLIN_VERSION_FOR_COMPOSE}" ) } fun List<Module>.withAllSubModules(includeSourcesets: Boolean = false): List<Module> = buildList { fun handleModule(module: Module) { +module if (module.kind != ModuleKind.multiplatform || includeSourcesets && module.kind == ModuleKind.multiplatform ) { module.subModules.forEach(::handleModule) } } forEach(::handleModule) }
apache-2.0
ed733c941fb6e34b86df0ec44f616846
44.868644
158
0.630947
6.084879
false
false
false
false
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/avatar/picker/AvatarPickerFragment.kt
1
9236
package org.thoughtcrime.securesms.avatar.picker import android.Manifest import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.Gravity import android.view.View import android.widget.PopupMenu import android.widget.Toast import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.fragment.app.setFragmentResult import androidx.fragment.app.setFragmentResultListener import androidx.fragment.app.viewModels import androidx.navigation.Navigation import androidx.recyclerview.widget.RecyclerView import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.avatar.Avatar import org.thoughtcrime.securesms.avatar.AvatarBundler import org.thoughtcrime.securesms.avatar.photo.PhotoEditorFragment import org.thoughtcrime.securesms.avatar.text.TextAvatarCreationFragment import org.thoughtcrime.securesms.avatar.vector.VectorAvatarCreationFragment import org.thoughtcrime.securesms.components.ButtonStripItemView import org.thoughtcrime.securesms.components.recyclerview.GridDividerDecoration import org.thoughtcrime.securesms.groups.ParcelableGroupId import org.thoughtcrime.securesms.mediasend.AvatarSelectionActivity import org.thoughtcrime.securesms.mediasend.Media import org.thoughtcrime.securesms.permissions.Permissions import org.thoughtcrime.securesms.util.MappingAdapter import org.thoughtcrime.securesms.util.ViewUtil import org.thoughtcrime.securesms.util.visible import java.util.Objects /** * Primary Avatar picker fragment, displays current user avatar and a list of recently used avatars and defaults. */ class AvatarPickerFragment : Fragment(R.layout.avatar_picker_fragment) { companion object { const val REQUEST_KEY_SELECT_AVATAR = "org.thoughtcrime.securesms.avatar.picker.SELECT_AVATAR" const val SELECT_AVATAR_MEDIA = "org.thoughtcrime.securesms.avatar.picker.SELECT_AVATAR_MEDIA" const val SELECT_AVATAR_CLEAR = "org.thoughtcrime.securesms.avatar.picker.SELECT_AVATAR_CLEAR" private const val REQUEST_CODE_SELECT_IMAGE = 1 } private val viewModel: AvatarPickerViewModel by viewModels(factoryProducer = this::createFactory) private lateinit var recycler: RecyclerView private fun createFactory(): AvatarPickerViewModel.Factory { val args = AvatarPickerFragmentArgs.fromBundle(requireArguments()) val groupId = ParcelableGroupId.get(args.groupId) return AvatarPickerViewModel.Factory(AvatarPickerRepository(requireContext()), groupId, args.isNewGroup, args.groupAvatarMedia) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val toolbar: Toolbar = view.findViewById(R.id.avatar_picker_toolbar) val cameraButton: ButtonStripItemView = view.findViewById(R.id.avatar_picker_camera) val photoButton: ButtonStripItemView = view.findViewById(R.id.avatar_picker_photo) val textButton: ButtonStripItemView = view.findViewById(R.id.avatar_picker_text) val saveButton: View = view.findViewById(R.id.avatar_picker_save) val clearButton: View = view.findViewById(R.id.avatar_picker_clear) recycler = view.findViewById(R.id.avatar_picker_recycler) recycler.addItemDecoration(GridDividerDecoration(4, ViewUtil.dpToPx(16))) val adapter = MappingAdapter() AvatarPickerItem.register(adapter, this::onAvatarClick, this::onAvatarLongClick) recycler.adapter = adapter val avatarViewHolder = AvatarPickerItem.ViewHolder(view) viewModel.state.observe(viewLifecycleOwner) { state -> if (state.currentAvatar != null) { avatarViewHolder.bind(AvatarPickerItem.Model(state.currentAvatar, false)) } clearButton.visible = state.canClear val wasEnabled = saveButton.isEnabled saveButton.isEnabled = state.canSave if (wasEnabled != state.canSave) { val alpha = if (state.canSave) 1f else 0.5f saveButton.animate().cancel() saveButton.animate().alpha(alpha) } val items = state.selectableAvatars.map { AvatarPickerItem.Model(it, it == state.currentAvatar) } val selectedPosition = items.indexOfFirst { it.isSelected } adapter.submitList(items) { if (selectedPosition > -1) recycler.smoothScrollToPosition(selectedPosition) } } toolbar.setNavigationOnClickListener { Navigation.findNavController(it).popBackStack() } cameraButton.setOnIconClickedListener { openCameraCapture() } photoButton.setOnIconClickedListener { openGallery() } textButton.setOnIconClickedListener { openTextEditor(null) } saveButton.setOnClickListener { v -> viewModel.save( { setFragmentResult( REQUEST_KEY_SELECT_AVATAR, Bundle().apply { putParcelable(SELECT_AVATAR_MEDIA, it) } ) Navigation.findNavController(v).popBackStack() }, { setFragmentResult( REQUEST_KEY_SELECT_AVATAR, Bundle().apply { putBoolean(SELECT_AVATAR_CLEAR, true) } ) Navigation.findNavController(v).popBackStack() } ) } clearButton.setOnClickListener { viewModel.clear() } setFragmentResultListener(TextAvatarCreationFragment.REQUEST_KEY_TEXT) { _, bundle -> val text = AvatarBundler.extractText(bundle) viewModel.onAvatarEditCompleted(text) } setFragmentResultListener(VectorAvatarCreationFragment.REQUEST_KEY_VECTOR) { _, bundle -> val vector = AvatarBundler.extractVector(bundle) viewModel.onAvatarEditCompleted(vector) } setFragmentResultListener(PhotoEditorFragment.REQUEST_KEY_EDIT) { _, bundle -> val photo = AvatarBundler.extractPhoto(bundle) viewModel.onAvatarEditCompleted(photo) } } override fun onResume() { super.onResume() ViewUtil.hideKeyboard(requireContext(), requireView()) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_CODE_SELECT_IMAGE && resultCode == Activity.RESULT_OK && data != null) { val media: Media = Objects.requireNonNull(data.getParcelableExtra(AvatarSelectionActivity.EXTRA_MEDIA)) viewModel.onAvatarPhotoSelectionCompleted(media) } else { super.onActivityResult(requestCode, resultCode, data) } } private fun onAvatarClick(avatar: Avatar, isSelected: Boolean) { if (isSelected) { openEditor(avatar) } else { viewModel.onAvatarSelectedFromGrid(avatar) } } private fun onAvatarLongClick(anchorView: View, avatar: Avatar): Boolean { val menuRes = when (avatar) { is Avatar.Photo -> R.menu.avatar_picker_context is Avatar.Text -> R.menu.avatar_picker_context is Avatar.Vector -> return true is Avatar.Resource -> return true } val popup = PopupMenu(context, anchorView, Gravity.TOP) popup.menuInflater.inflate(menuRes, popup.menu) popup.setOnMenuItemClickListener { menuItem -> when (menuItem.itemId) { R.id.action_delete -> viewModel.delete(avatar) } true } popup.show() return true } fun openEditor(avatar: Avatar) { when (avatar) { is Avatar.Photo -> openPhotoEditor(avatar) is Avatar.Resource -> throw UnsupportedOperationException() is Avatar.Text -> openTextEditor(avatar) is Avatar.Vector -> openVectorEditor(avatar) } } fun openPhotoEditor(photo: Avatar.Photo) { Navigation.findNavController(requireView()) .navigate(AvatarPickerFragmentDirections.actionAvatarPickerFragmentToAvatarPhotoEditorFragment(AvatarBundler.bundlePhoto(photo))) } fun openVectorEditor(vector: Avatar.Vector) { Navigation.findNavController(requireView()) .navigate(AvatarPickerFragmentDirections.actionAvatarPickerFragmentToVectorAvatarCreationFragment(AvatarBundler.bundleVector(vector))) } fun openTextEditor(text: Avatar.Text?) { val bundle = if (text != null) AvatarBundler.bundleText(text) else null Navigation.findNavController(requireView()) .navigate(AvatarPickerFragmentDirections.actionAvatarPickerFragmentToTextAvatarCreationFragment(bundle)) } fun openCameraCapture() { Permissions.with(this) .request(Manifest.permission.CAMERA) .ifNecessary() .onAllGranted { val intent = AvatarSelectionActivity.getIntentForCameraCapture(requireContext()) startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE) } .onAnyDenied { Toast.makeText(requireContext(), R.string.AvatarSelectionBottomSheetDialogFragment__taking_a_photo_requires_the_camera_permission, Toast.LENGTH_SHORT) .show() } .execute() } fun openGallery() { Permissions.with(this) .request(Manifest.permission.READ_EXTERNAL_STORAGE) .ifNecessary() .onAllGranted { val intent = AvatarSelectionActivity.getIntentForGallery(requireContext()) startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE) } .onAnyDenied { Toast.makeText(requireContext(), R.string.AvatarSelectionBottomSheetDialogFragment__viewing_your_gallery_requires_the_storage_permission, Toast.LENGTH_SHORT) .show() } .execute() } }
gpl-3.0
85c1ba79ecbac160f1bdd9cefd87cb6f
37.00823
165
0.738956
4.85084
false
false
false
false
darkoverlordofdata/entitas-kotlin
core/src/com/darkoverlordofdata/entitas/demo/systems/SpriteRenderSystem.kt
1
2164
package com.darkoverlordofdata.entitas.demo.systems /** * SpriteRenderSystem * * Renders all the sprites */ import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.utils.viewport.FillViewport import com.darkoverlordofdata.entitas.* import com.darkoverlordofdata.entitas.demo.* class SpriteRenderSystem(game: GameScene, pool: Pool) : IExecuteSystem { val pool = pool val group = pool.getGroup(Matcher.allOf(Matcher.Position, Matcher.View)) val scale = .8f //2f/3f val width = game.width.toFloat() val height = game.height.toFloat() val pixelFactor = game.pixelFactor val batch = SpriteBatch() val camera = game.camera val viewport = FillViewport(width/pixelFactor, height/pixelFactor, camera) val background = O2dLibrary.sprites.createSprite(O2dLibrary.getResource("background")) init { group.setSort({entities: Array<Entity> -> entities.sortBy { e:Entity -> e.layer.ordinal } }) viewport.apply() camera.position.set(width/(pixelFactor*2f), height/(pixelFactor*2f), 0f) camera.update() } override fun execute() { Gdx.gl.glClearColor(0f, 0f, 0f, 1f) Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT) batch.projectionMatrix = camera.combined batch.begin() batch.draw(background, 0f, 0f, width, height) for (entity in group.entities) { val sprite = entity.view.sprite if (sprite != null) { if (entity.hasScale) sprite.setScale(entity.scale.x * scale, entity.scale.y * scale) else sprite.setScale(scale) val x = sprite.width / 2f val y = sprite.height / 2f sprite.setPosition(entity.position.x - x, entity.position.y - y) sprite.draw(batch) } } batch.end() } fun resize(width: Int, height: Int) { viewport.update(width,height) camera.position.set(camera.viewportWidth/2f, camera.viewportHeight/2f, 0f) } }
mit
a61407ed3f104e42bbf89c93fc5a95ed
29.928571
90
0.629852
3.927405
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/card/classic/UnauthorizedClassicSector.kt
1
1692
/* * UnauthorizedClassicSector.kt * * Copyright 2012-2015 Eric Butler <[email protected]> * Copyright 2016-2019 Michael Farrell <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.card.classic import au.id.micolous.metrodroid.card.UnauthorizedException import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.hexString import kotlinx.serialization.Serializable import kotlinx.serialization.Transient @Serializable class UnauthorizedClassicSector (override val raw: ClassicSectorRaw): ClassicSector() { constructor() : this(ClassicSectorRaw(blocks = emptyList(), keyA = null, keyB = null, error = "Unauthorized", isUnauthorized = true)) @Transient override val blocks: List<ClassicBlock> get() = throw UnauthorizedException() override fun getRawData(idx: Int) = ListItem(Localizer.localizeString(R.string.unauthorized_sector_title_format, idx.hexString)) }
gpl-3.0
671958e1f6b0094e48829d388f179f59
39.285714
104
0.760638
4.240602
false
false
false
false
rubengees/ktask
sample-common/src/main/kotlin/com/rubengees/ktask/sample/RepositoryInfo.kt
1
597
package com.rubengees.ktask.sample import com.squareup.moshi.Json /** * TODO: Describe class * * @author Ruben Gees */ class RepositoryInfo(@field:Json(name = "items") val repositories: List<Repository>) { class Repository( @field:Json(name = "id") val id: Long, @field:Json(name = "name") val name: String, @field:Json(name = "owner") val owner: Owner, @field:Json(name = "stargazers_count") val stars: Int, @field:Json(name = "html_url") val url: String ) class Owner(@field:Json(name = "login") val name: String) }
mit
abc0760748cb8b830612666721dacc5b
28.85
86
0.613065
3.47093
false
false
false
false
GunoH/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/LibraryLicense.kt
4
7697
// 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.intellij.build /** * Describes a library which is included into distribution of an IntelliJ-based IDE. This information is used to show list of Third-party * software in About popup and on the product download page. */ data class LibraryLicense( /** * Presentable full name of the library. If {@code null} {@link #libraryName} will be used instead. */ val name: String? = null, /** * URL of the library site, may be {@code null} if the library doesn't have a site */ val url: String? = null, /** * Version of the library. If {@link #libraryName} points to a Maven library version is taken from the library configuration so it must * not be specified explicitly. */ val version: String? = null, /** * Name of the library in IDEA Project Configuration (for unnamed module libraries it's a name of its JAR file). May be {@code null} if * the library isn't explicitly added to dependencies of a module, in that case {@link #attachedTo} must be specified instead. This property * is used to automatically generate list of libraries used in a particular project. */ val libraryName: String? = null, /** * Names of additional libraries in IDEA Project Configuration which are associated with the given library. It makes sense to use this * property only for unnamed module library consisting of several JAR files, but even in such cases consider merging such JARs into a single * module library and giving it a name. */ val additionalLibraryNames: List<String> = emptyList(), /** * Specifies name of the module in IDEA Project configuration the library is implicitly attached to. It makes sense to use this property * only for libraries which cannot be added to a module dependencies as a regular dependency (e.g. if it isn't a Java library). For regular * cases specify {@link #libraryName} instead. */ val attachedTo: String? = null, /** * Set to {@code true} if this entry describes license for a transitive dependency included into the library specified by {@link #libraryName} */ val transitiveDependency: Boolean = false, /** * Type of a license (e.g. {@code 'Apache 2.0'}) */ val license: String? = null, /** * URL of a page on the library site (or a generic site) containing the license text, may be {@code null} for standard licenses * (see {@link #PREDEFINED_LICENSE_URLS}) or if there is no such page. */ val licenseUrl: String? = null, ) { init { require(name != null || libraryName != null) { "name or libraryName must be set" } } companion object { private const val APACHE_LICENSE_URL = "https://www.apache.org/licenses/LICENSE-2.0" private val PREDEFINED_LICENSE_URLS = mapOf("Apache 2.0" to APACHE_LICENSE_URL) @JvmStatic val JETBRAINS_OWN = "JetBrains" /** * Denotes version of library built from custom revision */ const val CUSTOM_REVISION = "custom revision" /** * Use this method only for JetBrains's own libraries which are available as part of IntelliJ-based IDEs only so there is no way to * give link to their sites. For other libraries please fill all necessary fields of {@link LibraryLicense} instead of using this method. */ @JvmStatic fun jetbrainsLibrary(libraryName: String): LibraryLicense { return LibraryLicense( libraryName = libraryName, license = JETBRAINS_OWN, ) } } fun getLibraryNames(): List<String> = listOfNotNull(libraryName) + additionalLibraryNames val presentableName: String get() = name ?: libraryName!! fun getLibraryLicenseUrl(): String? = licenseUrl ?: PREDEFINED_LICENSE_URLS.get(license) @Deprecated("Please specify exact URL for the Apache license, pointing to the repo of the dependency") fun apache(): LibraryLicense { require(license == null) { "No need to specify 'license' for Apache 2.0" } require(licenseUrl?.contains("apache.org/licenses") != true) { "No need to specify default 'licenseUrl' for Apache 2.0" } return copy( license = "Apache 2.0", licenseUrl = licenseUrl ?: APACHE_LICENSE_URL, ) } fun apache(licenseUrl: String): LibraryLicense { require(license == null) { "No need to specify 'license' for Apache 2.0" } return copy( license = "Apache 2.0", licenseUrl = licenseUrl ) } @Deprecated("Please specify exact URL for the BSD license, pointing to the repo of the dependency") fun simplifiedBsd(): LibraryLicense { require(license == null) { "No need to specify 'license' for Simplified BSD" } require(licenseUrl?.contains("opensource.org/licenses") != true) { "No need to specify default 'licenseUrl' for Simplified BSD" } return copy( license = "BSD 2-Clause", licenseUrl = licenseUrl ?: "https://opensource.org/licenses/BSD-2-Clause", ) } fun simplifiedBsd(licenseUrl: String): LibraryLicense { require(license == null) { "No need to specify 'license' for Simplified BSD" } return copy( license = "BSD 2-Clause", licenseUrl = licenseUrl ) } @Deprecated("Please specify exact URL for the BSD license, pointing to the repo or Web site of the dependency") fun newBsd(): LibraryLicense { require(license == null) { "No need to specify 'license' for New BSD" } require(licenseUrl?.contains("opensource.org/licenses") != true) { "No need to specify default 'licenseUrl' for New BSD" } return copy( license = "BSD 3-Clause", licenseUrl = licenseUrl ?: "https://opensource.org/licenses/BSD-3-Clause", ) } fun newBsd(licenseUrl: String): LibraryLicense { require(license == null) { "No need to specify 'license' for New BSD" } return copy( license = "BSD 3-Clause", licenseUrl = licenseUrl ) } @Deprecated("Please specify exact URL for the MIT license, pointing to the repo or Web site of the dependency") fun mit(): LibraryLicense { require(license == null) { "No need to specify 'license' for MIT" } require(licenseUrl?.contains("opensource.org/licenses") != true) { "No need to specify default 'licenseUrl' for MIT" } return copy( license = "MIT", licenseUrl = licenseUrl ?: "https://opensource.org/licenses/MIT", ) } fun mit(licenseUrl: String): LibraryLicense { require(license == null) { "No need to specify 'license' for MIT" } return copy( license = "MIT", licenseUrl = licenseUrl ) } fun eplV1(): LibraryLicense = epl(1) fun eplV2(): LibraryLicense = epl(2) fun eplV1(licenseUrl: String): LibraryLicense = epl(licenseUrl, 1) fun eplV2(licenseUrl: String): LibraryLicense = epl(licenseUrl, 2) private fun epl(licenseUrl: String, v: Int): LibraryLicense { require(license == null) { "No need to specify 'license' for EPL" } return copy( license = "Eclipse Public License ${v}.0", licenseUrl = licenseUrl ) } private fun epl(v: Int): LibraryLicense { require(v == 1 || v == 2) { "Version must be either 1 or 2 for Eclipse Public License" } require(license == null) { "No need to specify 'license' for Eclipse Public License" } require(licenseUrl?.contains("eclipse.org") != true) { "No need to specify default 'licenseUrl' for Eclipse Public License" } return copy( license = "Eclipse Public License ${v}.0", licenseUrl = licenseUrl ?: (if (v == 1) "https://www.eclipse.org/org/documents/epl-v10.html" else "https://www.eclipse.org/legal/epl-2.0") ) } }
apache-2.0
bab5fc2ae0670d609d2062130b252f00
38.675258
144
0.681954
4.231446
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/navigation/impl/gtdu.kt
8
3869
// 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.codeInsight.navigation.impl import com.intellij.codeInsight.navigation.CtrlMouseData import com.intellij.codeInsight.navigation.CtrlMouseInfo import com.intellij.find.actions.PsiTargetVariant import com.intellij.find.actions.SearchTargetVariant import com.intellij.find.actions.TargetVariant import com.intellij.find.usages.impl.symbolSearchTarget import com.intellij.model.psi.PsiSymbolService import com.intellij.model.psi.impl.TargetData import com.intellij.model.psi.impl.declaredReferencedData import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.util.SmartList internal fun gotoDeclarationOrUsages(file: PsiFile, offset: Int): GTDUActionData? { return processInjectionThenHost(file, offset, ::gotoDeclarationOrUsagesInner) } /** * "Go To Declaration Or Usages" action data */ internal interface GTDUActionData { @Suppress("DEPRECATION") @Deprecated("Unused in v2 implementation") fun ctrlMouseInfo(): CtrlMouseInfo? fun ctrlMouseData(): CtrlMouseData? fun result(): GTDUActionResult? } /** * "Go To Declaration Or Usages" action result */ internal sealed class GTDUActionResult { /** * Go To Declaration */ class GTD(val navigationActionResult: NavigationActionResult) : GTDUActionResult() /** * Show Usages */ class SU(val targetVariants: List<TargetVariant>) : GTDUActionResult() { init { require(targetVariants.isNotEmpty()) } } } private fun gotoDeclarationOrUsagesInner(file: PsiFile, offset: Int): GTDUActionData? { return fromDirectNavigation(file, offset)?.toGTDUActionData() ?: fromTargetData(file, offset) } private fun fromTargetData(file: PsiFile, offset: Int): GTDUActionData? { val (declaredData, referencedData) = declaredReferencedData(file, offset) ?: return null return referencedData?.toGTDActionData(file.project)?.toGTDUActionData() // GTD of referenced symbols ?: (referencedData)?.let { ShowUsagesGTDUActionData(file.project, it) } // SU of referenced symbols if nowhere to navigate ?: declaredData?.let { ShowUsagesGTDUActionData(file.project, it) } // SU of declared symbols } internal fun GTDActionData.toGTDUActionData(): GTDUActionData? { val gtdActionResult = result() ?: return null // nowhere to navigate return object : GTDUActionData { @Suppress("DEPRECATION", "DeprecatedCallableAddReplaceWith") @Deprecated("Unused in v2 implementation") override fun ctrlMouseInfo(): CtrlMouseInfo? = [email protected]() override fun ctrlMouseData(): CtrlMouseData? = [email protected]() override fun result(): GTDUActionResult = GTDUActionResult.GTD(gtdActionResult) } } private class ShowUsagesGTDUActionData(private val project: Project, private val targetData: TargetData) : GTDUActionData { @Suppress("DEPRECATION") @Deprecated("Unused in v2 implementation") override fun ctrlMouseInfo(): CtrlMouseInfo? = targetData.ctrlMouseInfo() override fun ctrlMouseData(): CtrlMouseData? = targetData.ctrlMouseData(project) override fun result(): GTDUActionResult? = searchTargetVariants(project, targetData).let { targets -> if (targets.isEmpty()) { null } else { GTDUActionResult.SU(targets) } } } private fun searchTargetVariants(project: Project, data: TargetData): List<TargetVariant> { return data.targets.mapNotNullTo(SmartList()) { (symbol, _) -> val psi: PsiElement? = PsiSymbolService.getInstance().extractElementFromSymbol(symbol) if (psi == null) { symbolSearchTarget(project, symbol)?.let(::SearchTargetVariant) } else { PsiTargetVariant(psi) } } }
apache-2.0
a69e27a48f3f06610e62e43155e9f9e9
34.824074
131
0.751615
4.735618
false
false
false
false
GunoH/intellij-community
plugins/completion-ml-ranking/src/com/intellij/completion/ml/util/RelevanceUtil.kt
9
4511
package com.intellij.completion.ml.util import com.intellij.codeInsight.completion.ml.MLWeigherUtil import com.intellij.completion.ml.features.MLCompletionWeigher import com.intellij.completion.ml.sorting.FeatureUtils import com.intellij.internal.statistic.utils.getPluginInfo import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.Pair import com.intellij.openapi.util.text.StringUtil object RelevanceUtil { private val LOG = logger<RelevanceUtil>() private const val NULL_TEXT = "null" private val IGNORED_FACTORS = setOf("kotlin.byNameAlphabetical", "scalaMethodCompletionWeigher", "unresolvedOnTop", "alphabetic", "TabNineLookupElementWeigher", "AixLookupElementWeigher", "CodotaCompletionWeigher", "CodotaCompletionWeigher_Kotlin", "EmcSuggestionsWeigher", "codotaPriorityWeigher", "com.zlabs.code.completion.ScaCompletionWeigher", "com.aliyun.odps.studio.intellij.compiler.codecompletion.OdpsqlCompletionWeigher") private val weighersClassesCache = HashMap<String, Boolean>() /* * First map contains only features affecting default elements ordering * */ fun asRelevanceMaps(relevanceObjects: List<Pair<String, Any?>>): kotlin.Pair<MutableMap<String, Any>, MutableMap<String, Any>> { val relevanceMap = HashMap<String, Any>() val additionalMap = mutableMapOf<String, Any>() for (pair in relevanceObjects) { val name = pair.first.normalized() val value = pair.second if (name in IGNORED_FACTORS || value == null) continue when (name) { "proximity" -> relevanceMap.addProximityValues("prox", value) "kotlin.proximity" -> relevanceMap.addProximityValues("kt_prox", value) "swiftSymbolProximity" -> { relevanceMap[name] = value // while this feature is used in actual models relevanceMap.addProximityValues("swift_prox", value) } "kotlin.callableWeight" -> relevanceMap.addDataClassValues("kotlin.callableWeight", value.toString()) "ml_weigh" -> additionalMap.addMlFeatures("ml", value) else -> if (acceptValue(value) || name == FeatureUtils.ML_RANK) relevanceMap[name] = value } } return kotlin.Pair(relevanceMap, additionalMap) } private fun acceptValue(value: Any): Boolean { return value is Number || value is Boolean || value.javaClass.isEnum || isJetBrainsClass(value.javaClass) } private fun isJetBrainsClass(aClass: Class<*>): Boolean { return weighersClassesCache.getOrPut(aClass.name) { getPluginInfo(aClass).type.isDevelopedByJetBrains() } } private fun String.normalized(): String { return substringBefore('@') } private fun MutableMap<String, Any>.addMlFeatures(prefix: String, comparable: Any) { if (comparable !is MLCompletionWeigher.DummyComparable) { LOG.error("Unexpected value type of `$prefix`: ${comparable.javaClass.simpleName}") return } for ((name, value) in comparable.mlFeatures) { this["${prefix}_$name"] = value } } private fun MutableMap<String, Any>.addProximityValues(prefix: String, proximity: Any) { val weights = MLWeigherUtil.extractWeightsOrNull(proximity) if (weights == null) { LOG.error("Unexpected comparable type for `$prefix` weigher: ${proximity.javaClass.simpleName}") return } for ((name, weight) in weights) { this["${prefix}_$name"] = weight } } private fun MutableMap<String, Any>.addDataClassValues(featureName: String, dataClassString: String) { if (StringUtil.countChars(dataClassString, '(') != 1) { this[featureName] = dataClassString } else { this.addProperties(featureName, dataClassString.substringAfter('(').substringBeforeLast(')').split(',')) } } private fun MutableMap<String, Any>.addProperties(prefix: String, properties: List<String>) { properties.forEach { if (it.isNotBlank()) { val key = "${prefix}_${it.substringBefore('=').trim()}" val value = it.substringAfter('=').trim() if (value == NULL_TEXT) return@forEach this[key] = value } } } }
apache-2.0
6bf265a3be74bc41b9895054907391da
39.648649
130
0.641321
4.694069
false
false
false
false
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/util/CachingGHUserAvatarLoader.kt
7
2846
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.util import com.github.benmanes.caffeine.cache.Caffeine import com.intellij.collaboration.async.CompletableFutureUtil.submitIOTask import com.intellij.collaboration.util.ProgressIndicatorsProvider import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.LowMemoryWatcher import com.intellij.util.ImageLoader import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubApiRequests import java.awt.Image import java.awt.image.BufferedImage import java.time.Duration import java.time.temporal.ChronoUnit import java.util.concurrent.CompletableFuture class CachingGHUserAvatarLoader : Disposable { private val indicatorProvider = ProgressIndicatorsProvider().also { Disposer.register(this, it) } private val avatarCache = Caffeine.newBuilder() .expireAfterAccess(Duration.of(5, ChronoUnit.MINUTES)) .build<String, CompletableFuture<Image?>>() init { LowMemoryWatcher.register(Runnable { avatarCache.invalidateAll() }, this) } fun requestAvatar(requestExecutor: GithubApiRequestExecutor, url: String): CompletableFuture<Image?> = avatarCache.get(url) { ProgressManager.getInstance().submitIOTask(indicatorProvider) { loadAndDownscale(requestExecutor, it, url, STORED_IMAGE_SIZE) } } private fun loadAndDownscale(requestExecutor: GithubApiRequestExecutor, indicator: ProgressIndicator, url: String, maximumSize: Int): Image? { try { val loadedImage = requestExecutor.execute(indicator, GithubApiRequests.CurrentUser.getAvatar(url)) return if (loadedImage.width <= maximumSize && loadedImage.height <= maximumSize) loadedImage else ImageLoader.scaleImage(loadedImage, maximumSize) as BufferedImage } catch (e: ProcessCanceledException) { return null } catch (e: Exception) { LOG.debug("Error loading image from $url", e) return null } } override fun dispose() {} companion object { private val LOG = logger<CachingGHUserAvatarLoader>() @JvmStatic fun getInstance(): CachingGHUserAvatarLoader = service() private const val MAXIMUM_ICON_SIZE = 40 // store images at maximum used size with maximum reasonable scale to avoid upscaling (3 for system scale, 2 for user scale) private const val STORED_IMAGE_SIZE = MAXIMUM_ICON_SIZE * 6 } }
apache-2.0
32929fdf3326da50601115a3bf390b11
39.098592
140
0.775123
4.69637
false
false
false
false
jk1/intellij-community
plugins/stats-collector/features/src/com/jetbrains/completion/feature/impl/BinaryFeatureImpl.kt
4
1904
/* * 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.jetbrains.completion.feature.impl import com.jetbrains.completion.feature.BinaryFeature import com.jetbrains.completion.feature.ex.UnexpectedBinaryValueException /** * @author Vitaliy.Bibaev */ class BinaryFeatureImpl(override val name: String, override val index: Int, override val undefinedIndex: Int, override val defaultValue: Double, private val firstValue: BinaryFeature.BinaryValueDescriptor, private val secondValue: BinaryFeature.BinaryValueDescriptor) : BinaryFeature { private fun transform(value: String): Double = when (value) { firstValue.key -> firstValue.mapped secondValue.key -> secondValue.mapped else -> throw UnexpectedBinaryValueException(name, value, setOf(firstValue.key, secondValue.key)) } override val availableValues: Pair<String, String> = firstValue.key to secondValue.key override fun process(value: Any, featureArray: DoubleArray) { featureArray[undefinedIndex] = 0.0 featureArray[index] = transform(value.toString()) } override fun setDefaults(featureArray: DoubleArray) { featureArray[undefinedIndex] = 1.0 featureArray[index] = defaultValue } }
apache-2.0
821e0dcbd446b11994621e6b407f1c77
38.6875
105
0.70063
4.76
false
false
false
false
yongce/AndroidLib
baseLib/src/main/java/me/ycdev/android/lib/common/ipc/ServiceConnector.kt
1
11996
package me.ycdev.android.lib.common.ipc import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.content.pm.ApplicationInfo import android.content.pm.ResolveInfo import android.os.Handler import android.os.IBinder import android.os.Looper import android.os.Message import android.os.SystemClock import androidx.annotation.IntDef import androidx.annotation.VisibleForTesting import androidx.annotation.WorkerThread import me.ycdev.android.lib.common.manager.ListenerManager import me.ycdev.android.lib.common.utils.Preconditions import timber.log.Timber import java.util.concurrent.atomic.AtomicInteger /** * @constructor * @param serviceName Used to print logs only. * @param connectLooper The looper used to connect/reconnect target Service. * By default, it's the main looper. */ abstract class ServiceConnector<IServiceInterface> protected constructor( cxt: Context, protected var serviceName: String, val connectLooper: Looper = Looper.getMainLooper() ) { protected var appContext: Context = cxt.applicationContext protected var stateListeners = ListenerManager<ConnectStateListener>(true) private val connectWaitLock = Any() private val state = AtomicInteger(STATE_DISCONNECTED) private var connectStartTime: Long = 0 private var serviceConnection: ServiceConnection? = null var service: IServiceInterface? = null private set @ConnectState val connectState: Int get() = state.get() /** * Get Intent to bind the target service. */ protected abstract fun getServiceIntent(): Intent /** * Convert the IBinder object to interface. */ protected abstract fun asInterface(service: IBinder): IServiceInterface protected open fun validatePermission(permission: String?): Boolean { return true // Skip to validate permission by default } fun isServiceExist(): Boolean { val intent = getServiceIntent() val servicesList = appContext.packageManager.queryIntentServices(intent, 0) return servicesList.size > 0 && selectTargetService(servicesList) != null } /** * Sub class can rewrite the candidate services select logic. */ @VisibleForTesting internal fun selectTargetService(servicesList: List<ResolveInfo>): ComponentName? { Timber.tag(TAG).i("[%s] Candidate services: %d", serviceName, servicesList.size) Preconditions.checkArgument(servicesList.isNotEmpty()) var serviceInfo = servicesList[0].serviceInfo for (info in servicesList) { if (!validatePermission(info.serviceInfo.permission)) { Timber.tag(TAG).w( "Skip not-matched permission candidate: %s, perm: %s", info.serviceInfo.name, info.serviceInfo.permission ) continue } if (info.serviceInfo.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM == ApplicationInfo.FLAG_SYSTEM) { serviceInfo = info.serviceInfo // search the system candidate Timber.tag(TAG).i("[%s] Service from system found and select it", serviceName) break } } return if (validatePermission(serviceInfo.permission)) { ComponentName(serviceInfo.packageName, serviceInfo.name) } else null } /** * Add a connect state listener, using [ListenerManager] to manager listeners. * Callbacks will be invoked in [.getConnectLooper] thread. */ fun addListener(listener: ConnectStateListener) { stateListeners.addListener(listener) } fun removeListener(listener: ConnectStateListener) { stateListeners.removeListener(listener) } fun connect() { connectServiceIfNeeded(false) } fun disconnect() { Timber.tag(TAG).i("[%s] disconnect service...", serviceName) connectHandler.removeMessages(MSG_CONNECT_TIMEOUT_CHECK) connectHandler.removeMessages(MSG_RECONNECT) connectHandler.removeMessages(MSG_NOTIFY_LISTENERS) service = null if (serviceConnection != null) { appContext.unbindService(serviceConnection!!) serviceConnection = null } updateConnectState(STATE_DISCONNECTED) } private fun connectServiceIfNeeded(rebind: Boolean) { if (service != null) { Timber.tag(TAG).d("[%s] service is connected", serviceName) return } if (!rebind) { if (!state.compareAndSet(STATE_DISCONNECTED, STATE_CONNECTING)) { Timber.tag(TAG).d("[%s] Service is under connecting", serviceName) return } updateConnectState(STATE_CONNECTING) } connectStartTime = SystemClock.elapsedRealtime() val intent = getServiceIntent() val servicesList = appContext.packageManager.queryIntentServices(intent, 0) if (servicesList.size == 0) { Timber.tag(TAG).w("[%s] no service component available, cannot connect", serviceName) updateConnectState(STATE_DISCONNECTED) return } val candidateService = selectTargetService(servicesList) if (candidateService == null) { Timber.tag(TAG) .w("[%s] no expected service component found, cannot connect", serviceName) updateConnectState(STATE_DISCONNECTED) return } // must set explicit component before bind/start service intent.component = candidateService serviceConnection = object : ServiceConnection { private var mConnectLost = false override fun onServiceConnected(cn: ComponentName, service: IBinder) { Timber.tag(TAG).i( "[%s] service connected, cn: %s, mConnectLost: %s", serviceName, cn, mConnectLost ) if (!mConnectLost) { // update 'mService' first, and then update the connect state and notify [email protected] = asInterface(service) connectHandler.removeMessages(MSG_CONNECT_TIMEOUT_CHECK) updateConnectState(STATE_CONNECTED) } // else: waiting for reconnecting using new ServiceConnection object } override fun onServiceDisconnected(cn: ComponentName) { Timber.tag(TAG).i( "[%s] service disconnected, cn: %s, mConnectLost: %s", serviceName, cn, mConnectLost ) if (mConnectLost) { return } // Unbind the service and bind it again later mConnectLost = true disconnect() connectHandler.sendEmptyMessageDelayed(MSG_RECONNECT, 1000) } } Timber.tag(TAG).i("[%s] connecting service...", serviceName) if (!appContext.bindService(intent, serviceConnection!!, Context.BIND_AUTO_CREATE)) { Timber.tag(TAG).w("[%s] cannot connect", serviceName) updateConnectState(STATE_DISCONNECTED) } else { connectHandler.removeMessages(MSG_CONNECT_TIMEOUT_CHECK) connectHandler.sendEmptyMessageDelayed( MSG_CONNECT_TIMEOUT_CHECK, CONNECT_TIMEOUT_CHECK_INTERVAL ) } } private fun updateConnectState(@ConnectState newState: Int) { if (newState != STATE_CONNECTING) { state.set(newState) } connectHandler.obtainMessage(MSG_NOTIFY_LISTENERS, newState, 0).sendToTarget() } /** * Waiting for the service connected with timeout. * * @param timeoutMillis Timeout in milliseconds to wait for the service connected. * 0 means no waiting and -1 means no timeout. */ @WorkerThread fun waitForConnected(timeoutMillis: Long = -1) { Preconditions.checkNonMainThread() if (service != null) { Timber.tag(TAG).d("[%s] already connected", serviceName) return } synchronized(connectWaitLock) { connect() var sleepTime: Long = 50 var timeElapsed: Long = 0 while (true) { val connectState = state.get() Timber.tag(TAG).d( "[%s] checking, service: %s, state: %d, time: %d/%d", serviceName, service, connectState, timeElapsed, timeoutMillis ) if (connectState == STATE_CONNECTED || connectState == STATE_DISCONNECTED) { break } if (timeoutMillis in 0..timeElapsed) { break } connect() try { Thread.sleep(sleepTime) } catch (e: InterruptedException) { Timber.tag(TAG).w(e, "interrupted") break } timeElapsed += sleepTime sleepTime *= 2 if (sleepTime > 1000) { sleepTime = 1000 } } } } private val connectHandler = object : Handler(connectLooper) { override fun handleMessage(msg: Message) { when (msg.what) { MSG_RECONNECT -> { Timber.tag(TAG).d("[%s] delayed reconnect fires...", serviceName) connect() } MSG_NOTIFY_LISTENERS -> { @ConnectState val newState = msg.arg1 Timber.tag(TAG).d("State changed: %s", strConnectState(newState)) stateListeners.notifyListeners { listener -> listener.onStateChanged(newState) } } MSG_CONNECT_TIMEOUT_CHECK -> { Timber.tag(TAG).d("checking connect timeout") val curState = state.get() if (SystemClock.elapsedRealtime() - connectStartTime >= FORCE_REBIND_TIME) { Timber.tag(TAG).d( "[%s] connect timeout, state: %s", serviceName, curState ) if (curState == STATE_CONNECTING) { // force to rebind the service connectServiceIfNeeded(true) } } else { if (curState == STATE_CONNECTING) { this.sendEmptyMessageDelayed( MSG_CONNECT_TIMEOUT_CHECK, CONNECT_TIMEOUT_CHECK_INTERVAL ) } } } } } } @Retention(AnnotationRetention.SOURCE) @IntDef(STATE_DISCONNECTED, STATE_CONNECTING, STATE_CONNECTED) annotation class ConnectState companion object { private const val TAG = "ServiceConnector" const val STATE_DISCONNECTED = 1 const val STATE_CONNECTING = 2 const val STATE_CONNECTED = 3 private const val MSG_RECONNECT = 1 private const val MSG_NOTIFY_LISTENERS = 2 private const val MSG_CONNECT_TIMEOUT_CHECK = 3 private const val CONNECT_TIMEOUT_CHECK_INTERVAL: Long = 5000 // 5s private const val FORCE_REBIND_TIME: Long = 30 * 1000L // 30 seconds fun strConnectState(state: Int): String { return when (state) { STATE_DISCONNECTED -> "disconnected" STATE_CONNECTING -> "connecting" STATE_CONNECTED -> "connected" else -> "unknown" } } } }
apache-2.0
5c5579e032fa263f17b9e28c80a35377
36.139319
120
0.583194
5.386619
false
false
false
false
DarkToast/AxonSpring
src/main/kotlin/de/tarent/axon/ports/rest/QueryController.kt
1
2486
package de.tarent.axon.ports.rest import com.fasterxml.jackson.annotation.JsonIgnore import de.tarent.axon.query.Game import de.tarent.axon.query.GameRepository import org.springframework.http.ResponseEntity import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.servlet.support.ServletUriComponentsBuilder import java.net.URI import java.util.* @Controller class QueryController(private val repository: GameRepository) { @RequestMapping(value = "/game/{gameUuid}", method = arrayOf(RequestMethod.GET), headers = arrayOf("Accept=text/plain")) fun actualGameString(@PathVariable gameUuid: UUID): ResponseEntity<String> { return Optional.ofNullable(repository.findOne(gameUuid)) .map { game -> ResponseEntity.ok(game.toString()) } .orElse(ResponseEntity.notFound().build()) } @RequestMapping(value = "/game/{gameUuid}", method = arrayOf(RequestMethod.GET), headers = arrayOf("Accept=application/json")) fun actualGameJson(@PathVariable gameUuid: UUID): ResponseEntity<JsonResponse> { return Optional.ofNullable(repository.findOne(gameUuid)) .map { game -> ResponseEntity.ok(JsonResponse(game, Link(game))) } .orElse(ResponseEntity.notFound().build()) } @RequestMapping(value = "/game", method = arrayOf(RequestMethod.GET), headers = arrayOf("Accept=application/json")) fun getGames(): ResponseEntity<List<Link>> { return ResponseEntity.ok(repository.findAll().map { game -> Link(game) }) } data class JsonResponse(val game: Game, val link: Link) data class Link(private @JsonIgnore val game: Game) { val gameUuid = game.gameUuid val links: MutableMap<String, URI> = hashMapOf() init { links.put("get", ServletUriComponentsBuilder.fromCurrentContextPath().path("/game/$gameUuid").build().toUri()) if(game.lastMoveFrom == 'O' || game.lastMoveFrom == '-') { links.put("crossPlays", ServletUriComponentsBuilder.fromCurrentContextPath().path("/game/$gameUuid/cross").build().toUri()) } else { links.put("circlePlays", ServletUriComponentsBuilder.fromCurrentContextPath().path("/game/$gameUuid/circle").build().toUri()) } } } }
apache-2.0
b965855884936c2c4aef8a6c25683ffc
45.924528
141
0.704344
4.578269
false
false
false
false
contentful/contentful-management.java
src/test/kotlin/com/contentful/java/cma/e2e/Base.kt
1
4351
/* * Copyright (C) 2019 Contentful GmbH * * 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.contentful.java.cma.e2e import com.contentful.java.cma.CMAClient import com.contentful.java.cma.Constants import com.contentful.java.cma.interceptor.AuthorizationHeaderInterceptor import com.contentful.java.cma.interceptor.ContentTypeInterceptor import com.contentful.java.cma.interceptor.ErrorInterceptor import com.contentful.java.cma.interceptor.UserAgentHeaderInterceptor import com.contentful.java.cma.model.CMAEnvironment import com.contentful.java.cma.model.CMAEnvironmentStatus import okhttp3.Call import okhttp3.OkHttpClient import org.junit.AfterClass import org.junit.BeforeClass import java.util.concurrent.TimeUnit import kotlin.test.assertTrue import kotlin.test.fail open class Base { companion object { private const val INTERMEDIATE_WAIT_TIME = 500L private const val RETRY_ATTEMPTS = 20 const val ENVIRONMENT_ID = "java_e2e" val SPACE_ID: String = System.getenv("JAVA_CMA_E2E_SPACE_ID")!! val ACCESS_TOKEN: String = System.getenv("JAVA_CMA_E2E_TOKEN")!! val PROXY: String? = System.getenv("JAVA_CMA_E2E_PROXY") lateinit var client: CMAClient lateinit var environment: CMAEnvironment @BeforeClass @JvmStatic fun setUpSuite() { client = CMAClient.Builder().apply { if (!(PROXY.isNullOrEmpty())) { setCoreEndpoint(PROXY) setUploadEndpoint(PROXY) } setAccessToken(ACCESS_TOKEN) setEnvironmentId(ENVIRONMENT_ID) setSpaceId(SPACE_ID) setCoreCallFactory(createCallFactory()) setUploadCallFactory(createCallFactory()) }.build() // delete existing environment try { val environment = client.environments().fetchOne(ENVIRONMENT_ID) client.environments().delete(environment) } catch (throwable: Throwable) { // no environment to be deleted found, so carry on. } environment = CMAEnvironment().setName("testing $ENVIRONMENT_ID").setId(ENVIRONMENT_ID) environment = client.environments().create(environment) var maxAttempts = RETRY_ATTEMPTS var current: CMAEnvironment do { current = client.environments().fetchOne(SPACE_ID, environment.id) if (current.status != CMAEnvironmentStatus.Ready) { try { Thread.sleep(INTERMEDIATE_WAIT_TIME) } catch (e: InterruptedException) { fail("Could not wait for environment creation.") } } } while (current.status != CMAEnvironmentStatus.Ready && --maxAttempts > 0) assertTrue("Environment not ready. $maxAttempts attempts left") { maxAttempts > 0 } environment = current } @AfterClass @JvmStatic fun tearDownSuite() { client.environments().delete(environment) } fun createCallFactory(): Call.Factory? { val okBuilder: OkHttpClient.Builder = OkHttpClient.Builder() .addInterceptor(AuthorizationHeaderInterceptor(ACCESS_TOKEN)) .addInterceptor(UserAgentHeaderInterceptor("E2EUserAgent")) .addInterceptor(ContentTypeInterceptor(Constants.DEFAULT_CONTENT_TYPE)) .addInterceptor(ErrorInterceptor()) .connectTimeout(2, TimeUnit.MINUTES) .readTimeout(2, TimeUnit.MINUTES) .writeTimeout(2, TimeUnit.MINUTES) return okBuilder.build() } } }
apache-2.0
ce1b121c5c1bf0da2f5dc9277328d923
37.175439
99
0.636865
4.995408
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/backup/legacy/models/Backup.kt
2
1194
package eu.kanade.tachiyomi.data.backup.legacy.models import eu.kanade.tachiyomi.data.database.models.Category import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.models.Track import kotlinx.serialization.Contextual import kotlinx.serialization.Serializable import java.text.SimpleDateFormat import java.util.Date import java.util.Locale @Serializable data class Backup( val version: Int? = null, var mangas: MutableList<MangaObject> = mutableListOf(), var categories: List<@Contextual Category>? = null, var extensions: List<String>? = null ) { companion object { const val CURRENT_VERSION = 2 fun getDefaultFilename(): String { val date = SimpleDateFormat("yyyy-MM-dd_HH-mm", Locale.getDefault()).format(Date()) return "tachiyomi_$date.json" } } } @Serializable data class MangaObject( var manga: @Contextual Manga, var chapters: List<@Contextual Chapter>? = null, var categories: List<String>? = null, var track: List<@Contextual Track>? = null, var history: List<@Contextual DHistory>? = null )
apache-2.0
e4229a7204b34103a26bb08b36f8e2f9
31.27027
95
0.724456
4.103093
false
false
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/base/StaticBlock.kt
1
4490
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * 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.github.jonathanxd.kores.base import com.github.jonathanxd.kores.Instructions import com.github.jonathanxd.kores.Types import com.github.jonathanxd.kores.base.comment.Comments import com.github.jonathanxd.kores.builder.self import com.github.jonathanxd.kores.generic.GenericSignature import java.lang.reflect.Type /** * Static block (aka class constructors/class initializers). */ data class StaticBlock( override val comments: Comments, override val innerTypes: List<TypeDeclaration>, override val body: Instructions ) : MethodDeclarationBase { init { BodyHolder.checkBody(this) } override val name: String get() = Constants.NAME override val annotations: List<Annotation> get() = emptyList() override val parameters: List<KoresParameter> get() = emptyList() override val returnType: Type get() = Constants.RETURN_TYPE override val genericSignature: GenericSignature get() = GenericSignature.empty() override val modifiers: Set<KoresModifier> get() = Constants.MODIFIERS override val throwsClause: List<Type> get() = emptyList() override fun builder(): Builder = Builder(this) class Builder() : MethodDeclarationBase.Builder<StaticBlock, Builder> { var comments: Comments = Comments.Absent var innerTypes: List<TypeDeclaration> = emptyList() var body: Instructions = Instructions.empty() constructor(defaults: StaticBlock) : this() { this.comments = defaults.comments this.innerTypes = defaults.innerTypes this.body = defaults.body } override fun name(value: String): Builder = self() override fun comments(value: Comments): Builder { this.comments = value return this } override fun throwsClause(value: List<Type>): Builder = self() override fun annotations(value: List<Annotation>): Builder = self() override fun modifiers(value: Set<KoresModifier>): Builder = self() override fun returnType(value: Type): Builder = self() override fun parameters(value: List<KoresParameter>): Builder = self() override fun innerTypes(value: List<TypeDeclaration>): Builder { this.innerTypes = value return this } override fun body(value: Instructions): Builder { this.body = value return this } override fun genericSignature(value: GenericSignature): Builder = self() override fun build(): StaticBlock = StaticBlock(this.comments, this.innerTypes, this.body) companion object { @JvmStatic fun builder(): Builder = Builder() @JvmStatic fun builder(defaults: StaticBlock): Builder = Builder(defaults) } } companion object Constants { val NAME = "<clinit>" val MODIFIERS = setOf(KoresModifier.STATIC) val RETURN_TYPE = Types.VOID } }
mit
20c226cbf51e706300ac8249935911c1
34.078125
118
0.670824
4.791889
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/sealedSubClassToObject/ConvertSealedSubClassToObjectFix.kt
5
4108
// 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.sealedSubClassToObject import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.lang.Language import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.JavaElementType import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.intentions.ConvertSecondaryConstructorToPrimaryIntention import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.buildExpression import org.jetbrains.kotlin.psi.psiUtil.getParentOfType class ConvertSealedSubClassToObjectFix : LocalQuickFix { override fun getFamilyName() = KotlinBundle.message("convert.sealed.sub.class.to.object.fix.family.name") companion object { val JAVA_LANG = Language.findLanguageByID("JAVA") val KOTLIN_LANG = Language.findLanguageByID("kotlin") } override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val klass = descriptor.psiElement.getParentOfType<KtClass>(false) ?: return changeInstances(klass) changeDeclaration(klass) } /** * Changes declaration of class to object. */ private fun changeDeclaration(element: KtClass) { val factory = KtPsiFactory(element) element.changeToObject(factory) element.transformToObject(factory) } private fun KtClass.changeToObject(factory: KtPsiFactory) { secondaryConstructors.forEach { ConvertSecondaryConstructorToPrimaryIntention().applyTo(it, null) } primaryConstructor?.delete() getClassOrInterfaceKeyword()?.replace(factory.createExpression(KtTokens.OBJECT_KEYWORD.value)) } private fun KtClass.transformToObject(factory: KtPsiFactory) { replace(factory.createObject(text)) } /** * Replace instantiations of the class with links to the singleton instance of the object. */ private fun changeInstances(klass: KtClass) { mapReferencesByLanguage(klass) .apply { replaceKotlin(klass) replaceJava(klass) } } /** * Map references to this class by language */ private fun mapReferencesByLanguage(klass: KtClass) = ReferencesSearch.search(klass) .groupBy({ it.element.language }, { it.element.parent }) /** * Replace Kotlin instantiations to a straightforward call to the singleton. */ private fun Map<Language, List<PsiElement>>.replaceKotlin(klass: KtClass) { val list = this[KOTLIN_LANG] ?: return val singletonCall = KtPsiFactory(klass).buildExpression { appendName(klass.nameAsSafeName) } list.filter { it.node.elementType == KtNodeTypes.CALL_EXPRESSION } .forEach { it.replace(singletonCall) } } /** * Replace Java instantiations to an instance of the object, unless it is the only thing * done in the statement, in which IDEA will consider wrong, so I delete the line. */ private fun Map<Language, List<PsiElement>>.replaceJava(klass: KtClass) { val list = this[JAVA_LANG] ?: return val first = list.firstOrNull() ?: return val elementFactory = JavaPsiFacade.getElementFactory(klass.project) val javaSingletonCall = elementFactory.createExpressionFromText("${klass.name}.INSTANCE", first) list.filter { it.node.elementType == JavaElementType.NEW_EXPRESSION } .forEach { when (it.parent.node.elementType) { JavaElementType.EXPRESSION_STATEMENT -> it.delete() else -> it.replace(javaSingletonCall) } } } }
apache-2.0
b4f26b9b9a21c97841e116df8f448cc4
38.509615
158
0.710321
4.821596
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateGetSetFunctionActionFactory.kt
4
1817
// 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.createFromUsage.createCallable import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.psi.KtArrayAccessExpression import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtContainerNode import org.jetbrains.kotlin.psi.KtPsiUtil abstract class CreateGetSetFunctionActionFactory(private val isGet: Boolean) : CreateCallableMemberFromUsageFactory<KtArrayAccessExpression>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtArrayAccessExpression? { return when (diagnostic.factory) { Errors.NO_GET_METHOD -> if (isGet) Errors.NO_GET_METHOD.cast(diagnostic).psiElement else null Errors.NO_SET_METHOD -> if (!isGet) Errors.NO_SET_METHOD.cast(diagnostic).psiElement else null in Errors.TYPE_MISMATCH_ERRORS, Errors.TYPE_MISMATCH_WARNING -> { val indicesNode = diagnostic.psiElement.parent as? KtContainerNode ?: return null if (indicesNode.node.elementType != KtNodeTypes.INDICES) return null val arrayAccess = indicesNode.parent as? KtArrayAccessExpression ?: return null val parent = arrayAccess.parent val isAssignmentLHS = KtPsiUtil.isAssignment(parent) && (parent as KtBinaryExpression).left == arrayAccess if (isAssignmentLHS == isGet) return null arrayAccess } else -> throw IllegalArgumentException("Unexpected diagnostic: ${diagnostic.factory.name}") } } }
apache-2.0
eeb5a8e3375dfec672ff7d98f7eac3ef
55.78125
158
0.729774
5.019337
false
false
false
false
dahlstrom-g/intellij-community
plugins/toml/core/src/main/kotlin/org/toml/lang/psi/ElementTypes.kt
4
1931
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.toml.lang.psi import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.fileTypes.LanguageFileType import com.intellij.openapi.fileTypes.ex.FileTypeIdentifiableByVirtualFile import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import org.toml.TomlBundle import org.toml.TomlIcons import org.toml.lang.TomlLanguage import org.toml.lang.psi.TomlElementTypes.* import javax.swing.Icon class TomlTokenType(debugName: String) : IElementType(debugName, TomlLanguage) class TomlCompositeType(debugName: String) : IElementType(debugName, TomlLanguage) object TomlFileType : LanguageFileType(TomlLanguage), FileTypeIdentifiableByVirtualFile { override fun getName(): String = "TOML" override fun getDescription(): String = TomlBundle.message("filetype.toml.description") override fun getDefaultExtension(): String = "toml" override fun getIcon(): Icon = TomlIcons.TomlFile override fun getCharset(file: VirtualFile, content: ByteArray): String = "UTF-8" override fun isMyFileType(file: VirtualFile): Boolean { return file.name == "config" && file.parent?.name == ".cargo" } } val TOML_COMMENTS = TokenSet.create(COMMENT) val TOML_BASIC_STRINGS = TokenSet.create(BASIC_STRING, MULTILINE_BASIC_STRING) val TOML_LITERAL_STRINGS = TokenSet.create(LITERAL_STRING, MULTILINE_LITERAL_STRING) val TOML_SINGLE_LINE_STRINGS = TokenSet.create(BASIC_STRING, LITERAL_STRING) val TOML_MULTILINE_STRINGS = TokenSet.create(MULTILINE_BASIC_STRING, MULTILINE_LITERAL_STRING) val TOML_STRING_LITERALS = TokenSet.orSet(TOML_BASIC_STRINGS, TOML_LITERAL_STRINGS) val TOML_LITERALS = TokenSet.orSet( TOML_STRING_LITERALS, TokenSet.create( BOOLEAN, NUMBER, DATE_TIME ) )
apache-2.0
74790fef458900eb6b3c14ec3a1e545a
38.408163
94
0.77421
4.014553
false
false
false
false
evoasm/evoasm
src/evoasm/x64/Interpreter.kt
1
42776
package evoasm.x64 import evoasm.measureTimeSeconds import kasm.* import kasm.ext.log2 import kasm.ext.toEnumSet import kasm.x64.* import kasm.x64.GpRegister64.* import java.util.logging.Logger import kotlin.IllegalArgumentException import kotlin.random.Random inline class InterpreterOpcode(val code: UShort) { } class InterpreterInstructionParameters(vararg val registers: Register) : InstructionParameters { override fun getGpRegister8(index: Int, isRead: Boolean, isWritten: Boolean) = registers[index] as GpRegister8 override fun getGpRegister16(index: Int, isRead: Boolean, isWritten: Boolean) = registers[index] as GpRegister16 override fun getGpRegister32(index: Int, isRead: Boolean, isWritten: Boolean) = registers[index] as GpRegister32 override fun getGpRegister64(index: Int, isRead: Boolean, isWritten: Boolean) = registers[index] as GpRegister64 override fun getMmRegister(index: Int, isRead: Boolean, isWritten: Boolean) = registers[index] as MmRegister override fun getXmmRegister(index: Int, isRead: Boolean, isWritten: Boolean) = registers[index] as XmmRegister override fun getYmmRegister(index: Int, isRead: Boolean, isWritten: Boolean) = registers[index] as YmmRegister override fun getZmmRegister(index: Int, isRead: Boolean, isWritten: Boolean) = registers[index] as ZmmRegister override fun getX87Register(index: Int, isRead: Boolean, isWritten: Boolean): X87Register = registers[index] as X87Register override fun useSibd() = false override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass !== other?.javaClass) return false other as InterpreterInstructionParameters if (!registers.contentEquals(other.registers)) return false return true } override fun hashCode(): Int { return registers.contentHashCode() } } data class InterpreterInstruction(val instruction: Instruction, val instructionParameters: InstructionParameters) //,val operandRegisters: List<Register>) class Interpreter(val programSet: ProgramSet, val input: ProgramSetInput, val output: ProgramSetOutput, val options: InterpreterOptions = InterpreterOptions.DEFAULT) { companion object { fun emitMultiplication(assembler: Assembler, register: GpRegister64, multiplier: Int) { when { Integer.bitCount(multiplier) == 1 -> { val shiftSize = log2(multiplier).toByte() assembler.sal(register, shiftSize) } multiplier <= Byte.MAX_VALUE -> { assembler.imul(register, register, multiplier.toByte()) } else -> { assembler.imul(register, register, multiplier) } } } val LOGGER = Logger.getLogger(Interpreter::class.java.name) private const val INSTRUCTION_ALIGNMENT = 8 // bytes private const val OPCODE_SIZE = Short.SIZE_BYTES // bytes private val FIRST_INSTRUCTION_ADDRESS_REGISTER = RBP private val IP_REGISTER = R14 internal val SCRATCH_REGISTER1 = R12 internal val COUNTERS_REGISTER = R13 internal val SCRATCH_REGISTER2 = R15 internal val GP_REGISTERS = listOf(RAX, RBX, RCX, RDX, RDI, RSI, R8, R9, R10, R11) internal val GP_REGISTERS_SET = GP_REGISTERS.toEnumSet() internal val XMM_REGISTERS = XmmRegister.values().filter { it.isSupported() }.toList() internal val XMM_REGISTERS_SET = XMM_REGISTERS.toEnumSet() internal val YMM_REGISTERS = YmmRegister.values().filter { it.isSupported() }.toList() internal val YMM_REGISTERS_SET = YMM_REGISTERS.toEnumSet() internal val MM_REGISTERS = MmRegister.values().toList() internal val MM_REGISTERS_SET = MM_REGISTERS.toEnumSet() private val DIV_INSTRUCTIONS = setOf( IdivRm8Ax, IdivRm16AxDx, IdivRm32EdxEax, IdivRm64RdxRax, DivRm8Ax, DivRm16AxDx, DivRm32EdxEax, DivRm64RdxRax) } private val instructionTracer = object : InstructionTracer { private fun addOperandRegisters(index: Int, operandRegisters: List<Register>) { this.operandRegisters[index] = operandRegisters operandRegisterCount = Math.max(operandRegisterCount, index + 1) } override fun traceWrite(register: GpRegister8, index: Int, range: BitRange, always: Boolean) { checkRegister(register) addOperandRegisters(index, options.gp8OperandRegisters[index]) } override fun traceWrite(register: GpRegister16, index: Int, range: BitRange, always: Boolean) { checkRegister(register) addOperandRegisters(index, options.gp16OperandRegisters[index]) } override fun traceWrite(register: GpRegister32, index: Int, range: BitRange, always: Boolean) { checkRegister(register) addOperandRegisters(index, options.gp32OperandRegisters[index]) } override fun traceWrite(register: GpRegister64, index: Int, range: BitRange, always: Boolean) { checkRegister(register) addOperandRegisters(index, options.gp64OperandRegisters[index]) } override fun traceWrite(register: XmmRegister, index: Int, range: BitRange, always: Boolean) { checkRegister(register) addOperandRegisters(index, options.xmmOperandRegisters[index]) } override fun traceWrite(register: YmmRegister, index: Int, range: BitRange, always: Boolean) { checkRegister(register) addOperandRegisters(index, options.ymmOperandRegisters[index]) } override fun traceWrite(register: MmRegister, index: Int, range: BitRange, always: Boolean) { checkRegister(register) addOperandRegisters(index, options.mmOperandRegisters[index]) } override fun traceWrite(register: X87Register, index: Int, range: BitRange, always: Boolean) { checkRegister(register) TODO() } override fun traceRead(register: GpRegister8, index: Int, range: BitRange) { checkRegister(register) addOperandRegisters(index, options.gp8OperandRegisters[index]) } override fun traceRead(register: GpRegister16, index: Int, range: BitRange) { checkRegister(register) addOperandRegisters(index, options.gp16OperandRegisters[index]) } override fun traceRead(register: GpRegister32, index: Int, range: BitRange) { checkRegister(register) addOperandRegisters(index, options.gp32OperandRegisters[index]) } override fun traceRead(register: GpRegister64, index: Int, range: BitRange) { checkRegister(register) addOperandRegisters(index, options.gp64OperandRegisters[index]) } override fun traceRead(register: XmmRegister, index: Int, range: BitRange) { checkRegister(register) addOperandRegisters(index, options.xmmOperandRegisters[index]) } override fun traceRead(register: YmmRegister, index: Int, range: BitRange) { checkRegister(register) addOperandRegisters(index, options.ymmOperandRegisters[index]) } override fun traceRead(register: MmRegister, index: Int, range: BitRange) { checkRegister(register) addOperandRegisters(index, options.mmOperandRegisters[index]) } override fun traceRead(register: X87Register, index: Int, range: BitRange) { checkRegister(register) TODO() } private val gpRegisters = GP_REGISTERS_SET private val xmmRegisters = XMM_REGISTERS_SET private val ymmRegisters = YMM_REGISTERS_SET private val mmRegisters = MM_REGISTERS_SET private var operandRegisterCount = 0 private val operandRegisters = Array(4) { emptyList<Register>()} private fun checkRegister(register: Register) { val normalizedRegister = normalizeRegister(register) checkNormalizedRegister(normalizedRegister, register) } private fun checkNormalizedRegister(normalizedRegister: Register, register: Register) { check(normalizedRegister in gpRegisters || register in xmmRegisters || register in ymmRegisters || register in mmRegisters ) { "invalid register $register ($normalizedRegister)" } } private fun normalizeRegister(register: Register): Register { return when (register) { is GpRegister32 -> register.topLevelRegister is GpRegister16 -> register.topLevelRegister is GpRegister8 -> register.topLevelRegister else -> register } } // override fun traceWrite(register: Register, implicit: Boolean, range: BitRange, always: Boolean) { // val normalizedRegister = normalizeRegister(register) // checkNormalizedRegister(normalizedRegister, register) // if (implicit) { // useRegister(register) // } else { // addRegisters(normalizedRegister) // } // } fun getOperandRegisterSequence() : Sequence<Array<Register>> { val indices = IntArray(operandRegisterCount + 1) return generateSequence { if(indices.last() != 0) { return@generateSequence null } val result = Array(operandRegisterCount) { operandRegisters[it][indices[it]] } indices[0]++ for (i in 0 until operandRegisterCount) { if(indices[i] >= operandRegisters[i].size) { indices[i] = 0 indices[i + 1]++ } } result } } internal var operandRegisterSequence: Sequence<Array<Register>>? = null override fun endTracing() { operandRegisterSequence = getOperandRegisterSequence() } override fun beginTracing() { operandRegisterCount = 0 operandRegisters.fill(emptyList()) } override fun traceRead(rflagsField: RflagsField) {} override fun traceWrite(rflagsField: RflagsField, always: Boolean) {} override fun traceRead(mxcsrField: MxcsrField) {} override fun traceWrite(mxcsrField: MxcsrField, always: Boolean) {} } private val traceInstructionParameters = object : InstructionParameters { override fun getGpRegister8(index: Int, isRead: Boolean, isWritten: Boolean): GpRegister8 { return GP_REGISTERS[0].subRegister8 } override fun getGpRegister16(index: Int, isRead: Boolean, isWritten: Boolean): GpRegister16 { return GP_REGISTERS[0].subRegister16 } override fun getGpRegister32(index: Int, isRead: Boolean, isWritten: Boolean): GpRegister32 { return GP_REGISTERS[0].subRegister32 } override fun getGpRegister64(index: Int, isRead: Boolean, isWritten: Boolean): GpRegister64 { return GP_REGISTERS[0] } override fun getMmRegister(index: Int, isRead: Boolean, isWritten: Boolean): MmRegister { return MM_REGISTERS[0] } override fun getXmmRegister(index: Int, isRead: Boolean, isWritten: Boolean): XmmRegister { return XMM_REGISTERS[0] } override fun getYmmRegister(index: Int, isRead: Boolean, isWritten: Boolean): YmmRegister { return YMM_REGISTERS[0] } override fun getZmmRegister(index: Int, isRead: Boolean, isWritten: Boolean): ZmmRegister { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression8(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression8 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression16(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression16 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression32(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression32 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression64(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression64 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression128(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression128 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression256(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression256 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression512(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression512 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getVectorAddress(index: Int, isRead: Boolean, isWritten: Boolean): VectorAddressExpression { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getX87Register(index: Int, isRead: Boolean, isWritten: Boolean): X87Register { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression80(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression80 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression28Bytes(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression28Bytes { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression108Bytes(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression108Bytes { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression512Bytes(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression512Bytes { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun useSibd(): Boolean { return false } override fun getByteImmediate(index: Int): Byte { return 0; } override fun getShortImmediate(index: Int): Short { return 0; } override fun getIntImmediate(index: Int): Int { return 0; } override fun getLongImmediate(index: Int): Long { return 0; } } private val instructionParameters = object : InstructionParameters { internal var operandRegisters = emptyArray<Register>() private val random = Random.Default override fun getGpRegister8(index: Int, isRead: Boolean, isWritten: Boolean): GpRegister8 { return operandRegisters[index] as GpRegister8 } override fun getGpRegister16(index: Int, isRead: Boolean, isWritten: Boolean): GpRegister16 { return operandRegisters[index] as GpRegister16 } override fun getGpRegister32(index: Int, isRead: Boolean, isWritten: Boolean): GpRegister32 { return operandRegisters[index] as GpRegister32 } override fun getGpRegister64(index: Int, isRead: Boolean, isWritten: Boolean): GpRegister64 { return operandRegisters[index] as GpRegister64 } override fun getMmRegister(index: Int, isRead: Boolean, isWritten: Boolean): MmRegister { return operandRegisters[index] as MmRegister } override fun getXmmRegister(index: Int, isRead: Boolean, isWritten: Boolean): XmmRegister { return operandRegisters[index] as XmmRegister } override fun getYmmRegister(index: Int, isRead: Boolean, isWritten: Boolean): YmmRegister { return operandRegisters[index] as YmmRegister } override fun getZmmRegister(index: Int, isRead: Boolean, isWritten: Boolean): ZmmRegister { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression8(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression8 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression16(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression16 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression32(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression32 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression64(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression64 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression128(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression128 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression256(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression256 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression512(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression512 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getVectorAddress(index: Int, isRead: Boolean, isWritten: Boolean): VectorAddressExpression { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getX87Register(index: Int, isRead: Boolean, isWritten: Boolean): X87Register { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression80(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression80 { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression28Bytes(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression28Bytes { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression108Bytes(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression108Bytes { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getAddressExpression512Bytes(index: Int, isRead: Boolean, isWritten: Boolean): AddressExpression512Bytes { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun useSibd(): Boolean { return false } override fun getByteImmediate(index: Int): Byte { return (random.nextBits(8)).toByte(); } override fun getShortImmediate(index: Int): Short { return (random.nextBits(16)).toShort(); } override fun getIntImmediate(index: Int): Int { return random.nextInt() } override fun getLongImmediate(index: Int): Long { return random.nextLong() } } val opcodeCount get() = instructionCounter - internalInstructionCount private var haltLinkPoint: Assembler.JumpLinkPoint? = null private var firstInstructionLinkPoint: Assembler.LongLinkPoint? = null internal val buffer = NativeBuffer(1024 * 512, CodeModel.LARGE) private val assembler = Assembler(buffer) private var emittedNopBytes = 0 private var instructionCounter: Int = 0 internal var instructions = UShortArray(1024) private var firstInstructionOffset: Int = -1 private var interpreterEpilogOffset: Int = -1 private val instructionMap = mutableMapOf<InterpreterInstruction, InterpreterOpcode>() init { emit() programSet.initialize(getHaltOpcode(), getEndOpcode()) LOGGER.finer(buffer.toByteString()) buffer.setExecutable(true) } internal fun getHaltOpcode(): InterpreterOpcode { return InterpreterOpcode(instructions[0].toUShort()); } internal fun getEndOpcode(): InterpreterOpcode { return InterpreterOpcode(instructions[1].toUShort()); } private val internalInstructionCount = 2 fun getOpcode(opcodeIndex: Int): InterpreterOpcode { // require(opcodeIndex < instructionCounter) { "invalid opcode index $opcodeIndex (max opcode index is $instructionCounter)" } return InterpreterOpcode(instructions[opcodeIndex + internalInstructionCount].toUShort()); } fun getOpcode(instruction: Instruction, operandRegisters: List<Register>): InterpreterOpcode? { return getOpcode(instruction, *operandRegisters.toTypedArray()) } fun getOpcode(instruction: Instruction, vararg operandRegisters: Register): InterpreterOpcode? { return instructionMap[InterpreterInstruction(instruction, InterpreterInstructionParameters(*operandRegisters))] } fun getInstruction(opcode: InterpreterOpcode): InterpreterInstruction? { return instructionMap.entries.find { it.value == opcode}?.key } private fun emitHaltInstruction() { emitInstruction(dispatch = false) { haltLinkPoint = assembler.jmp() } } private fun emitRflagsReset() { with(assembler) { pushfq() mov(AddressExpression64(RSP), 0) popfq() } } fun disassemble(opcode: InterpreterOpcode): Array<out Array<String>> { val instructionIndex = instructions.asShortArray().binarySearch(opcode.code.toShort(), 0, instructionCounter) LOGGER.finer("found index ${instructions.indexOf(opcode.code)} for ${opcode.code}") require(instructionIndex >= 0) { "opcode ${opcode.code} was not found"} val instructionOffset = getInstructionOffset(opcode) LOGGER.finer("instructionIndex: $instructionIndex") val instructionEndOffset = if(instructionIndex + 1 < instructionCounter) { getInstructionOffset(instructions[instructionIndex + 1]) } else { interpreterEpilogOffset } val codeArray = ByteArray(instructionEndOffset - instructionOffset) { buffer.byteBuffer.get(instructionOffset + it) } return Disassembler.disassemble(codeArray) } private fun emitEndInstruction() { with(assembler) { emitInstruction { // store result emitOutputStore() if(input.size != 1) { val inputCounterSubRegister = COUNTERS_REGISTER.subRegister16 // decrease input count dec(inputCounterSubRegister) ifNotEqual( { sub(IP_REGISTER, OPCODE_SIZE * (programSet.programSize + 1)) }, { // increment program counter add(COUNTERS_REGISTER, 1 shl 16) //inc(COUNTERS_REGISTER) // reset input counter mov(inputCounterSubRegister, input.size.toShort()) } ) } else { inc(COUNTERS_REGISTER.subRegister32) } // reset flags // NOTE: this includes only SF, ZF, AF, PF, and CF xor(GpRegister32.EAX, GpRegister32.EAX) sahfAh() // load inputs input.emitLoad(assembler) } } } private fun emitDispatch() { with(assembler) { // load next opcode movzx(SCRATCH_REGISTER1, AddressExpression16(IP_REGISTER)) if(options.compressOpcodes) { lea(SCRATCH_REGISTER1, AddressExpression64(FIRST_INSTRUCTION_ADDRESS_REGISTER, SCRATCH_REGISTER1, Scale.X8)) } else { lea(SCRATCH_REGISTER1, AddressExpression64(FIRST_INSTRUCTION_ADDRESS_REGISTER, SCRATCH_REGISTER1, Scale.X1)) } jmp(SCRATCH_REGISTER1) } } private fun encodeInstructionProlog() { with(assembler) { lea(IP_REGISTER, AddressExpression64(IP_REGISTER, OPCODE_SIZE)) } } private fun emitInstructionEpilog(dispatch: Boolean) { with(assembler) { if (dispatch) emitDispatch() if(options.compressOpcodes) { emittedNopBytes += align(INSTRUCTION_ALIGNMENT) } } } private fun emitInterpreterProlog() { with(assembler) { // let IP point to first opcode emitRflagsReset() firstInstructionLinkPoint = mov(FIRST_INSTRUCTION_ADDRESS_REGISTER) var perThreadPrologLinkPoint: Assembler.IntLinkPoint? = null var firstThreadPrologLinkPoint: Assembler.LongLinkPoint? = null if(haveMultipleThreads) { //TODO: directly multiply RDI by size firstThreadPrologLinkPoint = mov(SCRATCH_REGISTER1) imul(GpRegister32.EDI, GpRegister32.EDI, 0xdeadbeef.toInt()) perThreadPrologLinkPoint = Assembler.IntLinkPoint(buffer) add(SCRATCH_REGISTER1, RDI) jmp(SCRATCH_REGISTER1) } if(haveMultipleThreads) { firstThreadPrologLinkPoint!!.link(buffer.positionAddress.toLong()) } var threadPrologSize = -1 repeat(options.threadCount) { threadIndex -> val thisThreadPrologAddress = buffer.positionAddress mov(IP_REGISTER, programSet.getAddress(threadIndex).toLong()) if (input.size == 1) { if(threadIndex == 0) { xor(COUNTERS_REGISTER, COUNTERS_REGISTER) } else { mov(COUNTERS_REGISTER, threadIndex * programSet.perThreadProgramCount) } } else { if(threadIndex == 0) { mov(COUNTERS_REGISTER, input.size) nop(3) } else { val countersValue : Long = input.size.toLong() or ((threadIndex.toLong() * programSet.perThreadProgramCount.toLong()) shl 16) mov(COUNTERS_REGISTER, countersValue) } } input.emitLoad(assembler) emitDispatch() val thisThreadPrologSize = (buffer.positionAddress - thisThreadPrologAddress).toInt() if(threadPrologSize == -1) { threadPrologSize = thisThreadPrologSize } else { check(threadPrologSize == thisThreadPrologSize) { "thread prologs must have equal size ($threadPrologSize != $thisThreadPrologSize"} } } if(haveMultipleThreads) { perThreadPrologLinkPoint!!.link(threadPrologSize) } align(INSTRUCTION_ALIGNMENT) } } private fun emitInterpreterEpilog() { interpreterEpilogOffset = buffer.byteBuffer.position() assembler.link(haltLinkPoint!!) } val haveMultipleThreads get() = options.threadCount > 1 || options.forceMultithreading // private fun emitStartInstructions() { // repeat(options.threadCount) { // emitStartInstruction(it) // } // } // private fun emitStartInstruction(threadIndex: Int) { // inputs[threadIndex].emitLoad(assembler) // emitDispatch() // } private fun emit() { // val argumentRegisters = if(haveMultipleThreads) { // enumSetOf(RDI) // } else { // enumSetOf() // } assembler.emitStackFrame() { emitInterpreterProlog() val firstInstructionAddress = buffer.address.toLong() + buffer.position() LOGGER.fine("First inst addr ${Address(firstInstructionAddress.toULong())}") firstInstructionLinkPoint!!.link(firstInstructionAddress) // IMPORTANT: must be first instructions, in this order emitHaltInstruction() emitEndInstruction() emitInstructions() emitMoveInstructions() emitInterpreterEpilog() } LOGGER.info("Average instruction bufferSize: ${assembler.buffer.position() / options.instructions.size.toDouble()}") } private fun emitInstructions() { LOGGER.finer("emitting ${options.instructions.size} instructions") options.instructions.forEach { if (it in DIV_INSTRUCTIONS && options.safeDivision) { for(divisorInstruction in getDivisorInstructions(it)) { emitInstruction { interpreterOpcode -> emitDivInstruction(it, divisorInstruction) instructionMap[InterpreterInstruction(it, InterpreterInstructionParameters(divisorInstruction))] = interpreterOpcode } } } else { it.trace(instructionTracer, traceInstructionParameters) val operandRegisterSequence = instructionTracer.operandRegisterSequence!! operandRegisterSequence.forEach { operandRegisters -> emitInstruction { interpreterOpcode -> instructionParameters.operandRegisters = operandRegisters it.encode(buffer.byteBuffer, instructionParameters) instructionMap[InterpreterInstruction(it, InterpreterInstructionParameters(*operandRegisters))] = interpreterOpcode } } } } } private fun getDivisorInstructions(divInstruction: Instruction) : List<GpRegister> { return when (divInstruction) { is IdivRm8Ax, is DivRm8Ax -> options.gp8OperandRegisters[0] is IdivRm16AxDx, is DivRm16AxDx -> options.gp16OperandRegisters[0] is IdivRm32EdxEax, is DivRm32EdxEax -> options.gp32OperandRegisters[0] is IdivRm64RdxRax, is DivRm64RdxRax -> options.gp64OperandRegisters[0] else -> { throw RuntimeException() } } } private fun emitDivInstruction(instruction: Instruction, divisorRegister: GpRegister) { when (instruction) { is IdivRm8Ax, is DivRm8Ax -> { val divisorRegister8 = divisorRegister as GpRegister8 assembler.xor(GpRegister16.AX, GpRegister16.AX) assembler.test(divisorRegister, divisorRegister8) } is IdivRm16AxDx, is DivRm16AxDx -> { val divisorRegister16 = divisorRegister as GpRegister16 assembler.xor(GpRegister16.AX, GpRegister16.AX) assembler.xor(GpRegister16.DX, GpRegister16.DX) assembler.test(divisorRegister16, divisorRegister16) } is IdivRm32EdxEax, is DivRm32EdxEax -> { val divisorRegister32 = divisorRegister as GpRegister32 assembler.xor(GpRegister32.EAX, GpRegister32.EAX) assembler.xor(GpRegister32.EDX, GpRegister32.EDX) assembler.test(divisorRegister32, divisorRegister32) } is IdivRm64RdxRax, is DivRm64RdxRax -> { val divisorRegister64 = divisorRegister as GpRegister64 assembler.xor(RAX, RAX) assembler.xor(RDX, RDX) assembler.test(divisorRegister64, divisorRegister64) } else -> { throw RuntimeException() } } val linkPoint = assembler.je() when (instruction) { is R8m8Instruction -> { val divisorRegister8 = divisorRegister as GpRegister8 instruction.encode(assembler.buffer, divisorRegister8) } is R16m16Instruction -> { val divisorRegister16 = divisorRegister as GpRegister16 instruction.encode(assembler.buffer, divisorRegister16) } is R32m32Instruction -> { val divisorRegister32 = divisorRegister as GpRegister32 instruction.encode(assembler.buffer, divisorRegister32) } is R64m64Instruction -> { val divisorRegister64 = divisorRegister as GpRegister64 instruction.encode(assembler.buffer, divisorRegister64) } } assembler.link(linkPoint) } private fun emitMoveInstructions() { options.moveInstructions.forEach { emitMoveInstructions(it) } } private fun emitMoveInstructions(instruction: MoveInstruction) { val buffer = assembler.buffer val (registersList, registersSet) = when (instruction) { is R64m64R64Instruction, is R64R64m64Instruction -> GP_REGISTERS to GP_REGISTERS_SET is XmmXmmm64Instruction, is XmmXmmm128Instruction, is Xmmm64XmmInstruction -> XMM_REGISTERS to XMM_REGISTERS_SET is YmmYmmm256Instruction -> YMM_REGISTERS to YMM_REGISTERS_SET else -> throw IllegalArgumentException( "invalid move instruction $instruction") } as Pair<List<Register>, Set<Register>> val moves = options.movesGenerator(instruction, registersList) //NOTE: using the pd variant of the mov might cause a domain switch latency // i.e. if the register holds integer data (or possibly even packed vs single, single vs double float?) and we use a pd mov // https://stackoverflow.com/questions/6678073/difference-between-movdqa-and-movaps-x86-instructions moves.forEach { (destinationRegister, sourceRegister) -> require(destinationRegister in registersSet) require(sourceRegister in registersSet) emitInstruction { instructionMap[InterpreterInstruction(instruction as Instruction, InterpreterInstructionParameters(destinationRegister, sourceRegister))] = it when (instruction) { is R64m64R64Instruction -> instruction.encode(buffer, destinationRegister as GpRegister64, sourceRegister as GpRegister64) is R64R64m64Instruction -> instruction.encode(buffer, destinationRegister as GpRegister64, sourceRegister as GpRegister64) is XmmXmmm64Instruction -> instruction.encode(buffer, destinationRegister as XmmRegister, sourceRegister as XmmRegister) is Xmmm64XmmInstruction -> instruction.encode(buffer, destinationRegister as XmmRegister, sourceRegister as XmmRegister) is XmmXmmm128Instruction -> instruction.encode(buffer, destinationRegister as XmmRegister, sourceRegister as XmmRegister) is Xmmm128XmmInstruction -> instruction.encode(buffer, destinationRegister as XmmRegister, sourceRegister as XmmRegister) is YmmYmmm256Instruction -> instruction.encode(buffer, destinationRegister as YmmRegister, sourceRegister as YmmRegister) is Ymmm256YmmInstruction -> instruction.encode(buffer, destinationRegister as YmmRegister, sourceRegister as YmmRegister) } } } } private fun emitOutputStore() { output.emitStore(assembler) } private fun emitInstruction(dispatch: Boolean = true, block: (InterpreterOpcode) -> Unit) { val interpreterInstruction = addInstruction() encodeInstructionProlog() block(interpreterInstruction) emitInstructionEpilog(dispatch) } private fun addInstruction(): InterpreterOpcode { val opcode = if (firstInstructionOffset > 0) { val relativeInstructionOffset = buffer.byteBuffer.position() - firstInstructionOffset val opcodeInt = if(options.compressOpcodes) { relativeInstructionOffset / 8 } else { relativeInstructionOffset } require(opcodeInt < UShort.MAX_VALUE.toInt()) {"16-bit opcode size exceeded"} opcodeInt.toUShort() } else { firstInstructionOffset = buffer.byteBuffer.position() 0U } if (instructionCounter >= instructions.size) { val newInstructions = UShortArray(instructions.size * 2) instructions.copyInto(newInstructions) instructions = newInstructions } instructions[instructionCounter++] = opcode return InterpreterOpcode(opcode) } private fun getInstructionOffset(opcode: UShort) : Int { return firstInstructionOffset + if(options.compressOpcodes) { opcode.toInt() * 8 } else { opcode.toInt() } } private fun getInstructionOffset(opcode: InterpreterOpcode) = getInstructionOffset(opcode.code) fun run() { run(0) } fun run(threadIndex: Int) { LOGGER.fine("running address is ${buffer.address}") if(options.unsafe) { if(haveMultipleThreads) { buffer.executeUnsafe(threadIndex.toLong()) } else { buffer.executeUnsafe() } } else { if(haveMultipleThreads) { buffer.execute(threadIndex.toLong()) } else { buffer.execute() } } } fun runParallel() { if(options.unsafe) { buffer.executeParallelUnsafe(options.threadCount) } else { buffer.executeParallel(options.threadCount) } } data class RunMeasurements(var elapsedSeconds: Double, var instructionsPerSecond: Double) data class Statistics(val size: Int, val instructionCount: Int, val averageInstructionSize: Double, val nopRatio : Double) val statistics : Statistics get() { val emittedBytes = buffer.byteBuffer.position().toDouble() return Statistics( buffer.byteBuffer.position(), instructionCounter, emittedBytes / instructionCounter, emittedNopBytes / emittedBytes) } fun runAndMeasure() = runAndMeasure(0) fun runAndMeasure(threadIndex: Int): RunMeasurements { val elapsedSeconds = measureTimeSeconds { run(threadIndex) } val instructionsPerSecond = (programSet.instructionCount * input.size) / elapsedSeconds return RunMeasurements(elapsedSeconds, instructionsPerSecond) } }
agpl-3.0
9f7078e65e673f7cb90515217461e981
40.89618
162
0.60057
5.596755
false
false
false
false
sreich/ore-infinium
core/src/com/ore/infinium/components/AirComponent.kt
1
1618
/** MIT License Copyright (c) 2016 Shaun Reich <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.ore.infinium.components import com.artemis.Component import com.ore.infinium.util.ExtendedComponent class AirComponent : Component(), ExtendedComponent<AirComponent> { companion object { const val decreaseIntervalMs = 50L } var maxAir = 25000 //current air level var air = maxAir override fun copyFrom(other: AirComponent) = throw TODO("function not yet implemented") override fun canCombineWith(other: AirComponent) = throw TODO("function not yet implemented") }
mit
b0f8ccb2e747a6249d30338b86b11126
34.955556
97
0.778121
4.596591
false
false
false
false
paplorinc/intellij-community
plugins/gradle/java/src/service/project/MavenRepositoriesProjectResolver.kt
3
2370
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.service.project import com.intellij.externalSystem.MavenRepositoryData import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import org.gradle.tooling.model.idea.IdeaModule import org.gradle.tooling.model.idea.IdeaProject import org.jetbrains.plugins.gradle.model.RepositoriesModel import org.jetbrains.plugins.gradle.util.GradleConstants import java.util.* class MavenRepositoriesProjectResolver: AbstractProjectResolverExtension() { override fun populateProjectExtraModels(gradleProject: IdeaProject, ideProject: DataNode<ProjectData>) { val repositories = resolverCtx.getExtraProject(RepositoriesModel::class.java) addRepositoriesToProject(ideProject, repositories) super.populateProjectExtraModels(gradleProject, ideProject) } override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) { val repositories = resolverCtx.getExtraProject(gradleModule, RepositoriesModel::class.java) val ideProject = ExternalSystemApiUtil.findParent(ideModule, ProjectKeys.PROJECT) ideProject?.let { addRepositoriesToProject(it, repositories) } super.populateModuleExtraModels(gradleModule, ideModule) } override fun getExtraProjectModelClasses(): Set<Class<*>> { return Collections.singleton(RepositoriesModel::class.java) } private fun addRepositoriesToProject(ideProject: DataNode<ProjectData>, repositories: RepositoriesModel?) { if (repositories != null) { val knownRepositories = ExternalSystemApiUtil.getChildren(ideProject, MavenRepositoryData.KEY) .asSequence() .map { it.data } .toSet() repositories.all.asSequence() .map { MavenRepositoryData(GradleConstants.SYSTEM_ID, it.name, it.url) } .filter { !knownRepositories.contains(it) } .forEach { ideProject.addChild(DataNode(MavenRepositoryData.KEY, it, ideProject)) } } } }
apache-2.0
e61217fc34b8217b382ed8750c1c3db4
45.490196
140
0.781857
4.978992
false
false
false
false
paplorinc/intellij-community
plugins/devkit/devkit-core/src/actions/MigrateModuleNamesInSourcesAction.kt
2
14006
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.actions import com.intellij.icons.AllIcons import com.intellij.navigation.ItemPresentation import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.impl.ModuleRenamingHistoryState import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Factory import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiComment import com.intellij.psi.PsiFile import com.intellij.psi.PsiPlainText import com.intellij.psi.search.* import com.intellij.usageView.UsageInfo import com.intellij.usages.* import com.intellij.util.Processor import com.intellij.util.xmlb.XmlSerializationException import com.intellij.util.xmlb.XmlSerializer import org.jetbrains.idea.devkit.util.PsiUtil import java.io.File import kotlin.experimental.or private val LOG = Logger.getInstance(MigrateModuleNamesInSourcesAction::class.java) /** * This is a temporary action to be used for migrating occurrences of module names in IntelliJ IDEA sources after massive module renaming. */ class MigrateModuleNamesInSourcesAction : AnAction("Find/Update Module Names in Sources...", "Find and migrate to the new scheme occurrences of module names in IntelliJ IDEA project sources", null) { override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val viewPresentation = UsageViewPresentation().apply { tabText = "Occurrences of Module Names" toolwindowTitle = "Occurrences of Module Names" usagesString = "occurrences of module names" usagesWord = "occurrence" codeUsagesString = "Found Occurrences" isOpenInNewTab = true isCodeUsages = false isUsageTypeFilteringAvailable = true } val processPresentation = FindUsagesProcessPresentation(viewPresentation).apply { isShowNotFoundMessage = true isShowPanelIfOnlyOneUsage = true } val renamingScheme = try { LocalFileSystem.getInstance().refreshAndFindFileByIoFile( File(VfsUtil.virtualToIoFile(project.baseDir), "module-renaming-scheme.xml"))?.let { XmlSerializer.deserialize(JDOMUtil.load(it.inputStream), ModuleRenamingHistoryState::class.java).oldToNewName } } catch (e: XmlSerializationException) { LOG.error(e) return } val moduleNames = renamingScheme?.keys?.toList() ?: ModuleManager.getInstance(project).modules.map { it.name } val targets = moduleNames.map(::ModuleNameUsageTarget).toTypedArray() val searcherFactory = Factory<UsageSearcher> { val processed = HashSet<Pair<VirtualFile, Int>>() UsageSearcher { consumer -> val usageInfoConsumer = Processor<UsageInfo> { if (processed.add(Pair(it.virtualFile!!, it.navigationRange!!.startOffset))) { consumer.process(UsageInfo2UsageAdapter(it)) } else true } processOccurrences(project, moduleNames, usageInfoConsumer) } } val listener = object : UsageViewManager.UsageViewStateListener { override fun usageViewCreated(usageView: UsageView) { if (renamingScheme == null) return val migrateOccurrences = Runnable { @Suppress("UNCHECKED_CAST") val usages = (usageView.usages - usageView.excludedUsages) as Set<UsageInfo2UsageAdapter> val usagesByFile = usages.groupBy { it.file } val progressIndicator = ProgressManager.getInstance().progressIndicator var i = 0 usagesByFile.forEach { (file, usages) -> progressIndicator?.fraction = (i++).toDouble() / usagesByFile.size try { usages.sortedByDescending { it.usageInfo.navigationRange!!.startOffset }.forEach { var range = it.usageInfo.navigationRange!! if (it.document.charsSequence[range.startOffset] in listOf('"', '\'')) range = TextRange(range.startOffset + 1, range.endOffset - 1) val oldName = it.document.charsSequence.subSequence(range.startOffset, range.endOffset).toString() if (oldName !in renamingScheme) throw RuntimeException("Unknown module $oldName") val newName = renamingScheme[oldName]!! runWriteAction { it.document.replaceString(range.startOffset, range.endOffset, newName) } } } catch (e: Exception) { throw RuntimeException("Cannot replace usage in ${file.presentableUrl}: ${e.message}", e) } } } usageView.addPerformOperationAction(migrateOccurrences, "Migrate Module Name Occurrences", "Cannot migrate occurrences", "Migrate Module Name Occurrences") } override fun findingUsagesFinished(usageView: UsageView?) { } } UsageViewManager.getInstance(project).searchAndShowUsages(targets, searcherFactory, processPresentation, viewPresentation, listener) } private fun processOccurrences(project: Project, moduleNames: List<String>, consumer: Processor<UsageInfo>) { val progress = ProgressManager.getInstance().progressIndicator ?: EmptyProgressIndicator() progress.text = "Searching for module names..." val scope = GlobalSearchScope.projectScope(project) val searchHelper = PsiSearchHelper.getInstance(project) fun Char.isModuleNamePart() = this.isJavaIdentifierPart() || this == '-' fun GlobalSearchScope.filter(filter: (VirtualFile) -> Boolean) = object: DelegatingGlobalSearchScope(this) { override fun contains(file: VirtualFile): Boolean { return filter(file) && super.contains(file) } } fun mayMentionModuleNames(text: String) = (text.contains("JpsProject") || text.contains("package com.intellij.testGuiFramework") || text.contains("getJarPathForClass")) && !text.contains("StandardLicenseUrls") fun VirtualFile.isBuildScript() = when (extension) { "gant" -> true "groovy" -> VfsUtil.loadText(this).contains("package org.jetbrains.intellij.build") "java" -> mayMentionModuleNames(VfsUtil.loadText(this)) "kt" -> mayMentionModuleNames(VfsUtil.loadText(this)) else -> false } fun processCodeUsages(moduleName: String, quotedString: String, groovyOnly: Boolean) { val ignoredMethods = listOf("getPluginHomePath(", "getPluginHome(", "getPluginHomePathRelative(", "dir(", "withProjectLibrary(", "directoryName = ") val quotedOccurrencesProcessor = TextOccurenceProcessor { element, offset -> if (element.text != quotedString) return@TextOccurenceProcessor true if (ignoredMethods.any { element.textRange.startOffset > it.length && element.containingFile.text.startsWith(it, element.textRange.startOffset - it.length) }) { return@TextOccurenceProcessor true } consumer.process(UsageInfo(element, offset, offset + quotedString.length)) } val literalsScope = if (moduleName in regularWordsUsedAsModuleNames + moduleNamesUsedAsIDs) scope.filter { it.isBuildScript() && !groovyOnly || it.extension in listOf("groovy", "gant") } else scope searchHelper.processElementsWithWord(quotedOccurrencesProcessor, literalsScope, quotedString, UsageSearchContext.IN_CODE or UsageSearchContext.IN_STRINGS, true) } fun processUsagesInStrings(moduleName: String, substring: String) { val quotedOccurrencesProcessor = TextOccurenceProcessor { element, offset -> val text = element.text if (text[0] == '"' && text.lastOrNull() == '"' || text[0] == '\'' && text.lastOrNull() == '\'') { consumer.process(UsageInfo(element, offset + substring.indexOf(moduleName), offset + substring.length)) } else { true } } searchHelper.processElementsWithWord(quotedOccurrencesProcessor, scope, substring, UsageSearchContext.IN_STRINGS, true) } for ((i, moduleName) in moduleNames.withIndex()) { progress.fraction = i.toDouble() / moduleNames.size progress.text2 = "Searching for \"$moduleName\"" processCodeUsages(moduleName, "\"$moduleName\"", groovyOnly = false) processCodeUsages(moduleName, "'$moduleName'", groovyOnly = true) if (moduleName != "resources") { processUsagesInStrings(moduleName, "production/$moduleName") processUsagesInStrings(moduleName, "test/$moduleName") } val plainOccurrencesProcessor = TextOccurenceProcessor { element, offset -> val endOffset = offset + moduleName.length if ((offset == 0 || element.text[offset - 1].isWhitespace()) && (endOffset == element.textLength || element.text[endOffset].isWhitespace()) && element is PsiPlainText) { consumer.process(UsageInfo(element, offset, endOffset)) } else true } val plainTextScope = if (moduleName in regularWordsUsedAsModuleNames + moduleNamesUsedAsIDs) scope.filter {it.name == "plugin-list.txt"} else scope searchHelper.processElementsWithWord(plainOccurrencesProcessor, plainTextScope, moduleName, UsageSearchContext.IN_PLAIN_TEXT, true) if (moduleName !in regularWordsUsedAsModuleNames) { val commentsOccurrencesProcessor = TextOccurenceProcessor { element, offset -> val endOffset = offset + moduleName.length if ((offset == 0 || !element.text[offset - 1].isModuleNamePart() && element.text[offset-1] != '.') && (endOffset == element.textLength || !element.text[endOffset].isModuleNamePart() && element.text[endOffset] != '/' && !(endOffset < element.textLength - 2 && element.text[endOffset] == '.' && element.text[endOffset+1].isLetter())) && element is PsiComment) { consumer.process(UsageInfo(element, offset, endOffset)) } else true } searchHelper.processElementsWithWord(commentsOccurrencesProcessor, scope, moduleName, UsageSearchContext.IN_COMMENTS, true) } } } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = PsiUtil.isIdeaProject(e.project) } } private class ModuleNameUsageTarget(val moduleName: String) : UsageTarget, ItemPresentation { override fun getFiles() = null override fun getPresentation() = this override fun canNavigate() = false override fun getName() = "\"$moduleName\"" override fun findUsages() { throw UnsupportedOperationException() } override fun canNavigateToSource() = false override fun isReadOnly() = true override fun navigate(requestFocus: Boolean) { throw UnsupportedOperationException() } override fun findUsagesInEditor(editor: FileEditor) { } override fun highlightUsages(file: PsiFile, editor: Editor, clearHighlights: Boolean) { } override fun isValid() = true override fun update() { } override fun getPresentableText() = "Occurrences of \"$moduleName\"" override fun getLocationString() = null override fun getIcon(unused: Boolean) = AllIcons.Nodes.Module!! } private val regularWordsUsedAsModuleNames = setOf( "CloudBees", "AngularJS", "CloudFoundry", "CSS", "CFML", "Docker", "Dart", "EJS", "Guice", "Heroku", "Jade", "Kubernetes", "LiveEdit", "OpenShift", "Meteor", "NodeJS", "Perforce", "TFS", "WSL", "analyzer", "android", "ant", "annotations", "appcode", "artwork", "asp", "aspectj", "behat", "boot", "bootstrap", "build", "blade", "commandLineTool", "chronon", "codeception", "common", "commander", "copyright", "coverage", "dependencies", "designer", "ddmlib", "doxygen", "draw9patch", "drupal", "duplicates", "drools", "eclipse", "el", "emma", "editorconfig", "extensions", "flex", "gherkin", "flags", "freemarker", "github", "gradle", "haml", "graph", "icons", "idea", "images", "ipnb", "jira", "joomla", "jbpm", "json", "junit", "layoutlib", "less", "localization", "manifest", "main", "markdown", "maven", "ognl", "openapi", "ninepatch", "perflib", "observable", "phing", "php", "phpspec", "pixelprobe", "play", "profilers", "properties", "puppet", "postcss", "python", "repository", "resources", "rs", "relaxng", "restClient", "rest", "ruby", "sass", "sdklib", "seam", "ssh", "spellchecker", "stylus", "swift", "terminal", "tomcat", "textmate", "testData", "testFramework", "testng", "testRunner", "twig", "util", "updater", "vaadin", "vagrant", "vuejs", "velocity", "weblogic", "websocket", "wizard", "ws", "wordPress", "xml", "xpath", "yaml", "usageView", "error-prone", "spy-js", "WebStorm", "javac2", "dsm", "clion", "phpstorm", "WebComponents" ) private val moduleNamesUsedAsIDs = setOf("spring-integration", "spring-aop", "spring-mvc", "spring-security", "spring-webflow", "git4idea", "dvlib", "hg4idea", "JsTestDriver", "ByteCodeViewer", "appcode-designer", "dsm", "flex", "google-app-engine", "phpstorm-workshop", "ruby-core", "ruby-slim", "spring-ws", "svn4idea", "Yeoman", "spring-batch", "spring-data", "sdk-common", "ui-designer")
apache-2.0
186e795a4a1f2cca6eb217acf24cfee3
50.307692
232
0.68028
4.854766
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/ide/RecentProjectMetaInfo.kt
1
2223
// 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 com.intellij.ide import com.intellij.openapi.components.BaseState import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.wm.impl.FrameInfo import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.MapAnnotation import com.intellij.util.xmlb.annotations.OptionTag import com.intellij.util.xmlb.annotations.Property import java.util.concurrent.atomic.LongAdder class RecentProjectMetaInfo : BaseState() { @get:Attribute var opened by property(false) @get:Attribute var displayName by string() // to set frame title as early as possible @get:Attribute var frameTitle by string() var build by string() var productionCode by string() var eap by property(false) var binFolder by string() var projectOpenTimestamp by property(0L) var buildTimestamp by property(0L) var activationTimestamp by property(0L) var metadata by string() @get:Attribute var projectWorkspaceId by string() @get:Property(surroundWithTag = false) internal var frame: FrameInfo? by property() } class RecentProjectManagerState : BaseState() { @Deprecated("") @get:OptionTag val recentPaths by list<String>() @get:OptionTag val groups by list<ProjectGroup>() var pid by string() @get:OptionTag @get:MapAnnotation(sortBeforeSave = false) val additionalInfo by linkedMap<String, RecentProjectMetaInfo>() var lastProjectLocation by string() var lastOpenedProject by string() fun validateRecentProjects(modCounter: LongAdder) { val limit = AdvancedSettings.getInt("ide.max.recent.projects") if (additionalInfo.size <= limit || limit < 1) { return } // might be freezing for many projects that were stored as "opened" while (additionalInfo.size > limit) { val iterator = additionalInfo.keys.iterator() while (iterator.hasNext()) { val path = iterator.next() if (!additionalInfo.get(path)!!.opened) { iterator.remove() break } } } modCounter.increment() } }
apache-2.0
55f36e0652c29d402518fdc483f14068
27.512821
120
0.733243
4.258621
false
false
false
false
google/iosched
shared/src/main/java/com/google/samples/apps/iosched/shared/domain/feed/GetConferenceStateUseCase.kt
3
2785
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.shared.domain.feed import com.google.samples.apps.iosched.shared.di.MainDispatcher import com.google.samples.apps.iosched.shared.domain.FlowUseCase import com.google.samples.apps.iosched.shared.domain.feed.ConferenceState.ENDED import com.google.samples.apps.iosched.shared.domain.feed.ConferenceState.STARTED import com.google.samples.apps.iosched.shared.domain.feed.ConferenceState.UPCOMING import com.google.samples.apps.iosched.shared.result.Result import com.google.samples.apps.iosched.shared.time.TimeProvider import com.google.samples.apps.iosched.shared.util.TimeUtils import javax.inject.Inject import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import org.threeten.bp.Duration enum class ConferenceState { UPCOMING, STARTED, ENDED } /** * Gets the current [ConferenceState]. */ class GetConferenceStateUseCase @Inject constructor( @MainDispatcher val mainDispatcher: CoroutineDispatcher, private val timeProvider: TimeProvider ) : FlowUseCase<Unit?, ConferenceState>(mainDispatcher) { override fun execute(parameters: Unit?): Flow<Result<ConferenceState>> { return moveToNextState().map { Result.Success(it) } } private fun moveToNextState(): Flow<ConferenceState> = flow { do { val (nextState, delayForLaterState) = getNextStateWithDelay() emit(nextState) delay(delayForLaterState ?: 0) } while (nextState != ENDED) } private fun getNextStateWithDelay(): Pair<ConferenceState, Long?> { val timeUntilStart = Duration.between(timeProvider.now(), TimeUtils.getKeynoteStartTime()) return if (timeUntilStart.isNegative) { val timeUntilEnd = Duration.between(timeProvider.now(), TimeUtils.getConferenceEndTime()) if (timeUntilEnd.isNegative) { Pair(ENDED, null) } else { Pair(STARTED, timeUntilEnd.toMillis()) } } else { Pair(UPCOMING, timeUntilStart.toMillis()) } } }
apache-2.0
8afa3cd35f703bc58336aabfe9789c2a
38.225352
98
0.728187
4.413629
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/injection/auth/AuthDataModule.kt
2
6473
package org.stepik.android.view.injection.auth import dagger.Binds import dagger.Module import dagger.Provides import dagger.multibindings.IntoSet import okhttp3.Credentials import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Protocol import org.stepic.droid.configuration.EndpointResolver import org.stepic.droid.di.AppSingleton import org.stepic.droid.util.AppConstants import org.stepic.droid.util.DebugToolsHelper import org.stepic.droid.util.addUserAgent import org.stepic.droid.util.setTimeoutsInSeconds import org.stepik.android.data.auth.repository.AuthRepositoryImpl import org.stepik.android.data.auth.source.AuthRemoteDataSource import org.stepik.android.domain.auth.repository.AuthRepository import org.stepik.android.remote.auth.AuthRemoteDataSourceImpl import org.stepik.android.remote.auth.interceptor.AuthInterceptor import org.stepik.android.remote.auth.model.TokenType import org.stepik.android.remote.auth.service.EmptyAuthService import org.stepik.android.remote.auth.service.OAuthService import org.stepik.android.remote.base.CookieHelper import org.stepik.android.remote.base.NetworkFactory import org.stepik.android.remote.base.UserAgentProvider import org.stepik.android.view.injection.qualifiers.AuthLock import org.stepik.android.view.injection.qualifiers.AuthService import org.stepik.android.view.injection.qualifiers.CookieAuthService import org.stepik.android.view.injection.qualifiers.SocialAuthService import retrofit2.Converter import java.util.concurrent.locks.ReentrantReadWriteLock @Module abstract class AuthDataModule { @Binds @IntoSet internal abstract fun bindAuthInterceptor(authInterceptor: AuthInterceptor): Interceptor @Binds @AppSingleton abstract fun bindAuthRepository(authRepositoryImpl: AuthRepositoryImpl): AuthRepository @Binds internal abstract fun bindAuthRemoteDataSource(authRemoteDataSourceImpl: AuthRemoteDataSourceImpl): AuthRemoteDataSource @Module companion object { private val debugInterceptors = DebugToolsHelper.getDebugInterceptors() private fun addDebugInterceptors(okHttpBuilder: OkHttpClient.Builder) { debugInterceptors.forEach { okHttpBuilder.addNetworkInterceptor(it) } } @Provides @AppSingleton @JvmStatic @AuthLock internal fun provideAuthLock(): ReentrantReadWriteLock = ReentrantReadWriteLock() @Provides @AppSingleton @JvmStatic internal fun provideEmptyAuthService( endpointResolver: EndpointResolver, userAgentProvider: UserAgentProvider, converterFactory: Converter.Factory ): EmptyAuthService { val okHttpBuilder = OkHttpClient.Builder() okHttpBuilder.setTimeoutsInSeconds(NetworkFactory.TIMEOUT_IN_SECONDS) addDebugInterceptors(okHttpBuilder) okHttpBuilder.addInterceptor { chain -> chain.proceed(chain.addUserAgent(userAgentProvider.provideUserAgent())) } val retrofit = NetworkFactory.createRetrofit(endpointResolver.getBaseUrl(), okHttpBuilder.build(), converterFactory) return retrofit.create(EmptyAuthService::class.java) } @Provides @AppSingleton @JvmStatic @SocialAuthService internal fun provideSocialAuthService( endpointResolver: EndpointResolver, userAgentProvider: UserAgentProvider, converterFactory: Converter.Factory ): OAuthService = createAuthService( Credentials.basic(endpointResolver.getOAuthClientId(TokenType.SOCIAL), endpointResolver.getOAuthClientSecret(TokenType.SOCIAL)), userAgentProvider.provideUserAgent(), endpointResolver.getBaseUrl(), converterFactory ) @Provides @AppSingleton @JvmStatic @AuthService internal fun provideAuthService( endpointResolver: EndpointResolver, userAgentProvider: UserAgentProvider, converterFactory: Converter.Factory ): OAuthService = createAuthService( Credentials.basic( endpointResolver.getOAuthClientId(TokenType.LOGIN_PASSWORD), endpointResolver.getOAuthClientSecret(TokenType.LOGIN_PASSWORD) ), userAgentProvider.provideUserAgent(), endpointResolver.getBaseUrl(), converterFactory ) @Provides @AppSingleton @JvmStatic @CookieAuthService internal fun provideCookieAuthService( endpointResolver: EndpointResolver, userAgentProvider: UserAgentProvider, cookieHelper: CookieHelper, converterFactory: Converter.Factory ): OAuthService { val okHttpBuilder = OkHttpClient.Builder() okHttpBuilder.addNetworkInterceptor { chain -> cookieHelper.removeCookiesCompat() cookieHelper.fetchCookiesForBaseUrl() chain.proceed( cookieHelper.addCsrfTokenToRequest( chain.addUserAgent(userAgentProvider.provideUserAgent()) ) ) } okHttpBuilder.setTimeoutsInSeconds(NetworkFactory.TIMEOUT_IN_SECONDS) addDebugInterceptors(okHttpBuilder) val retrofit = NetworkFactory.createRetrofit(endpointResolver.getBaseUrl(), okHttpBuilder.build(), converterFactory) return retrofit.create(OAuthService::class.java) } private fun createAuthService(credentials: String, userAgent: String, host: String, converterFactory: Converter.Factory): OAuthService { val okHttpBuilder = OkHttpClient.Builder() okHttpBuilder.addInterceptor { chain -> chain.proceed(chain.addUserAgent(userAgent).newBuilder().header(AppConstants.authorizationHeaderName, credentials).build()) } okHttpBuilder.protocols(listOf(Protocol.HTTP_1_1)) okHttpBuilder.setTimeoutsInSeconds(NetworkFactory.TIMEOUT_IN_SECONDS) addDebugInterceptors(okHttpBuilder) val retrofit = NetworkFactory.createRetrofit(host, okHttpBuilder.build(), converterFactory) return retrofit.create(OAuthService::class.java) } } }
apache-2.0
5f0369a33cd5611fad1d46e8c422ef6a
39.974684
144
0.704465
5.698063
false
false
false
false
mcroghan/personal
KotlinFun/app/src/main/java/com/freesourfruit/kotlinfun/MainActivity.kt
1
3978
package com.freesourfruit.kotlinfun import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.WindowManager import android.view.inputmethod.EditorInfo import android.widget.EditText import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val editText = findViewById(R.id.editText) as EditText val textView = findViewById(R.id.textView) as TextView editText.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { textView.text = editText.text.toString().toIntOrNull()?.toEnglish() ?: "Sorry, that's greater than the maximum integer." true } else { false } } if (editText.requestFocus()) window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE) } private fun String.collapseSpaces() = this.replace("""\s+""".toRegex(), " ") private fun Int.toEnglish(): String = when(this.toString().length) { 1 -> this.digitToEnglish() 2 -> this.tensToEnglish() 3 -> this.hundredsToEnglish().collapseSpaces() in 4..6 -> this.thousandsToEnglish().collapseSpaces() in 7..9 -> this.millionsToEnglish().collapseSpaces() 10 -> this.billionsToEnglish().collapseSpaces() // max int is 2,147,483,647 else -> "ERROR" } private fun Int.digitToEnglish(): String = when(this % 10) { 0 -> "zero" 1 -> "one" 2 -> "two" 3 -> "three" 4 -> "four" 5 -> "five" 6 -> "six" 7 -> "seven" 8 -> "eight" 9 -> "nine" else -> "ERROR" } private fun Int.tensToEnglish(): String = when(this % 100) { 0 -> "" in 1..9 -> this.digitToEnglish() 10 -> "ten" 11 -> "eleven" 12 -> "twelve" 13 -> "thirteen" 14 -> "fourteen" 15 -> "fifteen" 16 -> "sixteen" 17 -> "seventeen" 18 -> "eighteen" 19 -> "nineteen" 20 -> "twenty" 30 -> "thirty" 40 -> "forty" 50 -> "fifty" 60 -> "sixty" 70 -> "seventy" 80 -> "eighty" 90 -> "ninety" in 21..29, in 31..39, in 41..49, in 51..59, in 61..69, in 71..79, in 81..89, in 91..99 -> (this - this % 10).tensToEnglish().plus(" ").plus(this.digitToEnglish()) else -> "ERROR" } private fun Int.magnitudeToEnglish(myMagnitude: Int, nextHigherMagnitude: Long, myName: String, toSayMyMagnitude: Int.() -> String, toSayLowerMagnitudes: Int.() -> String): String { val digitsICareAbout = (this % nextHigherMagnitude).toInt() // if it's billions, nextHigherMagnitude could be a Long val myMagnitudeDigits = (digitsICareAbout - digitsICareAbout % myMagnitude) / myMagnitude // strip off lower magnitudes for now val myMagnitudeEnglish = if (myMagnitudeDigits > 0) myMagnitudeDigits.toSayMyMagnitude().plus(" $myName ") else "" return myMagnitudeEnglish.plus(this.toSayLowerMagnitudes()) } private fun Int.hundredsToEnglish() = this.magnitudeToEnglish(100, 1000, "hundred", { digitToEnglish() }, { tensToEnglish() }) private fun Int.thousandsToEnglish() = this.magnitudeToEnglish(1000, 1000000, "thousand", { hundredsToEnglish() }, { hundredsToEnglish() }) private fun Int.millionsToEnglish() = this.magnitudeToEnglish(1000000, 1000000000, "million", { hundredsToEnglish() }, { thousandsToEnglish() }) private fun Int.billionsToEnglish() = this.magnitudeToEnglish(1000000000, 10000000000L, "billion", { digitToEnglish() }, { millionsToEnglish() }) }
gpl-2.0
a5fbed87259d5b3b295b5f86e62612c9
42.25
185
0.592257
4.319218
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/lazyCodegen/increment.kt
4
520
var holder = "" var globalA: A = A(-1) get(): A { holder += "getA" return field } class A(val p: Int) { var prop = this operator fun inc(): A { return A(p+1) } } fun box(): String { var a = A(1) ++a if (a.p != 2) return "fail 1: ${a.p} $holder" globalA = A(1) ++(globalA.prop) val holderValue = holder; if (globalA.p != 1 || globalA.prop.p != 2 || holderValue != "getA") return "fail 2: ${a.p} ${a.prop.p} ${holderValue}" return "OK" }
apache-2.0
9b16dd691df6dc58aa80e4cb57f6d42e
15.806452
122
0.490385
2.84153
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/codegen/bridges/test14.kt
1
751
package codegen.bridges.test14 import kotlin.test.* open class A<T, U> { open fun foo(x: T, y: U) { println(x.toString()) println(y.toString()) } } interface I1<T> { fun foo(x: Int, y: T) } interface I2<T> { fun foo(x: T, y: Int) } class B : A<Int, Int>(), I1<Int>, I2<Int> { var z: Int = 5 var q: Int = 7 override fun foo(x: Int, y: Int) { z = x q = y } } fun zzz(a: A<Int, Int>) { a.foo(42, 56) } @Test fun runTest() { val b = B() zzz(b) val a = A<Int, Int>() zzz(a) println(b.z) println(b.q) val i1: I1<Int> = b i1.foo(56, 42) println(b.z) println(b.q) val i2: I2<Int> = b i2.foo(156, 142) println(b.z) println(b.q) }
apache-2.0
f4ab9587fa6c0b8916fc895a7132eb0a
14.666667
43
0.492676
2.407051
false
true
false
false
aconsuegra/algorithms-playground
src/main/kotlin/me/consuegra/algorithms/KReverseInteger.kt
1
1211
package me.consuegra.algorithms /** * Reverse digits of an integer. * <p> * Example1: x = 123, return 321 * Example2: x = -123, return -321 * <p> * The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer * overflows. */ class KReverseInteger { fun reverse1(input: Int): Int { val isNegative = input < 0 val sb = StringBuilder() var positiveInput = Math.abs(input) while (positiveInput > 0) { sb.append(positiveInput % 10) positiveInput /= 10 } if (isNegative) { sb.insert(0, "-") } try { return Integer.parseInt(sb.toString()) } catch (e: NumberFormatException) { return 0 } } fun reverse2(input: Int): Int { val isNegative = input < 0 var positiveInput = Math.abs(input) var acc: Long = 0 while (positiveInput > 0) { acc = acc * 10 + positiveInput % 10 if (acc > Integer.MAX_VALUE) { return 0 } positiveInput /= 10 } return if (isNegative) -1 * acc.toInt() else acc.toInt() } }
mit
b72762ba039ceb3b0a5421f4e9c08a90
25.326087
110
0.535095
4.14726
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/stdlib/collections/MapTest/populateTo.kt
2
689
import kotlin.test.* fun box() { val pairs = arrayOf("a" to 1, "b" to 2) val expected = mapOf(*pairs) val linkedMap: LinkedHashMap<String, Int> = pairs.toMap(linkedMapOf()) assertEquals(expected, linkedMap) val hashMap: HashMap<String, Int> = pairs.asIterable().toMap(hashMapOf()) assertEquals(expected, hashMap) val mutableMap: MutableMap<String, Int> = pairs.asSequence().toMap(mutableMapOf()) assertEquals(expected, mutableMap) val mutableMap2 = mutableMap.toMap(mutableMapOf()) assertEquals(expected, mutableMap2) val mutableMap3 = mutableMap.toMap(hashMapOf<CharSequence, Any>()) assertEquals<Map<*, *>>(expected, mutableMap3) }
apache-2.0
80bacee009de8adf6013ebd5f12951e0
30.318182
86
0.703919
4.253086
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/api/components/webview/events/TopLoadingProgressEvent.kt
2
795
package abi43_0_0.host.exp.exponent.modules.api.components.webview.events import abi43_0_0.com.facebook.react.bridge.WritableMap import abi43_0_0.com.facebook.react.uimanager.events.Event import abi43_0_0.com.facebook.react.uimanager.events.RCTEventEmitter /** * Event emitted when there is a loading progress event. */ class TopLoadingProgressEvent(viewId: Int, private val mEventData: WritableMap) : Event<TopLoadingProgressEvent>(viewId) { companion object { const val EVENT_NAME = "topLoadingProgress" } override fun getEventName(): String = EVENT_NAME override fun canCoalesce(): Boolean = false override fun getCoalescingKey(): Short = 0 override fun dispatch(rctEventEmitter: RCTEventEmitter) = rctEventEmitter.receiveEvent(viewTag, eventName, mEventData) }
bsd-3-clause
0fcf29ec7513d0339df2e79dfa1234b0
32.125
81
0.778616
4.097938
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/execution/wsl/WslExecution.kt
7
4917
// 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. @file:JvmName("WslExecution") package com.intellij.execution.wsl import com.intellij.execution.CommandLineUtil import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.process.ProcessHandler import com.intellij.execution.process.ProcessOutput import com.intellij.execution.wsl.WSLUtil.LOG import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.text.StringUtil import com.intellij.util.EnvironmentUtil import com.intellij.util.LineSeparator import com.intellij.util.containers.ContainerUtil import java.util.function.Consumer @JvmOverloads @Throws(ExecutionException::class) fun WSLDistribution.executeInShellAndGetCommandOnlyStdout(commandLine: GeneralCommandLine, options: WSLCommandLineOptions, timeout: Int, processHandlerCustomizer: Consumer<ProcessHandler> = Consumer {}): ProcessOutput { if (!options.isExecuteCommandInShell) { throw AssertionError("Execution in shell is expected") } // When command is executed in interactive/login shell, the result stdout may contain additional output // produced by shell configuration files, for example, "Message Of The Day". // Let's print some unique message before executing the command to know where command output begins in the result output. val prefixText = "intellij: executing command..." options.addInitCommand("echo " + CommandLineUtil.posixQuote(prefixText)) if (options.isExecuteCommandInInteractiveShell) { // Disable oh-my-zsh auto update on shell initialization commandLine.environment[EnvironmentUtil.DISABLE_OMZ_AUTO_UPDATE] = "true" options.isPassEnvVarsUsingInterop = true } val output: ProcessOutput = executeOnWsl(commandLine, options, timeout, processHandlerCustomizer) val stdout = output.stdout val markerText = prefixText + LineSeparator.LF.separatorString val index = stdout.indexOf(markerText) if (index < 0) { val application = ApplicationManager.getApplication() if (application == null || application.isInternal || application.isUnitTestMode) { LOG.error("Cannot find '$prefixText' in stdout: $output") } else { LOG.info("Cannot find '$prefixText' in stdout") } return output } return ProcessOutput(stdout.substring(index + markerText.length), output.stderr, output.exitCode, output.isTimeout, output.isCancelled) } fun WSLDistribution.executeInShellAndGetCommandOnlyStdout(commandLine: GeneralCommandLine, options: WSLCommandLineOptions, timeout: Int, expectOneLineStdout: Boolean): String? { try { val output: ProcessOutput = executeInShellAndGetCommandOnlyStdout(commandLine, options, timeout) val stdout = output.stdout if (!output.isTimeout && output.exitCode == 0) { return if (expectOneLineStdout) expectOneLineOutput(commandLine, stdout) else stdout } LOG.info("Failed to execute $commandLine for $msId: exitCode=${output.exitCode}, timeout=${output.isTimeout}," + " stdout=$stdout, stderr=${output.stderr}") } catch (e: ExecutionException) { LOG.info("Failed to execute $commandLine for $msId", e) } return null } private fun WSLDistribution.expectOneLineOutput(commandLine: GeneralCommandLine, stdout: String): String { val converted = StringUtil.convertLineSeparators(stdout, LineSeparator.LF.separatorString) val lines = StringUtil.split(converted, LineSeparator.LF.separatorString, true, true) if (lines.size != 1) { LOG.info("One line stdout expected: " + msId + ", command=" + commandLine + ", stdout=" + stdout + ", lines=" + lines.size) } return StringUtil.notNullize(ContainerUtil.getFirstItem(lines), stdout) } @Throws(ExecutionException::class) private fun WSLDistribution.executeOnWsl(commandLine: GeneralCommandLine, options: WSLCommandLineOptions, timeout: Int, processHandlerCustomizer: Consumer<ProcessHandler>): ProcessOutput { patchCommandLine<GeneralCommandLine>(commandLine, null, options) val processHandler = CapturingProcessHandler(commandLine) processHandlerCustomizer.accept(processHandler) return processHandler.runProcess(timeout) }
apache-2.0
1bacbc4efdd36df083ba0c474473f41a
49.701031
158
0.694122
5.164916
false
false
false
false
ianhanniballake/muzei
source-gallery/src/main/java/com/google/android/apps/muzei/gallery/GalleryProvider.kt
1
6483
/* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.gallery import android.content.ContentProvider import android.content.ContentUris import android.content.ContentValues import android.content.Context import android.database.Cursor import android.net.Uri import android.os.ParcelFileDescriptor import android.util.Log import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import java.io.File import java.io.FileNotFoundException import java.io.UnsupportedEncodingException import java.security.MessageDigest import java.security.NoSuchAlgorithmException /** * Provides access to the Gallery's chosen photos through [.openFile]. Queries, * inserts, updates, and deletes are not supported and should instead go through * [GalleryDatabase]. */ class GalleryProvider : ContentProvider() { companion object { private const val TAG = "GalleryProvider" internal fun getCacheFileForUri(context: Context, uri: Uri): File? { val directory = File(context.getExternalFilesDir(null), "gallery_images") if (!directory.exists() && !directory.mkdirs()) { return null } // Create a unique filename based on the imageUri val filename = StringBuilder() filename.append(uri.scheme).append("_") .append(uri.host).append("_") val encodedPath = uri.encodedPath.takeUnless { it.isNullOrEmpty() }?.run { if (length > 60) { substring(length - 60) } else { this }.replace('/', '_') } if (encodedPath != null) { filename.append(encodedPath).append("_") } try { val md = MessageDigest.getInstance("MD5") md.update(uri.toString().toByteArray(charset("UTF-8"))) val digest = md.digest() filename.append(digest.joinToString(separator = "") { it.toInt().and(0xff).toString(16).padStart(2, '0') }) } catch (e: NoSuchAlgorithmException) { filename.append(uri.toString().hashCode()) } catch (e: UnsupportedEncodingException) { filename.append(uri.toString().hashCode()) } return File(directory, filename.toString()) } } override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int { throw UnsupportedOperationException("Deletes are not supported") } override fun getType(uri: Uri): String? { return "vnd.android.cursor.item/vnd.google.android.apps.muzei.gallery.chosen_photos" } override fun insert(uri: Uri, values: ContentValues?): Uri? { throw UnsupportedOperationException("Inserts are not supported") } override fun onCreate(): Boolean { return true } override fun query( uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String? ): Cursor? { throw UnsupportedOperationException("Queries are not supported") } @Throws(FileNotFoundException::class) override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? { val context: Context = context ?: return null require(mode == "r") { "Only reading chosen photos is allowed" } val id = ContentUris.parseId(uri) val chosenPhoto = GalleryDatabase.getInstance(context).chosenPhotoDao() .chosenPhotoBlocking(id) ?: throw FileNotFoundException("Unable to load $uri") val file = getCacheFileForUri(context, chosenPhoto.uri) if (file == null || !file.exists()) { // Assume we have persisted URI permission to the imageUri and can read the image directly from the imageUri try { return context.contentResolver.openFileDescriptor(chosenPhoto.uri, mode) } catch (e: SecurityException) { Log.d(TAG, "Unable to load $uri, deleting the row", e) GlobalScope.launch { GalleryDatabase.getInstance(context).chosenPhotoDao() .delete(context, listOf(chosenPhoto.id)) } throw FileNotFoundException("No permission to load $uri") } catch (e: IllegalArgumentException) { Log.d(TAG, "Unable to load $uri, deleting the row", e) GlobalScope.launch { GalleryDatabase.getInstance(context).chosenPhotoDao() .delete(context, listOf(chosenPhoto.id)) } throw FileNotFoundException("No permission to load $uri") } catch (e: UnsupportedOperationException) { Log.d(TAG, "Unable to load $uri, deleting the row", e) GlobalScope.launch { GalleryDatabase.getInstance(context).chosenPhotoDao() .delete(context, listOf(chosenPhoto.id)) } throw FileNotFoundException("No permission to load $uri") } catch (e: NullPointerException) { Log.d(TAG, "Unable to load $uri, deleting the row", e) GlobalScope.launch { GalleryDatabase.getInstance(context).chosenPhotoDao() .delete(context, listOf(chosenPhoto.id)) } throw FileNotFoundException("No permission to load $uri") } } return ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode(mode)) } override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int { throw UnsupportedOperationException("Updates are not supported") } }
apache-2.0
1e8ab041f5be9479ae2f17b8b08dc220
40.564103
120
0.615302
5.149325
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/utils/SkillDeserializer.kt
1
1607
package com.habitrpg.android.habitica.utils import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonParseException import com.habitrpg.android.habitica.models.Skill import java.lang.reflect.Type import java.util.* /** * Created by viirus on 25/11/15. */ class SkillDeserializer : JsonDeserializer<List<Skill>> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext): List<Skill> { val jsonObject = json.asJsonObject val skills = ArrayList<Skill>() for ((classname, value) in jsonObject.entrySet()) { for ((_, value1) in value.asJsonObject.entrySet()) { val skillObject = value1.asJsonObject val skill = Skill() skill.key = skillObject.get("key").asString skill.text = skillObject.get("text").asString skill.notes = skillObject.get("notes").asString skill.key = skillObject.get("key").asString skill.target = skillObject.get("target").asString skill.habitClass = classname skill.mana = skillObject.get("mana").asInt val lvlElement = skillObject.get("lvl") if (lvlElement != null) { skill.lvl = lvlElement.asInt } skills.add(skill) } } return skills } }
gpl-3.0
762ced4b962e7599d770d05c142cfa0b
33.755556
80
0.591786
4.89939
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveCurlyBracesFromTemplateInspection.kt
2
2337
// 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.ProblemHighlightType import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.canDropCurlyBrackets import org.jetbrains.kotlin.idea.base.psi.dropCurlyBracketsIfPossible import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection import org.jetbrains.kotlin.psi.KtBlockStringTemplateEntry class RemoveCurlyBracesFromTemplateInspection(@JvmField var reportWithoutWhitespace: Boolean = false) : AbstractApplicabilityBasedInspection<KtBlockStringTemplateEntry>(KtBlockStringTemplateEntry::class.java) { override fun inspectionText(element: KtBlockStringTemplateEntry): String = KotlinBundle.message("redundant.curly.braces.in.string.template") override fun inspectionHighlightType(element: KtBlockStringTemplateEntry) = if (reportWithoutWhitespace || element.hasWhitespaceAround()) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION override val defaultFixText: String get() = KotlinBundle.message("remove.curly.braces") override fun isApplicable(element: KtBlockStringTemplateEntry): Boolean = element.canDropCurlyBrackets() override fun applyTo(element: KtBlockStringTemplateEntry, project: Project, editor: Editor?) { element.dropCurlyBracketsIfPossible() } override fun createOptionsPanel() = MultipleCheckboxOptionsPanel(this).apply { addCheckbox(KotlinBundle.message("report.also.for.a.variables.without.a.whitespace.around"), "reportWithoutWhitespace") } } private fun KtBlockStringTemplateEntry.hasWhitespaceAround(): Boolean = prevSibling?.isWhitespaceOrQuote(true) == true && nextSibling?.isWhitespaceOrQuote(false) == true private fun PsiElement.isWhitespaceOrQuote(prev: Boolean): Boolean { val char = if (prev) text.lastOrNull() else text.firstOrNull() return char != null && (char.isWhitespace() || char == '"') }
apache-2.0
a815e2e5e4d9970f4f43210fda843113
52.113636
127
0.804878
5.216518
false
false
false
false
siosio/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/inspection/grammar/quickfix/GrazieReplaceTypoQuickFix.kt
1
4410
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.grazie.ide.inspection.grammar.quickfix import com.intellij.codeInsight.daemon.impl.UpdateHighlightersUtil import com.intellij.codeInsight.intention.FileModifier import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.choice.ChoiceTitleIntentionAction import com.intellij.codeInsight.intention.choice.ChoiceVariantIntentionAction import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.util.IntentionFamilyName import com.intellij.codeInspection.util.IntentionName import com.intellij.grazie.GrazieBundle import com.intellij.grazie.ide.fus.GrazieFUSCounter import com.intellij.grazie.ide.ui.components.dsl.msg import com.intellij.grazie.text.Rule import com.intellij.grazie.text.TextProblem import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiFile import com.intellij.psi.SmartPointerManager import com.intellij.psi.SmartPsiFileRange import kotlin.math.min internal object GrazieReplaceTypoQuickFix { private class ReplaceTypoTitleAction(@IntentionFamilyName family: String, @IntentionName title: String) : ChoiceTitleIntentionAction(family, title), HighPriorityAction private class ChangeToVariantAction( private val rule: Rule, override val index: Int, @IntentionFamilyName private val family: String, @NlsSafe private val suggestion: String, private val replacement: String, private val underlineRanges: List<SmartPsiFileRange>, private val replacementRange: SmartPsiFileRange, ) : ChoiceVariantIntentionAction(), HighPriorityAction { override fun getName(): String = suggestion.takeIf { it.isNotEmpty() } ?: msg("grazie.grammar.quickfix.remove.typo.tooltip") override fun getTooltipText(): String = if (suggestion.isNotEmpty()) { msg("grazie.grammar.quickfix.replace.typo.tooltip", suggestion) } else { msg("grazie.grammar.quickfix.remove.typo.tooltip") } override fun getFamilyName(): String = family override fun isAvailable(project: Project, editor: Editor?, file: PsiFile): Boolean = replacementRange.range != null override fun getFileModifierForPreview(target: PsiFile): FileModifier = this override fun applyFix(project: Project, file: PsiFile, editor: Editor?) { GrazieFUSCounter.quickFixInvoked(rule, project, "accept.suggestion") val replacementRange = this.replacementRange.range ?: return val document = file.viewProvider.document ?: return underlineRanges.forEach { underline -> underline.range?.let { UpdateHighlightersUtil.removeHighlightersWithExactRange(document, project, it) } } document.replaceString(replacementRange.startOffset, replacementRange.endOffset, replacement) } override fun startInWriteAction(): Boolean = true } fun getReplacementFixes(problem: TextProblem, underlineRanges: List<SmartPsiFileRange>, file: PsiFile): List<LocalQuickFix> { val replacementRange = problem.replacementRange val replacedText = replacementRange.subSequence(problem.text) val spm = SmartPointerManager.getInstance(file.project) val familyName = GrazieBundle.message("grazie.grammar.quickfix.replace.typo.text", problem.shortMessage) val result = arrayListOf<LocalQuickFix>(ReplaceTypoTitleAction(familyName, problem.shortMessage)) problem.corrections.forEachIndexed { index, suggestion -> val commonPrefix = StringUtil.commonPrefixLength(suggestion, replacedText) val commonSuffix = min(StringUtil.commonSuffixLength(suggestion, replacedText), min(suggestion.length, replacementRange.length) - commonPrefix) val localRange = TextRange(replacementRange.startOffset + commonPrefix, replacementRange.endOffset - commonSuffix) val replacement = suggestion.substring(commonPrefix, suggestion.length - commonSuffix) result.add(ChangeToVariantAction( problem.rule, index, familyName, suggestion, replacement, underlineRanges, spm.createSmartPsiFileRangePointer(file, problem.text.textRangeToFile(localRange)))) } return result } }
apache-2.0
0598ab53e994ea08f58bcbc814049cfd
48.550562
150
0.789796
4.846154
false
false
false
false
siosio/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/references/referenceUtil.kt
1
14710
// 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.references import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.builtins.isExtensionFunctionType import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.core.canMoveLambdaOutsideParentheses import org.jetbrains.kotlin.idea.core.moveFunctionLiteralOutsideParentheses import org.jetbrains.kotlin.idea.imports.canBeReferencedViaImport import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.intentions.OperatorToFunctionIntention import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex import org.jetbrains.kotlin.idea.stubindex.KotlinFunctionShortNameIndex import org.jetbrains.kotlin.idea.stubindex.KotlinPropertyShortNameIndex import org.jetbrains.kotlin.idea.stubindex.KotlinTypeAliasShortNameIndex import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver import org.jetbrains.kotlin.idea.util.ProjectRootsUtil import org.jetbrains.kotlin.kdoc.psi.impl.KDocName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.FunctionImportedFromObject import org.jetbrains.kotlin.resolve.PropertyImportedFromObject import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPropertyDescriptor import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedSimpleFunctionDescriptor import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedTypeAliasDescriptor import org.jetbrains.kotlin.util.OperatorNameConventions @Deprecated("For binary compatibility with AS, see KT-42061", replaceWith = ReplaceWith("mainReference")) @get:JvmName("getMainReference") val KtSimpleNameExpression.mainReferenceCompat: KtSimpleNameReference get() = mainReference @Deprecated("For binary compatibility with AS, see KT-42061", replaceWith = ReplaceWith("mainReference")) @get:JvmName("getMainReference") val KtReferenceExpression.mainReferenceCompat: KtReference get() = mainReference @Deprecated("For binary compatibility with AS, see KT-42061", replaceWith = ReplaceWith("mainReference")) @get:JvmName("getMainReference") val KDocName.mainReferenceCompat: KDocReference get() = mainReference @Deprecated("For binary compatibility with AS, see KT-42061", replaceWith = ReplaceWith("mainReference")) @get:JvmName("getMainReference") val KtElement.mainReferenceCompat: KtReference? get() = mainReference // Navigation element of the resolved reference // For property accessor return enclosing property val PsiReference.unwrappedTargets: Set<PsiElement> get() { fun PsiElement.adjust(): PsiElement? = when (val target = unwrapped?.originalElement) { is KtPropertyAccessor -> target.getNonStrictParentOfType<KtProperty>() else -> target } return when (this) { is PsiPolyVariantReference -> multiResolve(false).mapNotNullTo(HashSet()) { it.element?.adjust() } else -> listOfNotNull(resolve()?.adjust()).toSet() } } // fun PsiReference.canBeReferenceTo(candidateTarget: PsiElement): Boolean { // optimization return element.containingFile == candidateTarget.containingFile || ProjectRootsUtil.isInProjectOrLibSource(element, includeScriptsOutsideSourceRoots = true) } fun DeclarationDescriptor.findPsiDeclarations(project: Project, resolveScope: GlobalSearchScope): Collection<PsiElement> { val fqName = importableFqName ?: return emptyList() fun Collection<KtNamedDeclaration>.fqNameFilter() = filter { it.fqName == fqName } return when (this) { is DeserializedClassDescriptor -> KotlinFullClassNameIndex.getInstance()[fqName.asString(), project, resolveScope] is DeserializedTypeAliasDescriptor -> KotlinTypeAliasShortNameIndex.getInstance()[fqName.shortName() .asString(), project, resolveScope].fqNameFilter() is DeserializedSimpleFunctionDescriptor, is FunctionImportedFromObject -> KotlinFunctionShortNameIndex.getInstance()[fqName.shortName() .asString(), project, resolveScope].fqNameFilter() is DeserializedPropertyDescriptor, is PropertyImportedFromObject -> KotlinPropertyShortNameIndex.getInstance()[fqName.shortName() .asString(), project, resolveScope].fqNameFilter() is DeclarationDescriptorWithSource -> listOfNotNull(source.getPsi()) else -> emptyList() } } fun PsiReference.matchesTarget(candidateTarget: PsiElement): Boolean { if (!canBeReferenceTo(candidateTarget)) return false val unwrappedCandidate = candidateTarget.unwrapped?.originalElement ?: return false // Optimizations when (this) { is KtInvokeFunctionReference -> { if (candidateTarget !is KtNamedFunction && candidateTarget !is PsiMethod) return false if ((candidateTarget as PsiNamedElement).name != OperatorNameConventions.INVOKE.asString()) { return false } } is KtDestructuringDeclarationReference -> { if (candidateTarget !is KtNamedFunction && candidateTarget !is KtParameter && candidateTarget !is PsiMethod) return false } is KtSimpleNameReference -> { if (unwrappedCandidate is PsiMethod && !canBePsiMethodReference()) return false } } val element = element if (candidateTarget is KtImportAlias && (element is KtSimpleNameExpression && element.getReferencedName() == candidateTarget.name || this is KDocReference && this.canonicalText == candidateTarget.name) ) { val importDirective = candidateTarget.importDirective ?: return false val importedFqName = importDirective.importedFqName ?: return false val importedDescriptors = importDirective.containingKtFile.resolveImportReference(importedFqName) val importableTargets = unwrappedTargets.mapNotNull { when { it is KtConstructor<*> -> it.containingClassOrObject it is PsiMethod && it.isConstructor -> it.containingClass else -> it } } val project = element.project val resolveScope = element.resolveScope return importedDescriptors.any { it.findPsiDeclarations(project, resolveScope).any { declaration -> declaration in importableTargets } } } if (element is KtLabelReferenceExpression) { when ((element.parent as? KtContainerNode)?.parent) { is KtReturnExpression -> unwrappedTargets.forEach { if (it !is KtFunctionLiteral && !(it is KtNamedFunction && it.name.isNullOrEmpty())) return@forEach it as KtFunction val labeledExpression = it.getLabeledParent(element.getReferencedName()) if (labeledExpression != null) { if (candidateTarget == labeledExpression) return true else return@forEach } val calleeReference = it.getCalleeByLambdaArgument()?.mainReference ?: return@forEach if (calleeReference.matchesTarget(candidateTarget)) return true } is KtBreakExpression, is KtContinueExpression -> unwrappedTargets.forEach { val labeledExpression = (it as? KtExpression)?.getLabeledParent(element.getReferencedName()) ?: return@forEach if (candidateTarget == labeledExpression) return true } } } val targets = unwrappedTargets val manager = candidateTarget.manager if (targets.any { manager.areElementsEquivalent(unwrappedCandidate, it) }) { return true } if (this is KtReference) { return targets.any { it.isConstructorOf(unwrappedCandidate) || it is KtObjectDeclaration && it.isCompanion() && it.getNonStrictParentOfType<KtClass>() == unwrappedCandidate } } // TODO: Workaround for Kotlin constructor search in Java code. To be removed after refactoring of the search API else if (this is PsiJavaCodeReferenceElement && unwrappedCandidate is KtConstructor<*>) { var parent = getElement().parent if (parent is PsiAnonymousClass) { parent = parent.getParent() } if ((parent as? PsiNewExpression)?.resolveConstructor()?.unwrapped == unwrappedCandidate) return true } if (this is PsiJavaCodeReferenceElement && candidateTarget is KtObjectDeclaration && unwrappedTargets.size == 1) { val referredClass = unwrappedTargets.first() if (referredClass is KtClass && candidateTarget in referredClass.companionObjects) { if (parent is PsiImportStaticStatement) return true return parent.reference?.unwrappedTargets?.any { (it is KtProperty || it is KtNamedFunction) && it.parent?.parent == candidateTarget } ?: false } } return false } fun KtSimpleNameReference.canBePsiMethodReference(): Boolean { // NOTE: Accessor references are handled separately, see SyntheticPropertyAccessorReference if (element == (element.parent as? KtCallExpression)?.calleeExpression) return true val callableReference = element.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference } if (callableReference != null) return true val binaryOperator = element.getParentOfTypeAndBranch<KtBinaryExpression> { operationReference } if (binaryOperator != null) return true val unaryOperator = element.getParentOfTypeAndBranch<KtUnaryExpression> { operationReference } if (unaryOperator != null) return true if (element.getNonStrictParentOfType<KtImportDirective>() != null) return true return false } private fun PsiElement.isConstructorOf(unwrappedCandidate: PsiElement) = when { // call to Java constructor this is PsiMethod && isConstructor && containingClass == unwrappedCandidate -> true // call to Kotlin constructor this is KtConstructor<*> && getContainingClassOrObject().isEquivalentTo(unwrappedCandidate) -> true else -> false } fun AbstractKtReference<out KtExpression>.renameImplicitConventionalCall(newName: String?): KtExpression { if (newName == null) return expression val (newExpression, newNameElement) = OperatorToFunctionIntention.convert(expression) if (OperatorNameConventions.INVOKE.asString() == newName && newExpression is KtDotQualifiedExpression) { val canMoveLambda = newExpression.getPossiblyQualifiedCallExpression()?.canMoveLambdaOutsideParentheses() == true OperatorToFunctionIntention.replaceExplicitInvokeCallWithImplicit(newExpression)?.let { newQualifiedExpression -> newQualifiedExpression.getPossiblyQualifiedCallExpression() ?.takeIf { canMoveLambda } ?.let(KtCallExpression::moveFunctionLiteralOutsideParentheses) return newQualifiedExpression } } newNameElement.mainReference.handleElementRename(newName) return newExpression } fun KtElement.resolveMainReferenceToDescriptors(): Collection<DeclarationDescriptor> { val bindingContext = analyze(BodyResolveMode.PARTIAL) return mainReference?.resolveToDescriptors(bindingContext) ?: emptyList() } fun PsiReference.getImportAlias(): KtImportAlias? { return (this as? KtSimpleNameReference)?.getImportAlias() } // ----------- Read/write access ----------------------------------------------------------------------------------------------------------------------- fun KtReference.canBeResolvedViaImport(target: DeclarationDescriptor, bindingContext: BindingContext): Boolean { if (this is KDocReference) { val qualifier = element.getQualifier() ?: return true return if (target.isExtension) { val elementHasFunctionDescriptor = element.resolveMainReferenceToDescriptors().any { it is FunctionDescriptor } val qualifierHasClassDescriptor = qualifier.resolveMainReferenceToDescriptors().any { it is ClassDescriptor } elementHasFunctionDescriptor && qualifierHasClassDescriptor } else { false } } return element.canBeResolvedViaImport(target, bindingContext) } fun KtElement.canBeResolvedViaImport(target: DeclarationDescriptor, bindingContext: BindingContext): Boolean { if (!target.canBeReferencedViaImport()) return false if (target.isExtension) return true // assume that any type of reference can use imports when resolved to extension if (this !is KtNameReferenceExpression) return false val callTypeAndReceiver = CallTypeAndReceiver.detect(this) if (callTypeAndReceiver.receiver != null) { if (target !is PropertyDescriptor || !target.type.isExtensionFunctionType) return false if (callTypeAndReceiver !is CallTypeAndReceiver.DOT && callTypeAndReceiver !is CallTypeAndReceiver.SAFE) return false val resolvedCall = bindingContext[BindingContext.CALL, this].getResolvedCall(bindingContext) as? VariableAsFunctionResolvedCall ?: return false if (resolvedCall.variableCall.explicitReceiverKind.isDispatchReceiver) return false } if (parent is KtThisExpression || parent is KtSuperExpression) return false // TODO: it's a bad design of PSI tree, we should change it return true } fun KtFunction.getCalleeByLambdaArgument(): KtSimpleNameExpression? { val argument = getParentOfTypeAndBranch<KtValueArgument> { getArgumentExpression() } ?: return null val callExpression = when (argument) { is KtLambdaArgument -> argument.parent as? KtCallExpression else -> (argument.parent as? KtValueArgumentList)?.parent as? KtCallExpression } ?: return null return callExpression.calleeExpression as? KtSimpleNameExpression }
apache-2.0
c491221d35b403459bccd3d42b2eb414
48.52862
158
0.733855
5.844259
false
false
false
false
Zhouzhouzhou/AndroidDemo
app/src/main/java/com/zhou/android/kotlin/UndoTestActivity.kt
1
5175
package com.zhou.android.kotlin import android.app.ActivityManager import android.app.Dialog import android.content.* import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.support.v7.app.AlertDialog import android.util.Log import android.view.LayoutInflater import android.view.View import android.widget.Button import android.widget.PopupWindow import android.widget.TextView import com.zhou.android.R import com.zhou.android.common.BaseActivity import com.zhou.android.common.GV import com.zhou.android.common.ToastUtils /** * Created by mxz on 2019/6/5. */ class UndoTestActivity : BaseActivity() { lateinit var text: TextView lateinit var btn: Button override fun setContentView() { setContentView(R.layout.activity_undo) } override fun init() { text = findViewById(R.id.text) btn = findViewById(R.id.popup) // Log.d("zhou", window.callback.toString()) // window.callback = Callback(window.callback)//替换原先的 PhoneWindow Callback,缺点做一个默认callback代理 //动态代理 // val callback = window.callback // val handler = WindowCallbackInvocation(callback) // val proxy: Window.Callback = Proxy.newProxyInstance(Window.Callback::class.java.classLoader, arrayOf(Window.Callback::class.java), handler) as Window.Callback // window.callback = proxy // Log.i("zhou", "proxy >> ${window.callback}") registerReceiver(receiver, IntentFilter().apply { addAction(GV.MONITOR_TIMEOUT) addAction(GV.MONITOR_TIME_COUNT) }) ActivityMonitor.get().inject(this.javaClass, window) } override fun addListener() { findViewById<View>(R.id.dialog).setOnClickListener { val dialog = Dialog(this@UndoTestActivity).apply { setContentView(R.layout.layout_undo_dialog) setCancelable(true) setCanceledOnTouchOutside(true) findViewById<View>(R.id.btnOk).setOnClickListener { this.dismiss() } } dialog.show() } findViewById<View>(R.id.alertDialog).setOnClickListener { AlertDialog.Builder(this@UndoTestActivity) .setTitle("Alert Dialog") .setMessage("Show Dialog") .setPositiveButton("Yes") { dialog: DialogInterface, _ -> dialog.dismiss() }.create().show() } findViewById<View>(R.id.next).setOnClickListener { startActivity(Intent(this@UndoTestActivity, SimpleListKotlinActivity::class.java)) } btn.setOnClickListener { val popup = PopupWindow(this@UndoTestActivity).apply { setBackgroundDrawable(ColorDrawable(Color.parseColor("#C3C3C3"))) contentView = LayoutInflater.from(this@UndoTestActivity).inflate(R.layout.layout_undo_pop, null) } popup.showAsDropDown(btn) } } // override fun onCreate(savedInstanceState: Bundle?) { // super.onCreate(savedInstanceState) // ActivityMonitor.get().inject(this,window) // } override fun onDestroy() { super.onDestroy() unregisterReceiver(receiver) ActivityMonitor.get().onDestroy(this.javaClass) } private val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { intent?.also { when (it.action) { GV.MONITOR_TIME_COUNT -> { val t = "${it.getStringExtra("msg")}\n" text.append(t) } GV.MONITOR_TIMEOUT -> { Log.i("zhou", "UndoTestActivity received msg,finish") ToastUtils.show(this@UndoTestActivity, "timeout,finish!!") // finish() //这里在默认的主页做,我们做个不一样的操作 //如果当前这个是栈顶,我们就关闭自己,不在栈顶,就把前面的弹出栈 val am: ActivityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val list = am.getRunningTasks(1) if (list != null && list.isNotEmpty()) { if ([email protected] == list[0].topActivity?.className) { finish() } else { //这里会重启倒计时,如果在主页其实在白名单中是不会重计时的 context?.startActivity(Intent(context, UndoTestActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) }) } } } } } } } }
mit
9c8a71050e236e67c8f0af7e74a9e223
36.727273
168
0.571601
4.80135
false
true
false
false
JetBrains/kotlin-native
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/ObjCStubs.kt
1
25849
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.native.interop.gen import org.jetbrains.kotlin.native.interop.indexer.* internal fun ObjCMethod.getKotlinParameterNames(forConstructorOrFactory: Boolean = false): List<String> { val selectorParts = this.selector.split(":") val result = mutableListOf<String>() fun String.mangled(): String { var mangled = this while (mangled in result) { mangled = "_$mangled" } return mangled } // The names of all parameters except first must depend only on the selector: this.parameters.forEachIndexed { index, _ -> if (index > 0) { val name = selectorParts[index].takeIf { it.isNotEmpty() } ?: "_$index" result.add(name.mangled()) } } this.parameters.firstOrNull()?.let { val name = this.getFirstKotlinParameterNameCandidate(forConstructorOrFactory) result.add(0, name.mangled()) } if (this.isVariadic) { result.add("args".mangled()) } return result } private fun ObjCMethod.getFirstKotlinParameterNameCandidate(forConstructorOrFactory: Boolean): String { if (forConstructorOrFactory) { val selectorPart = this.selector.takeWhile { it != ':' }.trimStart('_') if (selectorPart.startsWith("init")) { selectorPart.removePrefix("init").removePrefix("With") .takeIf { it.isNotEmpty() }?.let { return it.decapitalize() } } } return this.parameters.first().name?.takeIf { it.isNotEmpty() } ?: "_0" } private fun ObjCMethod.getKotlinParameters( stubIrBuilder: StubsBuildingContext, forConstructorOrFactory: Boolean ): List<FunctionParameterStub> { if (this.isInit && this.parameters.isEmpty() && this.selector != "init") { // Create synthetic Unit parameter, just like Swift does in this case: val parameterName = this.selector.removePrefix("init").removePrefix("With").decapitalize() return listOf(FunctionParameterStub(parameterName, KotlinTypes.unit.toStubIrType())) // Note: this parameter is explicitly handled in compiler. } val names = getKotlinParameterNames(forConstructorOrFactory) // TODO: consider refactoring. val result = mutableListOf<FunctionParameterStub>() this.parameters.mapIndexedTo(result) { index, it -> val kotlinType = stubIrBuilder.mirror(it.type).argType val name = names[index] val annotations = if (it.nsConsumed) listOf(AnnotationStub.ObjC.Consumed) else emptyList() FunctionParameterStub(name, kotlinType.toStubIrType(), isVararg = false, annotations = annotations) } if (this.isVariadic) { result += FunctionParameterStub( names.last(), KotlinTypes.any.makeNullable().toStubIrType(), isVararg = true, annotations = emptyList() ) } return result } private class ObjCMethodStubBuilder( private val method: ObjCMethod, private val container: ObjCContainer, private val isDesignatedInitializer: Boolean, override val context: StubsBuildingContext ) : StubElementBuilder { private val isStret: Boolean private val stubReturnType: StubType val annotations = mutableListOf<AnnotationStub>() private val kotlinMethodParameters: List<FunctionParameterStub> private val external: Boolean private val receiver: ReceiverParameterStub? private val name: String = method.kotlinName private val origin = StubOrigin.ObjCMethod(method, container) private val modality: MemberStubModality private val isOverride: Boolean = container is ObjCClassOrProtocol && method.isOverride(container) init { val returnType = method.getReturnType(container.classOrProtocol) isStret = returnType.isStret(context.configuration.target) stubReturnType = if (returnType.unwrapTypedefs() is VoidType) { KotlinTypes.unit } else { context.mirror(returnType).argType }.toStubIrType() val methodAnnotation = AnnotationStub.ObjC.Method( method.selector, method.encoding, isStret ) annotations += buildObjCMethodAnnotations(methodAnnotation) kotlinMethodParameters = method.getKotlinParameters(context, forConstructorOrFactory = false) external = (container !is ObjCProtocol) modality = when (container) { is ObjCClass -> MemberStubModality.OPEN is ObjCProtocol -> if (method.isOptional) MemberStubModality.OPEN else MemberStubModality.ABSTRACT is ObjCCategory -> MemberStubModality.FINAL } receiver = if (container is ObjCCategory) { val receiverType = ClassifierStubType(context.getKotlinClassFor(container.clazz, isMeta = method.isClass)) ReceiverParameterStub(receiverType) } else null } private fun buildObjCMethodAnnotations(main: AnnotationStub): List<AnnotationStub> = listOfNotNull( main, AnnotationStub.ObjC.ConsumesReceiver.takeIf { method.nsConsumesSelf }, AnnotationStub.ObjC.ReturnsRetained.takeIf { method.nsReturnsRetained } ) fun isDefaultConstructor(): Boolean = method.isInit && method.parameters.isEmpty() override fun build(): List<FunctionalStub> { val replacement = if (method.isInit) { val parameters = method.getKotlinParameters(context, forConstructorOrFactory = true) when (container) { is ObjCClass -> { annotations.add(0, deprecatedInit( container.kotlinClassName(method.isClass), kotlinMethodParameters.map { it.name }, factory = false )) val designated = isDesignatedInitializer || context.configuration.disableDesignatedInitializerChecks val annotations = listOf(AnnotationStub.ObjC.Constructor(method.selector, designated)) val constructor = ConstructorStub(parameters, annotations, isPrimary = false, origin = origin) constructor } is ObjCCategory -> { assert(!method.isClass) val clazz = context.getKotlinClassFor(container.clazz, isMeta = false).type annotations.add(0, deprecatedInit( clazz.classifier.getRelativeFqName(), kotlinMethodParameters.map { it.name }, factory = true )) val factoryAnnotation = AnnotationStub.ObjC.Factory( method.selector, method.encoding, isStret ) val annotations = buildObjCMethodAnnotations(factoryAnnotation) val originalReturnType = method.getReturnType(container.clazz) val typeParameter = TypeParameterStub("T", clazz.toStubIrType()) val returnType = if (originalReturnType is ObjCPointer) { typeParameter.getStubType(originalReturnType.isNullable) } else { // This shouldn't happen actually. this.stubReturnType } val typeArgument = TypeArgumentStub(typeParameter.getStubType(false)) val receiverType = ClassifierStubType(KotlinTypes.objCClassOf, listOf(typeArgument)) val receiver = ReceiverParameterStub(receiverType) val createMethod = FunctionStub( "create", returnType, parameters, receiver = receiver, typeParameters = listOf(typeParameter), external = true, origin = StubOrigin.ObjCCategoryInitMethod(method), annotations = annotations, modality = MemberStubModality.FINAL ) createMethod } is ObjCProtocol -> null } } else { null } return listOfNotNull( FunctionStub( name, stubReturnType, kotlinMethodParameters.toList(), origin, annotations.toList(), external, receiver, modality, emptyList(), isOverride), replacement ) } } internal val ObjCContainer.classOrProtocol: ObjCClassOrProtocol get() = when (this) { is ObjCClassOrProtocol -> this is ObjCCategory -> this.clazz } private fun deprecatedInit(className: String, initParameterNames: List<String>, factory: Boolean): AnnotationStub { val replacement = if (factory) "$className.create" else className val replacementKind = if (factory) "factory method" else "constructor" val replaceWith = "$replacement(${initParameterNames.joinToString { it.asSimpleName() }})" return AnnotationStub.Deprecated("Use $replacementKind instead", replaceWith, DeprecationLevel.ERROR) } internal val ObjCMethod.kotlinName: String get() { val candidate = selector.split(":").first() val trimmed = candidate.trimEnd('_') return if (trimmed == "equals" && parameters.size == 1 || (trimmed == "hashCode" || trimmed == "toString") && parameters.size == 0) { candidate + "_" } else { candidate } } internal val ObjCClassOrProtocol.protocolsWithSupers: Sequence<ObjCProtocol> get() = this.protocols.asSequence().flatMap { sequenceOf(it) + it.protocolsWithSupers } internal val ObjCClassOrProtocol.immediateSuperTypes: Sequence<ObjCClassOrProtocol> get() { val baseClass = (this as? ObjCClass)?.baseClass if (baseClass != null) { return sequenceOf(baseClass) + this.protocols.asSequence() } return this.protocols.asSequence() } internal val ObjCClassOrProtocol.selfAndSuperTypes: Sequence<ObjCClassOrProtocol> get() = sequenceOf(this) + this.superTypes internal val ObjCClassOrProtocol.superTypes: Sequence<ObjCClassOrProtocol> get() = this.immediateSuperTypes.flatMap { it.selfAndSuperTypes }.distinct() internal fun ObjCClassOrProtocol.declaredMethods(isClass: Boolean): Sequence<ObjCMethod> = this.methods.asSequence().filter { it.isClass == isClass } @Suppress("UNUSED_PARAMETER") internal fun Sequence<ObjCMethod>.inheritedTo(container: ObjCClassOrProtocol, isMeta: Boolean): Sequence<ObjCMethod> = this // TODO: exclude methods that are marked as unavailable in [container]. internal fun ObjCClassOrProtocol.inheritedMethods(isClass: Boolean): Sequence<ObjCMethod> = this.immediateSuperTypes.flatMap { it.methodsWithInherited(isClass) } .distinctBy { it.selector } .inheritedTo(this, isClass) internal fun ObjCClassOrProtocol.methodsWithInherited(isClass: Boolean): Sequence<ObjCMethod> = (this.declaredMethods(isClass) + this.inheritedMethods(isClass)).distinctBy { it.selector } internal fun ObjCClass.getDesignatedInitializerSelectors(result: MutableSet<String>): Set<String> { // Note: Objective-C initializers act as usual methods and thus are inherited by subclasses. // Swift considers all super initializers to be available (unless otherwise specified explicitly), // but seems to consider them as non-designated if class declares its own ones explicitly. // Simulate the similar behaviour: val explicitlyDesignatedInitializers = this.methods.filter { it.isExplicitlyDesignatedInitializer && !it.isClass } if (explicitlyDesignatedInitializers.isNotEmpty()) { explicitlyDesignatedInitializers.mapTo(result) { it.selector } } else { this.declaredMethods(isClass = false).filter { it.isInit }.mapTo(result) { it.selector } this.baseClass?.getDesignatedInitializerSelectors(result) } this.superTypes.filterIsInstance<ObjCProtocol>() .flatMap { it.declaredMethods(isClass = false) }.filter { it.isInit } .mapTo(result) { it.selector } return result } internal fun ObjCMethod.isOverride(container: ObjCClassOrProtocol): Boolean = container.superTypes.any { superType -> superType.methods.any(this::replaces) } internal abstract class ObjCContainerStubBuilder( final override val context: StubsBuildingContext, private val container: ObjCClassOrProtocol, protected val metaContainerStub: ObjCContainerStubBuilder? ) : StubElementBuilder { private val isMeta: Boolean get() = metaContainerStub == null private val designatedInitializerSelectors = if (container is ObjCClass && !isMeta) { container.getDesignatedInitializerSelectors(mutableSetOf()) } else { emptySet() } private val methods: List<ObjCMethod> private val properties: List<ObjCProperty> private val protocolGetter: String? init { val superMethods = container.inheritedMethods(isMeta) // Add all methods declared in the class or protocol: var methods = container.declaredMethods(isMeta) // Exclude those which are identically declared in super types: methods -= superMethods // Add some special methods from super types: methods += superMethods.filter { it.returnsInstancetype() || it.isInit } // Add methods from adopted protocols that must be implemented according to Kotlin rules: if (container is ObjCClass) { methods += container.protocolsWithSupers.flatMap { it.declaredMethods(isMeta) }.filter { !it.isOptional } } // Add methods inherited from multiple supertypes that must be defined according to Kotlin rules: methods += container.immediateSuperTypes .flatMap { superType -> val methodsWithInherited = superType.methodsWithInherited(isMeta).inheritedTo(container, isMeta) // Select only those which are represented as non-abstract in Kotlin: when (superType) { is ObjCClass -> methodsWithInherited is ObjCProtocol -> methodsWithInherited.filter { it.isOptional } } } .groupBy { it.selector } .mapNotNull { (_, inheritedMethods) -> if (inheritedMethods.size > 1) inheritedMethods.first() else null } this.methods = methods.distinctBy { it.selector }.toList() this.properties = container.properties.filter { property -> property.getter.isClass == isMeta && // Select only properties that don't override anything: superMethods.none { property.getter.replaces(it) || property.setter?.replaces(it) ?: false } } } private val methodToStub = methods.map { it to ObjCMethodStubBuilder(it, container, it.selector in designatedInitializerSelectors, context) }.toMap() private val propertyBuilders = properties.mapNotNull { createObjCPropertyBuilder(context, it, container, this.methodToStub) } private val modality = when (container) { is ObjCClass -> ClassStubModality.OPEN is ObjCProtocol -> ClassStubModality.INTERFACE } private val classifier = context.getKotlinClassFor(container, isMeta) private val externalObjCAnnotation = when (container) { is ObjCProtocol -> { protocolGetter = if (metaContainerStub != null) { metaContainerStub.protocolGetter!! } else { // TODO: handle the case when protocol getter stub can't be compiled. context.generateNextUniqueId("kniprot_") } AnnotationStub.ObjC.ExternalClass(protocolGetter) } is ObjCClass -> { protocolGetter = null val binaryName = container.binaryName AnnotationStub.ObjC.ExternalClass("", binaryName ?: "") } } private val interfaces: List<StubType> by lazy { val interfaces = mutableListOf<StubType>() if (container is ObjCClass) { val baseClass = container.baseClass val baseClassifier = if (baseClass != null) { context.getKotlinClassFor(baseClass, isMeta) } else { if (isMeta) KotlinTypes.objCObjectBaseMeta else KotlinTypes.objCObjectBase } interfaces += baseClassifier.type.toStubIrType() } container.protocols.forEach { interfaces += context.getKotlinClassFor(it, isMeta).type.toStubIrType() } if (interfaces.isEmpty()) { assert(container is ObjCProtocol) val classifier = if (isMeta) KotlinTypes.objCObjectMeta else KotlinTypes.objCObject interfaces += classifier.type.toStubIrType() } if (!isMeta && container.isProtocolClass()) { // TODO: map Protocol type to ObjCProtocol instead. interfaces += KotlinTypes.objCProtocol.type.toStubIrType() } interfaces } private fun buildBody(): Pair<List<PropertyStub>, List<FunctionalStub>> { val defaultConstructor = if (container is ObjCClass && methodToStub.values.none { it.isDefaultConstructor() }) { // Always generate default constructor. // If it is not produced for an init method, then include it manually: ConstructorStub( isPrimary = false, visibility = VisibilityModifier.PROTECTED, origin = StubOrigin.Synthetic.DefaultConstructor) } else null return Pair( propertyBuilders.flatMap { it.build() }, methodToStub.values.flatMap { it.build() } + listOfNotNull(defaultConstructor) ) } protected fun buildClassStub(origin: StubOrigin, companion: ClassStub.Companion? = null): ClassStub { val (properties, methods) = buildBody() return ClassStub.Simple( classifier, properties = properties, methods = methods.filterIsInstance<FunctionStub>(), constructors = methods.filterIsInstance<ConstructorStub>(), origin = origin, modality = modality, annotations = listOf(externalObjCAnnotation), interfaces = interfaces, companion = companion ) } } internal sealed class ObjCClassOrProtocolStubBuilder( context: StubsBuildingContext, private val container: ObjCClassOrProtocol ) : ObjCContainerStubBuilder( context, container, metaContainerStub = object : ObjCContainerStubBuilder(context, container, metaContainerStub = null) { override fun build(): List<StubIrElement> { val origin = when (container) { is ObjCProtocol -> StubOrigin.ObjCProtocol(container, isMeta = true) is ObjCClass -> StubOrigin.ObjCClass(container, isMeta = true) } return listOf(buildClassStub(origin)) } } ) internal class ObjCProtocolStubBuilder( context: StubsBuildingContext, private val protocol: ObjCProtocol ) : ObjCClassOrProtocolStubBuilder(context, protocol), StubElementBuilder { override fun build(): List<StubIrElement> { val classStub = buildClassStub(StubOrigin.ObjCProtocol(protocol, isMeta = false)) return listOf(*metaContainerStub!!.build().toTypedArray(), classStub) } } internal class ObjCClassStubBuilder( context: StubsBuildingContext, private val clazz: ObjCClass ) : ObjCClassOrProtocolStubBuilder(context, clazz), StubElementBuilder { override fun build(): List<StubIrElement> { val companionSuper = ClassifierStubType(context.getKotlinClassFor(clazz, isMeta = true)) val objCClassType = KotlinTypes.objCClassOf.typeWith( context.getKotlinClassFor(clazz, isMeta = false).type ).toStubIrType() val superClassInit = SuperClassInit(companionSuper) val companionClassifier = context.getKotlinClassFor(clazz, isMeta = false).nested("Companion") val companion = ClassStub.Companion(companionClassifier, emptyList(), superClassInit, listOf(objCClassType)) val classStub = buildClassStub(StubOrigin.ObjCClass(clazz, isMeta = false), companion) return listOf(*metaContainerStub!!.build().toTypedArray(), classStub) } } class GeneratedObjCCategoriesMembers { private val propertyNames = mutableSetOf<String>() private val instanceMethodSelectors = mutableSetOf<String>() private val classMethodSelectors = mutableSetOf<String>() fun register(method: ObjCMethod): Boolean = (if (method.isClass) classMethodSelectors else instanceMethodSelectors).add(method.selector) fun register(property: ObjCProperty): Boolean = propertyNames.add(property.name) } internal class ObjCCategoryStubBuilder( override val context: StubsBuildingContext, private val category: ObjCCategory ) : StubElementBuilder { private val generatedMembers = context.generatedObjCCategoriesMembers .getOrPut(category.clazz, { GeneratedObjCCategoriesMembers() }) private val methodToBuilder = category.methods.filter { generatedMembers.register(it) }.map { it to ObjCMethodStubBuilder(it, category, isDesignatedInitializer = false, context = context) }.toMap() private val methodBuilders get() = methodToBuilder.values private val propertyBuilders = category.properties.filter { generatedMembers.register(it) }.mapNotNull { createObjCPropertyBuilder(context, it, category, methodToBuilder) } override fun build(): List<StubIrElement> { val description = "${category.clazz.name} (${category.name})" val meta = StubContainerMeta( "// @interface $description", "// @end; // $description" ) val container = SimpleStubContainer( meta = meta, functions = methodBuilders.flatMap { it.build() }, properties = propertyBuilders.flatMap { it.build() } ) return listOf(container) } } private fun createObjCPropertyBuilder( context: StubsBuildingContext, property: ObjCProperty, container: ObjCContainer, methodToStub: Map<ObjCMethod, ObjCMethodStubBuilder> ): ObjCPropertyStubBuilder? { // Note: the code below assumes that if the property is generated, // then its accessors are also generated as explicit methods. val getterStub = methodToStub[property.getter] ?: return null val setterStub = property.setter?.let { methodToStub[it] ?: return null } return ObjCPropertyStubBuilder(context, property, container, getterStub, setterStub) } private class ObjCPropertyStubBuilder( override val context: StubsBuildingContext, private val property: ObjCProperty, private val container: ObjCContainer, private val getterBuilder: ObjCMethodStubBuilder, private val setterMethod: ObjCMethodStubBuilder? ) : StubElementBuilder { override fun build(): List<PropertyStub> { val type = property.getType(container.classOrProtocol) val kotlinType = context.mirror(type).argType val getter = PropertyAccessor.Getter.ExternalGetter(annotations = getterBuilder.annotations) val setter = property.setter?.let { PropertyAccessor.Setter.ExternalSetter(annotations = setterMethod!!.annotations) } val kind = setter?.let { PropertyStub.Kind.Var(getter, it) } ?: PropertyStub.Kind.Val(getter) val modality = MemberStubModality.FINAL val receiver = when (container) { is ObjCClassOrProtocol -> null is ObjCCategory -> ClassifierStubType(context.getKotlinClassFor(container.clazz, isMeta = property.getter.isClass)) } val origin = StubOrigin.ObjCProperty(property, container) return listOf(PropertyStub(mangleSimple(property.name), kotlinType.toStubIrType(), kind, modality, receiver, origin = origin)) } } fun ObjCClassOrProtocol.kotlinClassName(isMeta: Boolean): String { val baseClassName = when (this) { is ObjCClass -> this.name is ObjCProtocol -> "${this.name}Protocol" } return if (isMeta) "${baseClassName}Meta" else baseClassName } internal fun ObjCClassOrProtocol.isProtocolClass(): Boolean = when (this) { is ObjCClass -> (name == "Protocol" || binaryName == "Protocol") is ObjCProtocol -> false }
apache-2.0
f43ab0721d6ad2995c69c1d34c27f14e
41.938538
134
0.646176
5.562513
false
false
false
false
jwren/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/util/SafeAnalysisUtils.kt
3
2535
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("SafeAnalysisUtils") package org.jetbrains.kotlin.idea.util import com.intellij.injected.editor.VirtualFileWindow import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.NonPhysicalFileSystem import com.intellij.psi.PsiElement import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes import org.jetbrains.jps.model.java.JavaSourceRootProperties import org.jetbrains.jps.model.module.JpsModuleSourceRootType import org.jetbrains.kotlin.config.ALL_KOTLIN_SOURCE_ROOT_TYPES import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.lazy.NoDescriptorForDeclarationException import org.jetbrains.kotlin.utils.addToStdlib.safeAs /** * Best effort to analyze element: * - Best effort for file that is out of source root scope: NoDescriptorForDeclarationException could be swallowed * - Do not swallow NoDescriptorForDeclarationException during analysis for in source scope files */ inline fun <T> PsiElement.actionUnderSafeAnalyzeBlock( crossinline action: () -> T, crossinline fallback: () -> T ): T = try { action() } catch (e: Exception) { e.returnIfNoDescriptorForDeclarationException(condition = { val file = containingFile it && (!file.isPhysical || !file.isUnderKotlinSourceRootTypes()) }) { fallback() } } val Exception.isItNoDescriptorForDeclarationException: Boolean get() = this is NoDescriptorForDeclarationException || cause?.safeAs<Exception>()?.isItNoDescriptorForDeclarationException == true inline fun <T> Exception.returnIfNoDescriptorForDeclarationException( crossinline condition: (Boolean) -> Boolean = { v -> v }, crossinline computable: () -> T ): T = if (condition(this.isItNoDescriptorForDeclarationException)) { computable() } else { throw this } val KOTLIN_AWARE_SOURCE_ROOT_TYPES: Set<JpsModuleSourceRootType<JavaSourceRootProperties>> = JavaModuleSourceRootTypes.SOURCES + ALL_KOTLIN_SOURCE_ROOT_TYPES fun PsiElement?.isUnderKotlinSourceRootTypes(): Boolean { val ktFile = this?.containingFile.safeAs<KtFile>() ?: return false val file = ktFile.virtualFile?.takeIf { it !is VirtualFileWindow && it.fileSystem !is NonPhysicalFileSystem } ?: return false val projectFileIndex = ProjectRootManager.getInstance(ktFile.project).fileIndex return projectFileIndex.isUnderSourceRootOfType(file, KOTLIN_AWARE_SOURCE_ROOT_TYPES) }
apache-2.0
72603b01f8101381a21a4942104b2668
45.090909
134
0.778698
4.810247
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromConstructorCallActionFactory.kt
4
5761
// 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.createFromUsage.createClass import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.caches.resolve.analyzeAndGetResult import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.getTypeInfoForTypeArguments import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.resolve.calls.util.getCall import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.utils.ifEmpty import java.util.* object CreateClassFromConstructorCallActionFactory : CreateClassFromUsageFactory<KtCallExpression>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtCallExpression? { val diagElement = diagnostic.psiElement if (diagElement.getNonStrictParentOfType<KtTypeReference>() != null) return null val callExpr = diagElement.parent as? KtCallExpression ?: return null return if (callExpr.calleeExpression == diagElement) callExpr else null } override fun getPossibleClassKinds(element: KtCallExpression, diagnostic: Diagnostic): List<ClassKind> { val inAnnotationEntry = diagnostic.psiElement.getNonStrictParentOfType<KtAnnotationEntry>() != null val (context, moduleDescriptor) = element.analyzeAndGetResult() val call = element.getCall(context) ?: return emptyList() val targetParents = getTargetParentsByCall(call, context).ifEmpty { return emptyList() } val classKind = if (inAnnotationEntry) ClassKind.ANNOTATION_CLASS else ClassKind.PLAIN_CLASS val fullCallExpr = element.getQualifiedExpressionForSelectorOrThis() val expectedType = fullCallExpr.guessTypeForClass(context, moduleDescriptor) if (expectedType != null && !targetParents.any { getClassKindFilter(expectedType, it)(classKind) }) return emptyList() return listOf(classKind) } override fun extractFixData(element: KtCallExpression, diagnostic: Diagnostic): ClassInfo? { val diagElement = diagnostic.psiElement if (diagElement.getNonStrictParentOfType<KtTypeReference>() != null) return null val inAnnotationEntry = diagElement.getNonStrictParentOfType<KtAnnotationEntry>() != null val callExpr = diagElement.parent as? KtCallExpression ?: return null if (callExpr.calleeExpression != diagElement) return null val calleeExpr = callExpr.calleeExpression as? KtSimpleNameExpression ?: return null val name = calleeExpr.getReferencedName() if (!inAnnotationEntry && !name.checkClassName()) return null val callParent = callExpr.parent val fullCallExpr = if (callParent is KtQualifiedExpression && callParent.selectorExpression == callExpr) callParent else callExpr val (context, moduleDescriptor) = callExpr.analyzeAndGetResult() val call = callExpr.getCall(context) ?: return null val targetParents = getTargetParentsByCall(call, context).ifEmpty { return null } val inner = isInnerClassExpected(call) val valueArguments = callExpr.valueArguments val defaultParamName = if (inAnnotationEntry && valueArguments.size == 1) "value" else null val anyType = moduleDescriptor.builtIns.nullableAnyType val parameterInfos = valueArguments.map { ParameterInfo( it.getArgumentExpression()?.let { expression -> TypeInfo(expression, Variance.IN_VARIANCE) } ?: TypeInfo( anyType, Variance.IN_VARIANCE ), it.getArgumentName()?.referenceExpression?.getReferencedName() ?: defaultParamName ) } val classKind = if (inAnnotationEntry) ClassKind.ANNOTATION_CLASS else ClassKind.PLAIN_CLASS val expectedType = fullCallExpr.guessTypeForClass(context, moduleDescriptor) val expectedTypeInfo = expectedType?.toClassTypeInfo() ?: TypeInfo.Empty val filteredParents = if (expectedType != null) { targetParents.filter { getClassKindFilter(expectedType, it)(classKind) }.ifEmpty { return null } } else targetParents val typeArgumentInfos = if (inAnnotationEntry) Collections.emptyList() else callExpr.getTypeInfoForTypeArguments() val argumentClassVisibilities = valueArguments.mapNotNull { (it.getArgumentExpression()?.getCallableDescriptor() as? ClassConstructorDescriptor)?.containingDeclaration?.visibility } val primaryConstructorVisibility = when { DescriptorVisibilities.PRIVATE in argumentClassVisibilities -> DescriptorVisibilities.PRIVATE DescriptorVisibilities.INTERNAL in argumentClassVisibilities -> DescriptorVisibilities.INTERNAL else -> null } return ClassInfo( name = name, targetParents = filteredParents, expectedTypeInfo = expectedTypeInfo, inner = inner, typeArguments = typeArgumentInfos, parameterInfos = parameterInfos, primaryConstructorVisibility = primaryConstructorVisibility ) } }
apache-2.0
868e5c46515de2d519693f76ac4398db
51.372727
158
0.738934
5.884576
false
false
false
false
jwren/intellij-community
plugins/kotlin/uast/uast-kotlin-base/test/org/jetbrains/uast/test/common/kotlin/UastFileComparisonTestBase.kt
4
1807
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.test.common.kotlin import com.intellij.openapi.util.io.FileUtil import org.jetbrains.kotlin.test.KtAssert import org.jetbrains.kotlin.idea.test.testFramework.KtUsefulTestCase import java.io.File interface UastFileComparisonTestBase { fun getTestMetadataFileFromPath(filePath: String, ext: String): File { return File(filePath.removeSuffix(".kt") + '.' + ext) } private val isTeamCityBuild: Boolean get() = System.getenv("TEAMCITY_VERSION") != null || KtUsefulTestCase.IS_UNDER_TEAMCITY fun cleanUpIdenticalFile( currentFile: File, counterpartFile: File, identicalFile: File, kind: String ) { // Already cleaned up if (identicalFile.exists()) return // Nothing to compare if (!currentFile.exists() || !counterpartFile.exists()) return val content = currentFile.readText().trim() if (content == counterpartFile.readText().trim()) { val message = if (isTeamCityBuild) { "Please remove .$kind.fir.txt dump and .$kind.fe10.txt dump" } else { currentFile.delete() counterpartFile.delete() FileUtil.writeToFile(identicalFile, content) "Deleted .$kind.fir.txt dump and .$kind.fe10.txt dump, added .$kind.txt instead" } KtAssert.fail( """ Dump via FIR UAST & via FE10 UAST are the same. $message Please re-run the test now """.trimIndent() ) } } }
apache-2.0
f94c51a2531e90d7d4d3047b5a3db65d
35.877551
158
0.60321
4.621483
false
true
false
false
robfletcher/keiko
keiko-core/src/main/kotlin/com/netflix/spinnaker/q/QueueProcessor.kt
1
4430
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.q import com.netflix.spinnaker.KotlinOpen import com.netflix.spinnaker.q.metrics.EventPublisher import com.netflix.spinnaker.q.metrics.HandlerThrewError import com.netflix.spinnaker.q.metrics.MessageDead import com.netflix.spinnaker.q.metrics.NoHandlerCapacity import org.slf4j.Logger import org.slf4j.LoggerFactory.getLogger import org.springframework.scheduling.annotation.Scheduled import java.time.Duration import java.util.Random import java.util.concurrent.RejectedExecutionException import javax.annotation.PostConstruct /** * The processor that fetches messages from the [Queue] and hands them off to * the appropriate [MessageHandler]. */ @KotlinOpen class QueueProcessor( private val queue: Queue, private val executor: QueueExecutor<*>, private val handlers: Collection<MessageHandler<*>>, private val activators: List<Activator>, private val publisher: EventPublisher, private val deadMessageHandler: DeadMessageCallback, private val fillExecutorEachCycle: Boolean = false, private val requeueDelay: Duration = Duration.ofSeconds(0), private val requeueMaxJitter: Duration = Duration.ofSeconds(0) ) { private val log: Logger = getLogger(javaClass) private val random: Random = Random() /** * Polls the [Queue] once (or more if [fillExecutorEachCycle] is true) so * long as [executor] has capacity. */ @Scheduled(fixedDelayString = "\${queue.poll.frequency.ms:10}") fun poll() = ifEnabled { if (executor.hasCapacity()) { if (fillExecutorEachCycle) { executor.availableCapacity().downTo(1).forEach { pollOnce() } } else { pollOnce() } } else { publisher.publishEvent(NoHandlerCapacity) } } /** * Polls the [Queue] once to attempt to read a single message. */ private fun pollOnce() { queue.poll { message, ack -> log.info("Received message $message") val handler = handlerFor(message) if (handler != null) { try { executor.execute { try { handler.invoke(message) ack.invoke() } catch (e: Throwable) { // Something very bad is happening log.error("Unhandled throwable from $message", e) publisher.publishEvent(HandlerThrewError(message)) } } } catch (e: RejectedExecutionException) { var requeueDelaySeconds = requeueDelay.seconds if (requeueMaxJitter.seconds > 0) { requeueDelaySeconds += random.nextInt(requeueMaxJitter.seconds.toInt()) } val requeueDelay = Duration.ofSeconds(requeueDelaySeconds) val numberOfAttempts = message.getAttribute<AttemptsAttribute>() log.warn( "Executor at capacity, re-queuing message {} (delay: {}, attempts: {})", message, requeueDelay, numberOfAttempts, e ) queue.push(message, requeueDelay) } } else { log.error("Unsupported message type ${message.javaClass.simpleName}: $message") deadMessageHandler.invoke(queue, message) publisher.publishEvent(MessageDead) } } } private fun ifEnabled(fn: () -> Unit) { if (activators.all { it.enabled }) { fn.invoke() } } private val handlerCache = mutableMapOf<Class<out Message>, MessageHandler<*>>() private fun handlerFor(message: Message) = handlerCache[message.javaClass] .let { handler -> handler ?: handlers .find { it.messageType.isAssignableFrom(message.javaClass) } ?.also { handlerCache[message.javaClass] = it } } @PostConstruct fun confirmQueueType() = log.info("Using ${queue.javaClass.simpleName} queue") }
apache-2.0
34761e7de2f30142c07e348ef58fe23c
31.814815
87
0.666591
4.465726
false
false
false
false
SimpleMobileTools/Simple-Notes
app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/MyWidgetProvider.kt
1
3748
package com.simplemobiletools.notes.pro.helpers import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Intent import android.net.Uri import android.widget.RemoteViews import com.simplemobiletools.commons.extensions.applyColorFilter import com.simplemobiletools.commons.extensions.getLaunchIntent import com.simplemobiletools.commons.extensions.setText import com.simplemobiletools.commons.extensions.setVisibleIf import com.simplemobiletools.commons.helpers.WIDGET_TEXT_COLOR import com.simplemobiletools.commons.helpers.ensureBackgroundThread import com.simplemobiletools.notes.pro.R import com.simplemobiletools.notes.pro.activities.SplashActivity import com.simplemobiletools.notes.pro.extensions.notesDB import com.simplemobiletools.notes.pro.extensions.widgetsDB import com.simplemobiletools.notes.pro.models.Widget import com.simplemobiletools.notes.pro.services.WidgetService class MyWidgetProvider : AppWidgetProvider() { private fun setupAppOpenIntent(context: Context, views: RemoteViews, id: Int, widget: Widget) { val intent = context.getLaunchIntent() ?: Intent(context, SplashActivity::class.java) intent.putExtra(OPEN_NOTE_ID, widget.noteId) val pendingIntent = PendingIntent.getActivity(context, widget.widgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) views.setOnClickPendingIntent(id, pendingIntent) } override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { super.onUpdate(context, appWidgetManager, appWidgetIds) ensureBackgroundThread { for (widgetId in appWidgetIds) { val widget = context.widgetsDB.getWidgetWithWidgetId(widgetId) ?: continue val views = RemoteViews(context.packageName, R.layout.widget) val note = context.notesDB.getNoteWithId(widget.noteId) views.applyColorFilter(R.id.notes_widget_background, widget.widgetBgColor) views.setTextColor(R.id.widget_note_title, widget.widgetTextColor) views.setText(R.id.widget_note_title, note?.title ?: "") views.setVisibleIf(R.id.widget_note_title, widget.widgetShowTitle) setupAppOpenIntent(context, views, R.id.notes_widget_holder, widget) Intent(context, WidgetService::class.java).apply { putExtra(NOTE_ID, widget.noteId) putExtra(WIDGET_TEXT_COLOR, widget.widgetTextColor) data = Uri.parse(this.toUri(Intent.URI_INTENT_SCHEME)) views.setRemoteAdapter(R.id.notes_widget_listview, this) } val startActivityIntent = context.getLaunchIntent() ?: Intent(context, SplashActivity::class.java) startActivityIntent.putExtra(OPEN_NOTE_ID, widget.noteId) val startActivityPendingIntent = PendingIntent.getActivity(context, widgetId, startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) views.setPendingIntentTemplate(R.id.notes_widget_listview, startActivityPendingIntent) appWidgetManager.updateAppWidget(widgetId, views) appWidgetManager.notifyAppWidgetViewDataChanged(widgetId, R.id.notes_widget_listview) } } } override fun onDeleted(context: Context, appWidgetIds: IntArray) { super.onDeleted(context, appWidgetIds) ensureBackgroundThread { appWidgetIds.forEach { context.widgetsDB.deleteWidgetId(it) } } } }
gpl-3.0
33ce0b0748e0c50d6d94164ad9c6ea0e
51.788732
154
0.723052
4.938076
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/checker/BreakContinue.fir.kt
10
1151
class C { fun f (a : Boolean, b : Boolean) { b@ (while (true) a@ { <error descr="[NOT_A_LOOP_LABEL] The label does not denote a loop">break@f</error> break break@b <error descr="[NOT_A_LOOP_LABEL] The label does not denote a loop">break@a</error> }) <error descr="[BREAK_OR_CONTINUE_OUTSIDE_A_LOOP] 'break' and 'continue' are only allowed inside a loop">continue</error> b@ (while (true) a@ { <error descr="[NOT_A_LOOP_LABEL] The label does not denote a loop">continue@f</error> continue continue@b <error descr="[NOT_A_LOOP_LABEL] The label does not denote a loop">continue@a</error> }) <error descr="[BREAK_OR_CONTINUE_OUTSIDE_A_LOOP] 'break' and 'continue' are only allowed inside a loop">break</error> <error descr="[BREAK_OR_CONTINUE_OUTSIDE_A_LOOP] 'break' and 'continue' are only allowed inside a loop">continue@f</error> <error descr="[BREAK_OR_CONTINUE_OUTSIDE_A_LOOP] 'break' and 'continue' are only allowed inside a loop">break@f</error> } }
apache-2.0
c2e254d0ee9be02525115b76f950e658
40.107143
130
0.592528
3.665605
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/plugin/src/org/jetbrains/kotlin/idea/compiler/configuration/LazyKotlinMavenArtifactDownloader.kt
7
1854
// 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.compiler.configuration import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import org.jetbrains.kotlin.idea.base.plugin.artifacts.AbstractLazyFileOutputProducer import org.jetbrains.kotlin.idea.compiler.configuration.LazyKotlinMavenArtifactDownloader.DownloadContext import java.io.File import java.security.MessageDigest internal class LazyKotlinMavenArtifactDownloader( private val artifactId: String, private val version: String, private val artifactIsPom: Boolean = false, ) : AbstractLazyFileOutputProducer<Unit, DownloadContext>("${this::class.java.name}-$artifactId-$version") { override fun produceOutput(input: Unit, computationContext: DownloadContext): List<File> { computationContext.indicator.text = computationContext.indicatorDownloadText return KotlinArtifactsDownloader.downloadMavenArtifacts( artifactId, version, computationContext.project, computationContext.indicator, artifactIsPom ) } override fun updateMessageDigestWithInput(messageDigest: MessageDigest, input: Unit, buffer: ByteArray) { // The input is the Internet, we don't track it in this implementation } fun getDownloadedIfUpToDateOrEmpty() = getOutputIfUpToDateOrEmpty(Unit) fun lazyDownload(downloadContext: DownloadContext) = lazyProduceOutput(Unit, downloadContext) fun isUpToDate() = isUpToDate(Unit) data class DownloadContext( val project: Project, val indicator: ProgressIndicator, @NlsContexts.ProgressText val indicatorDownloadText: String, ) }
apache-2.0
7df5653a637a469e5da6e6a37a987be7
44.219512
120
0.765372
4.917772
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/view/SimpleColoredTextIcon.kt
4
7248
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.coroutine.view import com.intellij.debugger.impl.DebuggerUtilsEx import com.intellij.debugger.settings.ThreadsViewSettings import com.intellij.icons.AllIcons import com.intellij.openapi.editor.HighlighterColors import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.ui.ColoredTextContainer import com.intellij.ui.SimpleColoredComponent import com.intellij.ui.SimpleTextAttributes import com.intellij.xdebugger.frame.presentation.XValuePresentation import com.intellij.xdebugger.impl.ui.DebuggerUIUtil import com.intellij.xdebugger.impl.ui.XDebuggerUIConstants import com.sun.jdi.Location import com.sun.jdi.ReferenceType import org.jetbrains.kotlin.idea.debugger.coroutine.KotlinDebuggerCoroutinesBundle import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutineInfoData import org.jetbrains.kotlin.idea.debugger.coroutine.data.State import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger import javax.swing.Icon class SimpleColoredTextIcon(val icon: Icon?, val hasChildren: Boolean) { private val texts = mutableListOf<String>() private val textKeyAttributes = mutableListOf<TextAttributesKey>() constructor(icon: Icon?, hasChildren: Boolean, text: String) : this(icon, hasChildren) { append(text) } internal fun append(value: String) { texts.add(value) textKeyAttributes.add(CoroutineDebuggerColors.REGULAR_ATTRIBUTES) } internal fun appendValue(value: String) { texts.add(value) textKeyAttributes.add(CoroutineDebuggerColors.VALUE_ATTRIBUTES) } private fun appendToComponent(component: ColoredTextContainer) { val size: Int = texts.size for (i in 0 until size) { val text: String = texts[i] val attribute: TextAttributesKey = textKeyAttributes[i] val simpleTextAttribute = toSimpleTextAttribute(attribute) component.append(text, simpleTextAttribute) } } private fun toSimpleTextAttribute(attribute: TextAttributesKey) = when (attribute) { CoroutineDebuggerColors.REGULAR_ATTRIBUTES -> SimpleTextAttributes.REGULAR_ATTRIBUTES CoroutineDebuggerColors.VALUE_ATTRIBUTES -> XDebuggerUIConstants.VALUE_NAME_ATTRIBUTES else -> SimpleTextAttributes.REGULAR_ATTRIBUTES } fun forEachTextBlock(f: (Pair<String, TextAttributesKey>) -> Unit) { for (pair in texts zip textKeyAttributes) f(pair) } fun simpleString(): String { val component = SimpleColoredComponent() appendToComponent(component) return component.getCharSequence(false).toString() } fun valuePresentation(): XValuePresentation { return object : XValuePresentation() { override fun isShowName() = false override fun getSeparator() = "" override fun renderValue(renderer: XValueTextRenderer) { forEachTextBlock { renderer.renderValue(it.first, it.second) } } } } } interface CoroutineDebuggerColors { companion object { val REGULAR_ATTRIBUTES: TextAttributesKey = HighlighterColors.TEXT val VALUE_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("KOTLIN_COROUTINE_DEBUGGER_VALUE", HighlighterColors.TEXT) } } fun fromState(state: State): Icon = when (state) { State.SUSPENDED -> AllIcons.Debugger.ThreadFrozen State.RUNNING -> AllIcons.Debugger.ThreadRunning State.CREATED -> AllIcons.Debugger.ThreadStates.Idle else -> AllIcons.Debugger.ThreadStates.Daemon_sign } class SimpleColoredTextIconPresentationRenderer { companion object { val log by logger } private val settings: ThreadsViewSettings = ThreadsViewSettings.getInstance() fun render(infoData: CoroutineInfoData): SimpleColoredTextIcon { val thread = infoData.activeThread val name = thread?.name()?.substringBefore(" @${infoData.descriptor.name}") ?: "" val threadState = if (thread != null) DebuggerUtilsEx.getThreadStatusText(thread.status()) else "" val icon = fromState(infoData.descriptor.state) val label = SimpleColoredTextIcon(icon, !infoData.isCreated()) label.append("\"") label.appendValue(infoData.descriptor.formatName()) label.append("\": ${infoData.descriptor.state}") if (name.isNotEmpty()) { label.append(" on thread \"") label.appendValue(name) label.append("\": $threadState") } return label } /** * Taken from #StackFrameDescriptorImpl.calcRepresentation */ fun render(location: Location): SimpleColoredTextIcon { val label = SimpleColoredTextIcon(null, false) DebuggerUIUtil.getColorScheme(null) if (location.method() != null) { val myName = location.method().name() val methodDisplay = if (settings.SHOW_ARGUMENTS_TYPES) DebuggerUtilsEx.methodNameWithArguments(location.method()) else myName label.appendValue(methodDisplay) } if (settings.SHOW_LINE_NUMBER) { label.append(":") label.append("" + DebuggerUtilsEx.getLineNumber(location, false)) } if (settings.SHOW_CLASS_NAME) { val name = try { val refType: ReferenceType = location.declaringType() refType.name() } catch (e: InternalError) { e.toString() } if (name != null) { label.append(", ") val dotIndex = name.lastIndexOf('.') if (dotIndex < 0) { label.append(name) } else { label.append(name.substring(dotIndex + 1)) if (settings.SHOW_PACKAGE_NAME) { label.append(" (${name.substring(0, dotIndex)})") } } } } if (settings.SHOW_SOURCE_NAME) { label.append(", ") val sourceName = DebuggerUtilsEx.getSourceName(location) { e: Throwable? -> log.error("Error while trying to resolve sourceName for location", e, location.toString()) "Unknown Source" } label.append(sourceName) } return label } fun renderCreationNode() = SimpleColoredTextIcon( null, true, KotlinDebuggerCoroutinesBundle.message("coroutine.dump.creation.trace") ) fun renderErrorNode(error: String) = SimpleColoredTextIcon(AllIcons.Actions.Lightning, false, KotlinDebuggerCoroutinesBundle.message(error)) fun renderInfoNode(text: String) = SimpleColoredTextIcon(AllIcons.General.Information, false, KotlinDebuggerCoroutinesBundle.message(text)) fun renderGroup(groupName: String) = SimpleColoredTextIcon(AllIcons.Debugger.ThreadGroup, true, groupName) }
apache-2.0
798918602a142fa4b6736d21f937c261
36.947644
158
0.65963
5.089888
false
false
false
false
sandipv22/pointer_replacer
allusive/src/main/java/com/afterroot/allusive2/adapter/PointersAdapter.kt
1
5734
/* * Copyright (C) 2016-2021 Sandip Vaghela * 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.afterroot.allusive2.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.appcompat.widget.AppCompatImageView import androidx.appcompat.widget.AppCompatTextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.view.updateLayoutParams import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.afterroot.allusive2.GlideApp import com.afterroot.allusive2.R import com.afterroot.allusive2.Reason import com.afterroot.allusive2.adapter.callback.ItemSelectedCallback import com.afterroot.allusive2.databinding.ItemPointerRepoBinding import com.afterroot.allusive2.getMinPointerSize import com.afterroot.allusive2.model.Pointer import com.afterroot.core.extensions.getDrawableExt import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.bumptech.glide.request.transition.DrawableCrossFadeFactory import com.google.firebase.storage.FirebaseStorage import org.koin.core.component.KoinComponent import org.koin.core.component.get /** * New list adapter for Repository screen. * */ class PointersAdapter(private val callbacks: ItemSelectedCallback<Pointer>) : ListAdapter<Pointer, RecyclerView.ViewHolder>(object : DiffUtil.ItemCallback<Pointer?>() { override fun areItemsTheSame(oldItem: Pointer, newItem: Pointer): Boolean = oldItem == newItem override fun areContentsTheSame(oldItem: Pointer, newItem: Pointer): Boolean = oldItem.hashCode() == newItem.hashCode() }) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val binding = ItemPointerRepoBinding.inflate(LayoutInflater.from(parent.context), parent, false) return PointerVH(binding, callbacks) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { holder as PointerVH holder.bind(getItem(position)) } inner class PointerVH(binding: ItemPointerRepoBinding, private val callbacks: ItemSelectedCallback<Pointer>) : RecyclerView.ViewHolder(binding.root), KoinComponent { val context: Context = binding.root.context private val itemName: AppCompatTextView = binding.infoPointerPackName private val itemThumb: AppCompatImageView = binding.infoPointerImage private val itemUploader: AppCompatTextView = binding.infoUsername private val infoMeta: AppCompatTextView = binding.infoMeta fun bind(pointer: Pointer) { when (pointer.reasonCode) { Reason.OK -> { val storageReference = get<FirebaseStorage>().reference.child("pointers/${pointer.filename}") itemName.text = pointer.name pointer.uploadedBy?.forEach { itemUploader.text = String.format(context.getString(R.string.str_format_uploaded_by), it.value) } itemThumb.apply { updateLayoutParams<ConstraintLayout.LayoutParams> { height = context.getMinPointerSize() width = context.getMinPointerSize() } val factory = DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build() GlideApp.with(context) .load(storageReference) .override(context.getMinPointerSize(), context.getMinPointerSize()) .transition(DrawableTransitionOptions.withCrossFade(factory)) .into(this) background = context.getDrawableExt(R.drawable.transparent_grid) } infoMeta.text = context.resources.getQuantityString( R.plurals.str_format_download_count, pointer.downloads, pointer.downloads ) } else -> { itemThumb.apply { updateLayoutParams<ConstraintLayout.LayoutParams> { height = context.getMinPointerSize() width = context.getMinPointerSize() } background = null setImageDrawable(context.getDrawableExt(R.drawable.ic_removed, R.color.color_error)) } itemName.text = pointer.name infoMeta.text = null itemUploader.text = null } } with(super.itemView) { tag = pointer setOnClickListener { callbacks.onClick(adapterPosition, itemView, pointer) } setOnLongClickListener { return@setOnLongClickListener callbacks.onLongClick(adapterPosition, pointer) } } } } }
apache-2.0
2f20c941f41a98278a9943f5ece6dab1
45.617886
119
0.648064
5.455756
false
false
false
false
K0zka/kerub
src/test/kotlin/com/github/kerubistan/kerub/utils/junix/sysfs/NetTest.kt
2
1255
package com.github.kerubistan.kerub.utils.junix.sysfs import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.whenever import org.apache.sshd.client.session.ClientSession import org.apache.sshd.client.subsystem.sftp.SftpClient import org.junit.Test import java.io.ByteArrayInputStream import kotlin.test.assertEquals class NetTest { private val clientSession: ClientSession = mock() private val sftpClient: SftpClient = mock() @Test fun listDevices() { val deviceDir = mock<SftpClient.DirEntry>() whenever(deviceDir.filename).thenReturn("eth0") whenever(clientSession.createSftpClient()).thenReturn(sftpClient) whenever(sftpClient.readDir(any<String>())).thenReturn(listOf(deviceDir)) val device = Net.listDevices(clientSession) assertEquals(device.size, 1) assertEquals(device[0], "eth0") } @Test fun getMacAddress() { val content = ByteArrayInputStream("52:54:00:b5:75:bb".toByteArray(charset("ASCII"))) whenever(sftpClient.read(any())).thenReturn(content) whenever(clientSession.createSftpClient()).thenReturn(sftpClient) val response = Net.getMacAddress(clientSession, "eth0") assertEquals(response.size, 6) assertEquals(response[2], 0.toByte()) } }
apache-2.0
c4b478bc713c911470b72cb6d041a24d
28.904762
87
0.779283
3.691176
false
true
false
false
fvasco/pinpoi
app/src/main/java/io/github/fvasco/pinpoi/PlacemarkDetailFragment.kt
1
9971
package io.github.fvasco.pinpoi import android.app.AlertDialog import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.location.Location import android.os.Bundle import android.text.Html import android.text.method.LinkMovementMethod import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.edit import androidx.core.text.HtmlCompat import androidx.fragment.app.Fragment import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.openlocationcode.OpenLocationCode import io.github.fvasco.pinpoi.dao.PlacemarkCollectionDao import io.github.fvasco.pinpoi.dao.PlacemarkDao import io.github.fvasco.pinpoi.model.Placemark import io.github.fvasco.pinpoi.model.PlacemarkAnnotation import io.github.fvasco.pinpoi.util.* import kotlinx.android.synthetic.main.placemark_detail.* import java.util.concurrent.Future /** * A fragment representing a single Placemark detail screen. * This fragment is either contained in a [PlacemarkListActivity] * in two-pane mode (on tablets) or a [PlacemarkDetailActivity] * on handsets. */ class PlacemarkDetailFragment : Fragment() { // show coordinates // show address // show placemark collection details var placemark: Placemark? = null set(value) { saveData() field = value Log.i(PlacemarkDetailFragment::class.java.simpleName, "open placemark ${value?.id}") placemarkAnnotation = if (value == null) null else placemarkDao.loadPlacemarkAnnotation(value) val placemarkCollection = if (value == null) null else placemarkCollectionDao.findPlacemarkCollectionById(value.collectionId) if (value != null) { preferences?.edit { putLong(ARG_PLACEMARK_ID, value.id) } } placemarkNameText.text = value?.name placemarkDetailText.text = when { value == null -> null value.description.isBlank() -> value.name value.description.isHtml() -> "<p>${Html.escapeHtml(value.name)}</p>${value.description}".let { html -> Html.fromHtml(html, HtmlCompat.FROM_HTML_MODE_COMPACT) } else -> "${value.name}\n\n${value.description}" } noteText.setText(placemarkAnnotation?.note) coordinatesText.text = if (value == null) null else getString( R.string.location, Location.convert(value.coordinates.latitude.toDouble(), Location.FORMAT_DEGREES), Location.convert(value.coordinates.longitude.toDouble(), Location.FORMAT_DEGREES) ) plusCodeText.visibility = View.GONE if (value != null) { val plusCode = OpenLocationCode.encode( value.coordinates.latitude.toDouble(), value.coordinates.longitude.toDouble() ) plusCodeText.text = "Plus Code: $plusCode" plusCodeText.visibility = View.VISIBLE } searchAddressFuture?.cancel(true) addressText.text = null addressText.visibility = View.GONE if (value != null) { searchAddressFuture = LocationUtil(requireContext()).getAddressStringAsync(value.coordinates) { address -> if (!address.isNullOrEmpty()) { addressText?.visibility = View.VISIBLE addressText?.text = address } } } if (placemarkCollection == null) { collectionDescriptionTitle.visibility = View.GONE collectionDescriptionText.visibility = View.GONE } else { collectionDescriptionTitle.visibility = View.VISIBLE collectionDescriptionText.visibility = View.VISIBLE collectionDescriptionTitle.text = placemarkCollection.name collectionDescriptionText.text = placemarkCollection.description } } val longClickListener: View.OnLongClickListener = View.OnLongClickListener { LocationUtil(requireContext()).openExternalMap(placemark!!, true) true } private lateinit var placemarkDao: PlacemarkDao private lateinit var placemarkCollectionDao: PlacemarkCollectionDao var placemarkAnnotation: PlacemarkAnnotation? = null private set private var preferences: SharedPreferences? = null private var searchAddressFuture: Future<Unit>? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) preferences = activity?.getSharedPreferences(PlacemarkDetailFragment::class.java.simpleName, Context.MODE_PRIVATE) placemarkDao = PlacemarkDao(requireContext()) placemarkCollectionDao = PlacemarkCollectionDao(requireContext()) placemarkDao.open() placemarkCollectionDao.open() val id = savedInstanceState?.getLong(ARG_PLACEMARK_ID) ?: arguments?.getLong( ARG_PLACEMARK_ID, preferences?.getLong(ARG_PLACEMARK_ID, 0) ?: 0 ) ?: 0 preferences?.edit { putLong(ARG_PLACEMARK_ID, id) } } override fun onPause() { saveData() super.onPause() } override fun onDestroy() { placemarkDao.close() placemarkCollectionDao.close() super.onDestroy() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.placemark_detail, container, false) } override fun onStart() { super.onStart() // By default, these links will appear but not respond to user input. placemarkDetailText.movementMethod = LinkMovementMethod.getInstance() placemark = placemarkDao.getPlacemark(preferences?.getLong(ARG_PLACEMARK_ID, 0) ?: 0) } override fun onResume() { super.onResume() shareButton.setOnClickListener { onShare() } resetStarFabIcon(requireActivity().findViewById(R.id.fabStar) as FloatingActionButton) } override fun onSaveInstanceState(outState: Bundle) { placemark?.let { placemark -> outState.putLong(ARG_PLACEMARK_ID, placemark.id) } super.onSaveInstanceState(outState) } fun onMapClick(view: View) { placemark?.apply { LocationUtil(requireContext()).openExternalMap(this, false) } } fun onShare() { val placemark = placemark ?: return val view = view ?: return val places = mutableListOf<String?>(placemark.name) if (placemark.description.length in 1..100) places.add(placemark.description) places.add(placemarkAnnotation?.note) places.add(addressText.text?.toString()) with(placemark.coordinates) { places.add(this.toString()) places.add( Location.convert(latitude.toDouble(), Location.FORMAT_DEGREES) + ' ' + Location.convert(longitude.toDouble(), Location.FORMAT_DEGREES) ) places.add( Location.convert(latitude.toDouble(), Location.FORMAT_MINUTES) + ' ' + Location.convert(longitude.toDouble(), Location.FORMAT_MINUTES) ) places.add( Location.convert(latitude.toDouble(), Location.FORMAT_SECONDS) + ' ' + Location.convert(longitude.toDouble(), Location.FORMAT_SECONDS) ) places.add(OpenLocationCode.encode(latitude.toDouble(), longitude.toDouble())) } // remove empty lines places.removeAll { it.isNullOrBlank() } // open chooser and share AlertDialog.Builder(view.context) .setTitle(getString(R.string.share)) .setItems(places.toTypedArray()) { dialog, which -> dialog.tryDismiss() try { val text = places[which] var intent = Intent(Intent.ACTION_SEND) intent.type = "text/plain" intent.putExtra(Intent.EXTRA_TEXT, text) intent = Intent.createChooser(intent, text) requireContext().startActivity(intent) } catch (e: Exception) { Log.e(PlacemarkDetailActivity::class.java.simpleName, "Error on map click", e) context?.showToast(e) } } .show() } fun resetStarFabIcon(starFab: FloatingActionButton) { val drawable = if (placemarkAnnotation?.flagged == true) R.drawable.ic_bookmark_white else R.drawable.ic_bookmark_border_white starFab.setImageDrawable(resources.getDrawable(drawable, requireActivity().baseContext.theme)) } fun onStarClick(starFab: FloatingActionButton) { placemarkAnnotation?.flagged = !placemarkAnnotation!!.flagged resetStarFabIcon(starFab) doAsync { saveData() } } private fun saveData() { // save previous annotation placemarkAnnotation?.apply { note = noteText.text.toString() placemarkDao.update(this) } } companion object { /** * The fragment argument representing the item ID that this fragment * represents. */ const val ARG_PLACEMARK_ID = "placemarkId" } }
gpl-3.0
e4d571e14d6d5bc2f58c71fd0d0b0667
38.255906
115
0.613579
5.212232
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/highlighter/GroovyKeywordAnnotator.kt
9
3144
// 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.plugins.groovy.highlighter import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.kRECORD import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.kVAR import org.jetbrains.plugins.groovy.lang.lexer.TokenSets import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrRecordDefinition import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement /** * Groovy allows keywords to appear in various places such as FQNs, reference names, labels, etc. * Syntax highlighter highlights all of them since it's based on lexer, which has no clue which keyword is really a keyword. * This knowledge becomes available only after parsing. * * This annotator clears text attributes for elements which are not really keywords. */ class GroovyKeywordAnnotator : Annotator { override fun annotate(element: PsiElement, holder: AnnotationHolder) { if (shouldBeErased(element)) { holder.newSilentAnnotation(HighlightSeverity.INFORMATION).enforcedTextAttributes(TextAttributes.ERASE_MARKER).create() } } } fun shouldBeErased(element: PsiElement): Boolean { val tokenType = element.node.elementType if (tokenType !in TokenSets.KEYWORDS) return false // do not touch other elements val parent = element.parent if (parent is GrArgumentLabel) { // don't highlight: print (void:'foo') return true } else if (PsiTreeUtil.getParentOfType(element, GrCodeReferenceElement::class.java) != null) { if (TokenSets.CODE_REFERENCE_ELEMENT_NAME_TOKENS.contains(tokenType)) { return true // it is allowed to name packages 'as', 'in', 'def' or 'trait' } } else if (tokenType === GroovyTokenTypes.kDEF && element.parent is GrAnnotationNameValuePair) { return true } else if (parent is GrReferenceExpression && element === parent.referenceNameElement) { if (tokenType === GroovyTokenTypes.kSUPER && parent.qualifier == null) return false if (tokenType === GroovyTokenTypes.kTHIS && parent.qualifier == null) return false return true // don't highlight foo.def } else if (parent !is GrModifierList && tokenType === kVAR) { return true } else if (parent !is GrRecordDefinition && tokenType === kRECORD) { return true } return false }
apache-2.0
b438f8784660fb90f02ed3a433ad1209
45.925373
158
0.780216
4.342541
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinSuppressIntentionAction.kt
2
7751
// 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.codeInspection.SuppressIntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.idea.KotlinIdeaAnalysisBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.util.addAnnotation import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.replaceFileAnnotationList import org.jetbrains.kotlin.resolve.BindingContext class KotlinSuppressIntentionAction private constructor( suppressAt: PsiElement, private val suppressKey: String, private val kind: AnnotationHostKind ) : SuppressIntentionAction() { val pointer = suppressAt.createSmartPointer() val project = suppressAt.project constructor( suppressAt: KtExpression, suppressKey: String, kind: AnnotationHostKind ) : this(suppressAt as PsiElement, suppressKey, kind) constructor( suppressAt: KtFile, suppressKey: String, kind: AnnotationHostKind ) : this(suppressAt as PsiElement, suppressKey, kind) override fun getFamilyName() = KotlinIdeaAnalysisBundle.message("intention.suppress.family") override fun getText() = KotlinIdeaAnalysisBundle.message("intention.suppress.text", suppressKey, kind.kind, kind.name) override fun isAvailable(project: Project, editor: Editor?, element: PsiElement) = element.isValid override fun invoke(project: Project, editor: Editor?, element: PsiElement) { if (!element.isValid) return val suppressAt = pointer.element ?: return if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return val id = "\"$suppressKey\"" when (suppressAt) { is KtModifierListOwner -> suppressAt.addAnnotation( StandardNames.FqNames.suppress, id, whiteSpaceText = if (kind.newLineNeeded) "\n" else " ", addToExistingAnnotation = { entry -> addArgumentToSuppressAnnotation( entry, id ); true }) is KtAnnotatedExpression -> suppressAtAnnotatedExpression(CaretBox(suppressAt, editor), id) is KtExpression -> suppressAtExpression(CaretBox(suppressAt, editor), id) is KtFile -> suppressAtFile(suppressAt, id) } } private fun suppressAtFile(ktFile: KtFile, id: String) { val psiFactory = KtPsiFactory(project) val fileAnnotationList: KtFileAnnotationList? = ktFile.fileAnnotationList if (fileAnnotationList == null) { val newAnnotationList = psiFactory.createFileAnnotationListWithAnnotation(suppressAnnotationText(id, false)) val packageDirective = ktFile.packageDirective val createAnnotationList = if (packageDirective != null && PsiTreeUtil.skipWhitespacesForward(packageDirective) == ktFile.importList) { // packageDirective could be empty but suppression still should be added before it to generate consistent PSI ktFile.addBefore(newAnnotationList, packageDirective) as KtFileAnnotationList } else { replaceFileAnnotationList(ktFile, newAnnotationList) } ktFile.addAfter(psiFactory.createWhiteSpace(kind), createAnnotationList) return } val suppressAnnotation: KtAnnotationEntry? = findSuppressAnnotation(fileAnnotationList) if (suppressAnnotation == null) { val newSuppressAnnotation = psiFactory.createFileAnnotation(suppressAnnotationText(id, false)) fileAnnotationList.add(psiFactory.createWhiteSpace(kind)) fileAnnotationList.add(newSuppressAnnotation) as KtAnnotationEntry return } addArgumentToSuppressAnnotation(suppressAnnotation, id) } private fun suppressAtAnnotatedExpression(suppressAt: CaretBox<KtAnnotatedExpression>, id: String) { val entry = findSuppressAnnotation(suppressAt.expression) if (entry != null) { // already annotated with @suppress addArgumentToSuppressAnnotation(entry, id) } else { suppressAtExpression(suppressAt, id) } } private fun suppressAtExpression(caretBox: CaretBox<KtExpression>, id: String) { val suppressAt = caretBox.expression assert(suppressAt !is KtDeclaration) { "Declarations should have been checked for above" } val placeholderText = "PLACEHOLDER_ID" val annotatedExpression = KtPsiFactory(suppressAt).createExpression(suppressAnnotationText(id) + "\n" + placeholderText) val copy = suppressAt.copy()!! val afterReplace = suppressAt.replace(annotatedExpression) as KtAnnotatedExpression val toReplace = afterReplace.findElementAt(afterReplace.textLength - 2)!! assert(toReplace.text == placeholderText) val result = toReplace.replace(copy)!! caretBox.positionCaretInCopy(result) } private fun addArgumentToSuppressAnnotation(entry: KtAnnotationEntry, id: String) { // add new arguments to an existing entry val args = entry.valueArgumentList val psiFactory = KtPsiFactory(entry) val newArgList = psiFactory.createCallArguments("($id)") when { args == null -> // new argument list entry.addAfter(newArgList, entry.lastChild) args.arguments.isEmpty() -> // replace '()' with a new argument list args.replace(newArgList) else -> args.addArgument(newArgList.arguments[0]) } } private fun suppressAnnotationText(id: String, withAt: Boolean = true) = "${if (withAt) "@" else ""}${StandardNames.FqNames.suppress.shortName()}($id)" private fun findSuppressAnnotation(annotated: KtAnnotated): KtAnnotationEntry? { val context = annotated.analyze() return findSuppressAnnotation(context, annotated.annotationEntries) } private fun findSuppressAnnotation(annotationList: KtFileAnnotationList): KtAnnotationEntry? { val context = annotationList.analyze() return findSuppressAnnotation(context, annotationList.annotationEntries) } private fun findSuppressAnnotation(context: BindingContext, annotationEntries: List<KtAnnotationEntry>): KtAnnotationEntry? { return annotationEntries.firstOrNull { entry -> context.get(BindingContext.ANNOTATION, entry)?.fqName == StandardNames.FqNames.suppress } } } class AnnotationHostKind(val kind: String, val name: String, val newLineNeeded: Boolean) private fun KtPsiFactory.createWhiteSpace(kind: AnnotationHostKind): PsiElement { return if (kind.newLineNeeded) createNewLine() else createWhiteSpace() } private class CaretBox<out E : KtExpression>( val expression: E, private val editor: Editor? ) { private val offsetInExpression: Int = (editor?.caretModel?.offset ?: 0) - expression.textRange!!.startOffset fun positionCaretInCopy(copy: PsiElement) { if (editor == null) return editor.caretModel.moveToOffset(copy.textOffset + offsetInExpression) } }
apache-2.0
940cce44105bf0a0dcf81885546042a3
41.587912
158
0.6972
5.604483
false
false
false
false
smmribeiro/intellij-community
plugins/completion-ml-ranking/src/com/intellij/completion/ml/ranker/local/catboost/LocalCatBoostModelProvider.kt
9
1616
package com.intellij.completion.ml.ranker.local.catboost import com.intellij.completion.ml.ranker.local.DecisionFunctionWithLanguages import com.intellij.completion.ml.ranker.local.LocalZipModelProvider import com.intellij.completion.ml.ranker.local.ZipCompletionRankingModelMetadataReader import com.intellij.internal.ml.FeaturesInfo import com.intellij.internal.ml.catboost.NaiveCatBoostModel import com.intellij.internal.ml.completion.CompletionRankingModelBase import com.intellij.openapi.diagnostic.logger import java.util.zip.ZipFile class LocalCatBoostModelProvider : LocalZipModelProvider { companion object { private const val MODEL_FILE = "model.bin" private val LOG = logger<LocalCatBoostModelProvider>() } override fun isSupportedFormat(file: ZipFile): Boolean { return file.getEntry(MODEL_FILE) != null } override fun loadModel(file: ZipFile): DecisionFunctionWithLanguages { val reader = ZipCompletionRankingModelMetadataReader(file) val metadata = FeaturesInfo.buildInfo(reader) val languages = reader.getSupportedLanguages() val stream = reader.tryGetResourceAsStream(MODEL_FILE) ?: throw IllegalStateException("Can't find '$MODEL_FILE' resource in zip file") val model = stream.use { NaiveCatBoostModel.loadModel(it) } return DecisionFunctionWithLanguages(object : CompletionRankingModelBase(metadata) { override fun predict(features: DoubleArray): Double { try { return model.makePredict(features) } catch (t: Throwable) { LOG.error(t) return 0.0 } } }, languages) } }
apache-2.0
6aa7bbd69cc78d579880415230016a51
39.425
138
0.761757
4.476454
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/new/tests/testData/inference/nullability/typeCast.kt
13
692
fun foo() { val cast1: /*T1@*/Int = 1/*LIT*/ as /*T0@*/Int/*T0@Int*/ val cast2: /*T3@*/Int? = null/*NULL!!U*/ as /*T2@*/Int?/*T2@Int*/ val cast3: /*T5@*/Float = (1/*LIT*/ as /*T4@*/Int/*T4@Int*/)/*T4@Int*/.toFloat()/*Float!!L*/ val nya: /*T6@*/Int? = null/*NULL!!U*/ val cast4: /*T8@*/Int? = nya/*T6@Int*/ as /*T7@*/Int?/*T7@Int*/ } //LOWER <: T0 due to 'ASSIGNMENT' //T0 <: T1 due to 'INITIALIZER' //UPPER <: T2 due to 'ASSIGNMENT' //T2 <: T3 due to 'INITIALIZER' //LOWER <: T4 due to 'ASSIGNMENT' //T4 := LOWER due to 'USE_AS_RECEIVER' //LOWER <: T5 due to 'INITIALIZER' //UPPER <: T6 due to 'INITIALIZER' //T6 <: T7 due to 'ASSIGNMENT' //T7 <: T8 due to 'INITIALIZER'
apache-2.0
254722189ed2a0696870e8fb9930c3cf
37.444444
96
0.559249
2.516364
false
false
false
false
Jire/Charlatano
src/main/kotlin/com/charlatano/utils/Angle.kt
1
1559
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.utils import java.lang.Math.abs typealias Angle = Vector fun Vector.normalize() = apply { if (x != x) x = 0.0 if (y != y) y = 0.0 if (x > 89) x = 89.0 if (x < -89) x = -89.0 while (y > 180) y -= 360 while (y <= -180) y += 360 if (y > 180) y = 180.0 if (y < -180F) y = -180.0 z = 0.0 } internal fun Angle.distanceTo(target: Angle) = abs(x - target.x) + abs(y - target.y) + abs(z - target.z) internal fun Angle.isValid() = !(z != 0.0 || x < -89 || x > 180 || y < -180 || y > 180 || x.isNaN() || y.isNaN() || z.isNaN()) internal fun Angle.finalize(orig: Angle, strictness: Double) { x -= orig.x y -= orig.y z = 0.0 normalize() x = orig.x + x * strictness y = orig.y + y * strictness normalize() }
agpl-3.0
4b8e3bef5f21ad8ca958ddb4f8387e40
26.368421
104
0.649134
3.056863
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/models/ResponseHandlingModel.kt
1
2614
package ch.rmy.android.http_shortcuts.data.models import ch.rmy.android.http_shortcuts.data.enums.ResponseDisplayAction import io.realm.RealmList import io.realm.RealmModel import io.realm.annotations.RealmClass @RealmClass(name = "ResponseHandling", embedded = true) open class ResponseHandlingModel( var uiType: String = UI_TYPE_WINDOW, var successOutput: String = SUCCESS_OUTPUT_RESPONSE, var failureOutput: String = FAILURE_OUTPUT_DETAILED, var successMessage: String = "", var includeMetaInfo: Boolean = false, displayActions: List<ResponseDisplayAction> = listOf( ResponseDisplayAction.RERUN, ResponseDisplayAction.SHARE, ResponseDisplayAction.SAVE, ), ) : RealmModel { private var actions: RealmList<String> init { actions = RealmList<String>().apply { addAll(displayActions.map { it.key }) } } var displayActions: List<ResponseDisplayAction> get() = actions.mapNotNull(ResponseDisplayAction::parse) set(value) { actions = RealmList<String>().apply { addAll(value.map { it.key }) } } fun validate() { if (uiType !in setOf(UI_TYPE_WINDOW, UI_TYPE_DIALOG, UI_TYPE_TOAST)) { throw IllegalArgumentException("Invalid response handling type: $uiType") } if (successOutput !in setOf(SUCCESS_OUTPUT_MESSAGE, SUCCESS_OUTPUT_RESPONSE, SUCCESS_OUTPUT_NONE)) { throw IllegalArgumentException("Invalid response handling success output: $successOutput") } if (failureOutput !in setOf(FAILURE_OUTPUT_DETAILED, FAILURE_OUTPUT_SIMPLE, FAILURE_OUTPUT_NONE)) { throw IllegalArgumentException("Invalid response handling failure output: $failureOutput") } } fun isSameAs(other: ResponseHandlingModel?) = other?.uiType == uiType && other.successOutput == successOutput && other.failureOutput == failureOutput && other.successMessage == successMessage && other.includeMetaInfo == includeMetaInfo && other.actions == actions companion object { const val UI_TYPE_TOAST = "toast" const val UI_TYPE_DIALOG = "dialog" const val UI_TYPE_WINDOW = "window" const val SUCCESS_OUTPUT_RESPONSE = "response" const val SUCCESS_OUTPUT_MESSAGE = "message" const val SUCCESS_OUTPUT_NONE = "none" const val FAILURE_OUTPUT_DETAILED = "detailed" const val FAILURE_OUTPUT_SIMPLE = "simple" const val FAILURE_OUTPUT_NONE = "none" } }
mit
9c544a852472b357b4053e49d7c354ec
34.324324
108
0.656848
4.56993
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/activity/policies/AccountCreationTermsViewState.kt
2
1390
/* * Copyright 2018 New Vector Ltd * * 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 im.vector.activity.policies import org.matrix.androidsdk.rest.model.login.LocalizedFlowDataLoginTerms data class AccountCreationTermsViewState( val localizedFlowDataLoginTermsChecked: List<LocalizedFlowDataLoginTermsChecked> ) { fun check(data: LocalizedFlowDataLoginTerms) { localizedFlowDataLoginTermsChecked.find { it.localizedFlowDataLoginTerms == data }?.checked = true } fun uncheck(data: LocalizedFlowDataLoginTerms) { localizedFlowDataLoginTermsChecked.find { it.localizedFlowDataLoginTerms == data }?.checked = false } fun allChecked(): Boolean { localizedFlowDataLoginTermsChecked.forEach { if (!it.checked) { return false } } // Ok return true } }
apache-2.0
e85112311e05b0d37c8afc423f9f82d2
32.119048
107
0.71295
4.894366
false
false
false
false
Duke1/UnrealMedia
UnrealMedia/app/src/main/java/com/qfleng/um/BaseActivity.kt
1
1584
package com.qfleng.um import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.LayoutInflater import androidx.appcompat.app.AppCompatActivity import android.view.View import androidx.lifecycle.Observer import com.qfleng.um.audio.AudioPlayManager import com.qfleng.um.bean.MediaInfo import com.qfleng.um.fragment.AudioControlFragment open class BaseActivity : AppCompatActivity() { val handler = Handler(Looper.getMainLooper()) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun setContentView(layoutResID: Int) { setContentView(LayoutInflater.from(this).inflate(layoutResID, null)) } override fun setContentView(view: View?) { super.setContentView(view) setupControlView() } private fun setupControlView() { // val bottomSheetBehavior = BottomSheetBehavior.from<View>(playerControlLayout) // bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED if (findViewById<View>(R.id.define_audio_control_view) != null) { AudioPlayManager.INSTANCE.mediaInfoLd.observe(this, Observer<MediaInfo> { if (null != it) { supportFragmentManager .beginTransaction() .replace(R.id.define_audio_control_view, AudioControlFragment()) .commit() } }) } } fun doOnUi(func: () -> Unit) { handler.post { func() } } }
mit
5c3d22740e24f94236f29765c3b11979
25.4
92
0.653409
4.8
false
false
false
false
masm11/contextplayer
app/src/main/java/me/masm11/contextplayer/player/Player.kt
1
23244
/* Context Player - Audio Player with Contexts Copyright (C) 2016, 2017 Yuuki Harano 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 me.masm11.contextplayer.player import android.media.MediaPlayer import android.media.AudioAttributes import android.net.Uri import android.content.Context import android.os.Handler import android.os.Looper import android.os.Message import me.masm11.contextplayer.ui.ExplorerActivity import me.masm11.contextplayer.fs.MFile import me.masm11.logger.Log import java.util.Locale class Player : Runnable { class CreatedMediaPlayer (val mediaPlayer: MediaPlayer, val path: String) data class PlayArgs(val path: String?, val pos: Int, val start: Boolean) private val OP_PLAY = 1 private val OP_STOP = 2 private val OP_SEEK = 3 private val OP_SET_VOLUME = 4 private val OP_SET_TOPDIR = 6 private val OP_PREV = 7 private val OP_NEXT = 8 private val OP_TOGGLE = 9 private val OP_FINISH = 10 private lateinit var thr: Thread private lateinit var ctxt: Context private lateinit var attr: AudioAttributes private var aid: Int = 0 private var topDir = "/" var playingPath: String? = null get() = field private set(path) { field = path } private var nextPath: String? = null private var curPlayer: MediaPlayer? = null private var nextPlayer: MediaPlayer? = null private var volume: Int = 0 private var handler: Handler? = null private lateinit var mainHandler: Handler inner class HandlerCallback: Handler.Callback { override fun handleMessage(msg: Message): Boolean { Log.d("handleMessage: ${msg.what}") when (msg.what) { OP_PLAY -> handle_play(msg) OP_STOP -> handle_stop(msg) OP_SEEK -> handle_seek(msg) OP_SET_VOLUME -> handle_set_volume(msg) OP_SET_TOPDIR -> handle_set_topdir(msg) OP_PREV -> handle_prev(msg) OP_NEXT -> handle_next(msg) OP_TOGGLE -> handle_toggle(msg) OP_FINISH -> handle_finish(msg) else -> return false } return true } private fun handle_play(msg: Message) { /* 再生を開始する。 * - path が指定されている場合: * → その path から開始し、再生できる曲を曲先頭から再生する。 * - path が指定されていない場合: * - curPlayer != null の場合: * → curPlayer.play() する。 * - curPlayer == null の場合: * - playingPath != null の場合: * → その path から開始し、再生できる曲を曲先頭から再生する。 * - playingPath == null の場合: * → topDir 内で最初に再生できる曲を再生する。 */ val args = msg.obj as PlayArgs val path = args.path val pos = args.pos val start = args.start Log.i("path=${path}") Log.d("release nextPlayer") releaseNextPlayer() if (path != null) { // path が指定された。 // その path から開始し、再生できる曲を曲先頭から再生する。 Log.d("path=${path}") Log.d("release curPlayer") releaseCurPlayer() Log.d("createMediaPlayer") val ret = createMediaPlayer(path, pos, false) if (ret == null) { Log.w("No audio file found.") return } Log.d("createMediaPlayer OK.") curPlayer = ret.mediaPlayer playingPath = ret.path Log.d("curPlayer=${curPlayer}") Log.d("playingPath=${playingPath}") } else if (curPlayer != null) { // path が指定されてない && 再生途中だった // 再生再開 Log.d("curPlayer exists. starting it.") } else if (playingPath != null) { // path が指定されてない && 再生途中でない && context に playingPath がある // その path から開始し、再生できる曲を曲先頭から再生する。 Log.d("playingPath=${playingPath}") Log.d("release nextPlayer") releaseCurPlayer() Log.d("creating mediaplayer.") val ret = createMediaPlayer(playingPath, pos, false) if (ret == null) { Log.w("No audio file found.") return } Log.d("creating mediaplayer OK.") curPlayer = ret.mediaPlayer playingPath = ret.path Log.d("curPlayer=${curPlayer}") Log.d("playingPath=${playingPath}") } else { // 何もない // topDir 内から再生できる曲を探し、曲先頭から再生する。 Log.d("none.") Log.d("release curPlayer.") releaseCurPlayer() Log.d("creating mediaplayer.") val ret = createMediaPlayer("", 0, false) if (ret == null) { Log.w("No audio file found.") return } Log.d("creating mediaplayer OK.") curPlayer = ret.mediaPlayer playingPath = ret.path Log.d("curPlayer=${curPlayer}") Log.d("playingPath=${playingPath}") } if (start) { Log.d("starting.") setMediaPlayerVolume() startPlay() Log.d("enqueue next player.") enqueueNext() } callOneshotBroadcastListener() } private fun handle_stop(@Suppress("UNUSED_PARAMETER") msg: Message) { /* 再生を一時停止する。 * - curPlayer != null の場合 * → pause() し、context を保存する * - curPlayer == null の場合 * → 何もしない */ Log.d("") stopPlay() } private fun handle_seek(msg: Message) { val plr = curPlayer Log.d("pos=${msg.arg1}") if (msg.arg1 != -1 && plr != null) plr.seekTo(msg.arg1) } private fun handle_set_volume(msg: Message) { volume = msg.arg1 val vol = volume.toFloat() / 100.0f curPlayer?.setVolume(vol, vol) nextPlayer?.setVolume(vol, vol) } private fun handle_set_topdir(msg: Message) { topDir = msg.obj as String // 「次の曲」が変わる可能性があるので、enqueue しなおす。 if (curPlayer != null) { Log.d("enqueue next player.") enqueueNext() } } private fun handle_prev(@Suppress("UNUSED_PARAMETER") msg: Message) { val player: MediaPlayer? = curPlayer if (player != null) { val pos = player.currentPosition if (pos >= 3 * 1000) player.seekTo(0) else { releaseNextPlayer() releaseCurPlayer() val ret = createMediaPlayer(selectPrev(playingPath), 0, true) if (ret == null) { Log.w("No audio file.") stopPlay() } else { val mp = ret.mediaPlayer curPlayer = mp playingPath = ret.path setMediaPlayerVolume() mp.start() enqueueNext() } } } } private fun handle_next(@Suppress("UNUSED_PARAMETER") msg: Message) { if (curPlayer != null) { releaseCurPlayer() playingPath = nextPath curPlayer = nextPlayer nextPath = null nextPlayer = null val plr = curPlayer if (plr != null) { plr.start() enqueueNext() } } } private fun handle_toggle(@Suppress("UNUSED_PARAMETER") msg: Message) { Log.d("") val plr = curPlayer if (plr != null && plr.isPlaying) stopPlay() else play(null) } private fun handle_finish(@Suppress("UNUSED_PARAMETER") msg: Message) { Looper.myLooper()?.quitSafely() stopPlay() } } override fun run() { Looper.prepare() handler = Handler(HandlerCallback()) Looper.loop() Log.d("thread exiting.") } fun finish() { val h = handler if (h != null) { val msg = Message.obtain(h, OP_FINISH) h.sendMessage(msg) } thr.join() } fun play(path: String?) { val h = handler if (h != null) { val args = PlayArgs(path, 0, true) val msg = Message.obtain(h, OP_PLAY, args) h.sendMessage(msg) } } fun stop() { val h = handler if (h != null) { val msg = Message.obtain(h, OP_STOP) h.sendMessage(msg) } } fun next() { val h = handler if (h != null) { val msg = Message.obtain(h, OP_NEXT) h.sendMessage(msg) } } fun prev() { val h = handler if (h != null) { val msg = Message.obtain(h, OP_PREV) h.sendMessage(msg) } } fun toggle() { val h = handler if (h != null) { val msg = Message.obtain(h, OP_TOGGLE) h.sendMessage(msg) } } fun seek(pos: Int) { val h = handler if (h != null) { val msg = Message.obtain(h, OP_SEEK, pos, 0) h.sendMessage(msg) } } val currentPosition: Int get() { val plr = curPlayer if (plr != null) { try { return plr.currentPosition } catch (e: IllegalStateException) { // return 0 } } return 0 } val duration: Int get() { val plr = curPlayer if (plr != null) { try { return plr.duration } catch (e: IllegalStateException) { // return 0 } } return 0 } val isPlaying: Boolean get() { val plr = curPlayer if (plr != null) { try { return plr.isPlaying } catch (e: IllegalStateException) { // return false } } return false } fun setVolume(vol: Int) { val h = handler if (h != null) { val msg = Message.obtain(h, OP_SET_VOLUME, vol, 0) h.sendMessage(msg) } } fun setFile(path: String?, pos: Int) { val h = handler if (h != null) { val args = PlayArgs(path, pos, false) val msg = Message.obtain(h, OP_PLAY, args) h.sendMessage(msg) } } fun setTopDir(path: String) { val h = handler if (h != null) { val msg = Message.obtain(h, OP_SET_TOPDIR, path) h.sendMessage(msg) } } // curPlayer がセットされた状態で呼ばれ、 // 再生を start する。 private fun startPlay() { if (curPlayer != null) { Log.d("request audio focus.") callAudioFocusRequestListener(true) setMediaPlayerVolume() try { Log.d("starting.") curPlayer?.start() } catch (e: Exception) { Log.e("exception", e) } Log.d("set to foreground") callSetForegroundListener(true) callStartBroadcastListener(true) callUpdateAppWidgetListener() callSaveContextListener() } } private fun stopPlay() { try { callStartBroadcastListener(false) Log.d("set to non-foreground") callSetForegroundListener(false) setMediaPlayerVolume() val plr = curPlayer if (plr != null) { /* paused から pause() は問題ないが、 * prepared から pause() は正しくないみたい。 */ if (plr.isPlaying) { Log.d("pause ${plr}") plr.pause() } else Log.d("already paused ${plr}") } callUpdateAppWidgetListener() Log.d("abandon audio focus.") callAudioFocusRequestListener(false) Log.d("save context") callSaveContextListener() } catch (e: Exception) { Log.e("exception", e) } } private fun setMediaPlayerVolume() { val vol = volume.toFloat() / 100.0f curPlayer?.setVolume(vol, vol) nextPlayer?.setVolume(vol, vol) } private fun enqueueNext() { Log.d("release nextPlayer") releaseNextPlayer() Log.d("creating mediaplayer") val ret = createMediaPlayer(selectNext(playingPath), 0, false) if (ret == null) { Log.w("No audio file found.") return } Log.d("creating mediaplayer OK.") nextPlayer = ret.mediaPlayer nextPath = ret.path setMediaPlayerVolume() Log.d("nextPlayer=${nextPlayer}") Log.d("nextPath=${nextPath}") try { Log.d("setting it as nextmediaplayer.") curPlayer?.setNextMediaPlayer(nextPlayer) } catch (e: Exception) { Log.e("exception", e) } } private fun createMediaPlayer(startPath: String?, startPos: Int, back: Boolean): CreatedMediaPlayer? { var path = startPath var pos = startPos Log.d("path=${path}") Log.d("pos=${pos}") var tested = emptySet<String>() while (true) { Log.d("iter") try { Log.d("path=${path}") if (path == null || tested.contains(path)) { // 再生できるものがない… Log.d("No audio file.") return null } tested = tested + path Log.d("try create mediaplayer.") val player = MediaPlayer.create(ctxt, Uri.parse("file://${MFile(path).file.absolutePath}"), null, attr, aid) if (player == null) { Log.w("MediaPlayer.create() failed: ${path}") path = if (back) selectPrev(path) else selectNext(path) pos = 0 // お目当てのファイルが見つからなかった。次のファイルの先頭からとする。 continue } Log.d("create mediaplayer ok.") if (pos > 0) { // 0 の場合に seekTo() すると、曲の頭が切れるみたい? Log.d("seek to ${pos}") player.seekTo(pos) } player.setOnCompletionListener { mp -> Log.d("shifting") playingPath = nextPath curPlayer = nextPlayer Log.d("now playingPath=${playingPath}") Log.d("now curPlayer=${curPlayer}") Log.d("releasing ${mp}") mp.release() Log.d("clearing nextPath/nextPlayer") nextPath = null nextPlayer = null callSaveContextListener() if (curPlayer != null) { Log.d("enqueue next mediaplayer.") enqueueNext() } else stopPlay() } player.setOnErrorListener(MediaPlayer.OnErrorListener { _, what, extra -> Log.d("error reported. ${what}, ${extra}.") // 両方 release して新たに作り直す。 releaseNextPlayer() releaseCurPlayer() Log.d("creating mediaplayer.") val ret = createMediaPlayer(nextPath, 0, false) if (ret == null) { Log.w("No audio file found.") stopPlay() return@OnErrorListener true } curPlayer = ret.mediaPlayer playingPath = ret.path setMediaPlayerVolume() Log.d("starting it.") curPlayer?.start() Log.d("enqueuing next.") enqueueNext() setMediaPlayerVolume() callSaveContextListener() true }) Log.d("done. player=${player}, path=${path}") return CreatedMediaPlayer(player, path) } catch (e: Exception) { Log.e("exception", e) } return null } } private fun releaseCurPlayer() { Log.d("") try { Log.d("releasing...") curPlayer?.release() Log.d("releasing... ok") curPlayer = null } catch (e: Exception) { Log.e("exception", e) } } private fun releaseNextPlayer() { Log.d("") try { Log.d("releasing...") nextPlayer?.release() Log.d("releasing... ok") nextPlayer = null } catch (e: Exception) { Log.e("exception", e) } } private fun selectNext(nextOf: String?): String? { if (nextOf == null) return null; Log.d("nextOf=${nextOf}") var found: String? = null if (nextOf.startsWith(topDir)) { if (topDir != "//") { // +1: for '/' ↓ val parts = nextOf.substring(topDir.length + 1).split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() found = lookForFile(MFile(topDir), parts, 0, false) } else { val parts = nextOf.substring(2).split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() found = lookForFile(MFile(topDir), parts, 0, false) } } if (found == null) found = lookForFile(MFile(topDir), null, 0, false) Log.d("found=${found}") return found } private fun selectPrev(prevOf: String?): String? { if (prevOf == null) return null; Log.d("prevOf=${prevOf}") var found: String? = null if (prevOf.startsWith(topDir)) { if (topDir != "//") { // +1: for '/' ↓ val parts = prevOf.substring(topDir.length + 1).split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() found = lookForFile(MFile(topDir), parts, 0, true) } else { val parts = prevOf.substring(2).split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() found = lookForFile(MFile(topDir), parts, 0, true) } } if (found == null) found = lookForFile(MFile(topDir), null, 0, true) Log.d("found=${found}") return found } /* 次のファイルを探す。 * dir: 今見ているディレクトリ * parts[]: topdir からの相対 path。'/' で区切られている。 * parts_idx: ディレクトリの nest。 * backward: 逆向き検索。 * 最初にこのメソッドに来る時、nextOf は、 * /dir/parts[0]/parts[1]/…/parts[N] * だったことになる。 * lookForFile() の役割は、dir 内 subdir も含めて、nextOf の次のファイルを探すこと。 * parts == null の場合、nextOf の path tree から外れた場所を探している。 */ private fun lookForFile(dir: MFile, parts: Array<String>?, parts_idx: Int, backward: Boolean): String? { var cur: String? = null if (parts != null) { if (parts_idx < parts.size) cur = parts[parts_idx] } val files = ExplorerActivity.listFiles(dir, backward) for (file in files) { if (cur == null) { if (file.isDirectory) { val r = lookForFile(file, null, parts_idx + 1, backward) if (r != null) return r } else { return file.absolutePath } } else { val compare = comparePath(file.name, cur) if (compare == 0) { // 今そこ。 if (file.isDirectory) { val r = lookForFile(file, parts, parts_idx + 1, backward) if (r != null) return r } else { // これは今再生中。 } } else if (!backward && compare > 0) { if (file.isDirectory) { // 次を探していたら dir だった val r = lookForFile(file, null, parts_idx + 1, backward) if (r != null) return r } else { // 次のファイルを見つけた return file.absolutePath } } else if (backward && compare < 0) { if (file.isDirectory) { // 次を探していたら dir だった val r = lookForFile(file, null, parts_idx + 1, backward) if (r != null) return r } else { // 次のファイルを見つけた return file.absolutePath } } } } return null } private fun comparePath(p1: String, p2: String): Int { val l1 = p1.toLowerCase(Locale.getDefault()) val l2 = p2.toLowerCase(Locale.getDefault()) var r = l1.compareTo(l2) if (r == 0) r = p1.compareTo(p2) return r } private fun callSaveContextListener() { mainHandler.post { saveContextListener() } } private fun callSetForegroundListener(onoff: Boolean) { mainHandler.post { setForegroundListener(onoff) } } private fun callStartBroadcastListener(onoff: Boolean) { mainHandler.post { startBroadcastListener(onoff) } } private fun callUpdateAppWidgetListener() { mainHandler.post { updateAppWidgetListener() } } private fun callAudioFocusRequestListener(onoff: Boolean) { mainHandler.post { audioFocusRequestListener(onoff) } } private fun callOneshotBroadcastListener() { mainHandler.post { oneshotBroadcastListener() } } private lateinit var saveContextListener: () -> Unit private lateinit var setForegroundListener: (Boolean) -> Unit private lateinit var startBroadcastListener: (Boolean) -> Unit private lateinit var updateAppWidgetListener: () -> Unit private lateinit var audioFocusRequestListener: (Boolean) -> Unit private lateinit var oneshotBroadcastListener: () -> Unit companion object { fun create(ctxt: Context, attr: AudioAttributes, aid: Int, saveContextListener: () -> Unit, setForegroundListener: (Boolean) -> Unit, startBroadcastListener: (Boolean) -> Unit, updateAppWidgetListener: () -> Unit, audioFocusRequestListener: (Boolean) -> Unit, oneshotBroadcastListener: () -> Unit) : Player { val p = Player() p.mainHandler = Handler() p.ctxt = ctxt p.attr = attr p.aid = aid p.saveContextListener = saveContextListener p.setForegroundListener = setForegroundListener p.startBroadcastListener = startBroadcastListener p.updateAppWidgetListener = updateAppWidgetListener p.audioFocusRequestListener = audioFocusRequestListener p.oneshotBroadcastListener = oneshotBroadcastListener p.thr = Thread(p) p.thr.start() while (p.handler == null) Thread.sleep(100) return p } } }
apache-2.0
ac779122939e7f9a25cc44b5d55d6bfe
26.5975
124
0.545611
4.054729
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/breadwallet/breadbox/NetworkManager.kt
1
11748
/** * BreadWallet * * Created by Ahsan Butt <[email protected]> on 10/01/19. * Copyright (c) 2019 breadwallet LLC * * 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.breadwallet.breadbox import com.breadwallet.crypto.AddressScheme import com.breadwallet.crypto.Network import com.breadwallet.crypto.NetworkPeer import com.breadwallet.crypto.System import com.breadwallet.crypto.Wallet import com.breadwallet.crypto.WalletManager import com.breadwallet.crypto.WalletManagerMode import com.breadwallet.logger.logDebug import com.breadwallet.tools.manager.BRSharedPrefs import com.breadwallet.util.isBitcoin import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.BroadcastChannel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch import java.util.concurrent.ConcurrentHashMap /** * Responsible for tracking (and un-tracking) [Wallet]s and all related hook-up. */ class NetworkManager( private val system: System, private val scope: CoroutineScope, private val networkInitializers: List<NetworkInitializer> ) { var enabledWallets: List<String> = emptyList() set(value) { if (field == value) return field = value scope.launch { updateWallets() } } var managerModes: Map<String, WalletManagerMode> = emptyMap() set(value) { if (field == value) return field = value scope.launch { updateManagerModes() } } private val initializeActionChannel = ConcurrentHashMap<String, Channel<Unit>>() private val networkState = ConcurrentHashMap<String, NetworkState>() private val networkStateChannel = BroadcastChannel<Pair<String, NetworkState>>(Channel.BUFFERED) init { system.networks.forEach(::initializeNetwork) } /** * Initializes a [Network]. */ fun initializeNetwork(network: Network) { if (system.walletManagers.any { it.network == network }) { logDebug("WalletManager for network (${network.uids}) already exists.") networkState[network.currency.uids] = NetworkState.Initialized return } scope.launch { initializeNetwork(network, false) } } /** * Emits the [NetworkState] for a [Network] specified by its [currencyId] */ fun networkState(currencyId: String) = networkStateChannel .asFlow() .filter { it.first.equals(currencyId, true) } .mapLatest { it.second } .onStart { networkState[currencyId]?.let { emit(it) } ?: emit(NetworkState.Loading) } /** * Completes the initialization process for a [Network] specified by * its [currencyId]. */ fun completeNetworkInitialization(currencyId: String) { val channel = checkNotNull(initializeActionChannel[currencyId]) { "Network for $currencyId not waiting on initialize action." } channel.offer(Unit) } /** * Connects a [WalletManager] if needed. */ fun connectManager(manager: WalletManager) { scope.launch { enabledWallets .filter { manager.networkContainsCurrency(it) } .onEach { val networkPeer = getNetworkPeer(manager) val network = manager.network manager.mode = network.getManagerMode(managerModes[network.currency.uids]) manager.connect(networkPeer) } } } /** * Registers all needed currencies for the given [WalletManager]. */ fun registerCurrencies(manager: WalletManager) { scope.launch { enabledWallets .filter { manager.networkContainsCurrency(it) } .onEach { logDebug("Registering wallet for: $it") manager.registerWalletFor(manager.findCurrency(it)) } } } private suspend fun initializeNetwork(network: Network, createIfNeeded: Boolean) { val initializer = networkInitializers.get(network.currency.uids) if (initializer == null) { logDebug("No initializer found for network '${network.name}'") return } if (createIfNeeded) { emitNetworkState(network.currency.uids, NetworkState.Loading) } val state = initializer.initialize(system, network, createIfNeeded) emitNetworkState(network.currency.uids, state) when (state) { is NetworkState.Initialized -> { logDebug("Network '${network.name}' initialized.") val wmMode = network.getManagerMode(managerModes[network.currency.uids]) system.createWalletManager( network, wmMode, network.getAddressScheme(), emptySet() ) } is NetworkState.ActionNeeded -> { logDebug("Network '${network.name}' requires further action.") waitForInitializeAction(network) } is NetworkState.Error -> { logDebug( "Network '${network.name}' failed to initialize. ${state.message}", state.error ) emitNetworkState(network.currency.uids, NetworkState.ActionNeeded) waitForInitializeAction(network) } } } private suspend fun waitForInitializeAction(network: Network) { initializeActionChannel.getSafe(network.currency.uids).receive() initializeNetwork(network, true) } private fun updateWallets() { // Disconnect unneeded wallet managers val systemWallets = system.wallets systemWallets.forEach { disconnectWalletManager(it, enabledWallets) } // Enable wallets by connecting and registering as necessary enabledWallets.forEach { enabledWallet -> val systemWallet = systemWallets.find { it.currencyId.equals(enabledWallet, true) } val walletManager = systemWallet?.walletManager ?: system .walletManagers .find { it.networkContainsCurrency(enabledWallet) } if (walletManager != null) { connectAndRegister( walletManager, enabledWallet ) } } } private fun updateManagerModes() { managerModes.entries.forEach { modeEntry: Map.Entry<String, WalletManagerMode> -> val wallet = system.wallets.find { it.currencyId.equals(modeEntry.key, true) } val walletManager = wallet?.walletManager ?: system .walletManagers .find { it.networkContainsCurrency(modeEntry.key) } val mode = walletManager?.network?.getManagerMode(modeEntry.value) if (mode != null && walletManager.mode != mode) { logDebug("Restarting Wallet Manager with new mode: ${walletManager.network} ${modeEntry.value}") walletManager.mode = walletManager.network.getManagerMode(modeEntry.value) walletManager.disconnect() walletManager.connect(getNetworkPeer(walletManager)) } } } /** * Disconnect [WalletManager] for [systemWallet], if connected and not needed for * another tracked wallet. */ private fun disconnectWalletManager(systemWallet: Wallet, enabledWallets: List<String>) { val walletManager = systemWallet.walletManager val disconnectWalletManager = walletManager.state.isTracked() && enabledWallets.none { walletManager.networkContainsCurrency(it) } if (disconnectWalletManager) { logDebug("Disconnecting Wallet Manager: ${systemWallet.currency.code}") systemWallet.walletManager.disconnect() } } /** * Connect [WalletManager] for [currencyId], if not already connected, and register for * [currencyId]. */ private fun connectAndRegister( walletManager: WalletManager, currencyId: String ) { val network = walletManager.network val mode = network.getManagerMode(managerModes[network.currency.uids]) val networkPeer = getNetworkPeer(walletManager) if (!walletManager.state.isTracked()) { logDebug("Connecting Wallet Manager: ${walletManager.network}") walletManager.mode = mode walletManager.connect(networkPeer) } // TODO: Once CORE-871 is fixed, calling registerWalletFor() here will be redundant, as // we should get another WalletManagerChangedEvent after connecting above logDebug("Registering wallet for: $currencyId") walletManager.registerWalletFor( walletManager.findCurrency( currencyId ) ) } private fun getNetworkPeer(manager: WalletManager): NetworkPeer? { val address = BRSharedPrefs .getTrustNode(iso = manager.currency.code) .orEmpty() return manager .network .getPeerOrNull(address) } private fun emitNetworkState(currencyId: String, state: NetworkState) { networkState[currencyId] = state networkStateChannel.offer(Pair(currencyId, state)) } } private fun Network.getManagerMode(preferredMode: WalletManagerMode?): WalletManagerMode = when { currency.isBitcoinCash() -> WalletManagerMode.API_ONLY preferredMode == null -> defaultWalletManagerMode supportsWalletManagerMode(preferredMode) -> preferredMode else -> defaultWalletManagerMode } private fun Network.getAddressScheme(): AddressScheme { return when { currency.code.isBitcoin() -> { if (BRSharedPrefs.getIsSegwitEnabled()) { AddressScheme.BTC_SEGWIT } else { AddressScheme.BTC_LEGACY } } else -> defaultAddressScheme } } fun List<NetworkInitializer>.get(currencyId: String) = firstOrNull { it !is DefaultNetworkInitializer && it.isSupported(currencyId) } ?: firstOrNull { it.isSupported(currencyId) } private fun ConcurrentHashMap<String, Channel<Unit>>.getSafe(key: String) = run { getOrElse(key, { Channel() }).also { putIfAbsent(key, it) } }
mit
c18e5fbd28caf8020db9f88a4a748cf9
36.059937
112
0.639854
5.212067
false
false
false
false
Austin72/Charlatano
src/main/kotlin/com/charlatano/utils/Hook.kt
1
1326
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.utils class Hook(val clauseDefault: Boolean, val durationDefault: Int, val predicate: () -> Boolean) { operator inline fun invoke(clause: Boolean = clauseDefault, duration: Int = durationDefault, crossinline body: () -> Unit) { if (!clause) every(duration) { if (predicate()) body() } else if (predicate()) body() } } fun hook(durationDefault: Int = 8, clauseDefault: Boolean = false, predicate: () -> Boolean) = Hook(clauseDefault, durationDefault, predicate)
agpl-3.0
a07cfea7efe96f829170436c4532d1df
38.029412
142
0.714932
3.981982
false
false
false
false
quran/quran_android
app/src/main/java/com/quran/labs/androidquran/ui/translation/TranslationAdapter.kt
2
17721
package com.quran.labs.androidquran.ui.translation import android.content.Context import android.graphics.Color import android.text.SpannableString import android.text.SpannableStringBuilder import android.text.Spanned import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.annotation.LayoutRes import androidx.core.content.ContextCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.quran.common.search.SearchTextUtil import com.quran.data.model.SuraAyah import com.quran.data.model.highlight.HighlightType import com.quran.labs.androidquran.R import com.quran.labs.androidquran.common.QuranAyahInfo import com.quran.labs.androidquran.model.translation.ArabicDatabaseUtils import com.quran.labs.androidquran.ui.helpers.ExpandTafseerSpan import com.quran.labs.androidquran.ui.helpers.HighlightTypes import com.quran.labs.androidquran.ui.helpers.UthmaniSpan import com.quran.labs.androidquran.ui.util.TypefaceManager import com.quran.labs.androidquran.util.QuranSettings import com.quran.labs.androidquran.view.AyahNumberView import com.quran.labs.androidquran.view.DividerView import kotlin.math.ln1p import kotlin.math.min internal class TranslationAdapter( private val context: Context, private val recyclerView: RecyclerView, private val onClickListener: View.OnClickListener, private val onVerseSelectedListener: OnVerseSelectedListener ) : RecyclerView.Adapter<TranslationAdapter.RowViewHolder>() { private val inflater: LayoutInflater = LayoutInflater.from(context) private val data: MutableList<TranslationViewRow> = mutableListOf() private var fontSize: Int = 0 private var textColor: Int = 0 private var dividerColor: Int = 0 private var arabicTextColor: Int = 0 private var suraHeaderColor: Int = 0 private var ayahSelectionColor: Int = 0 private var isNightMode: Boolean = false private var highlightedAyah: Int = 0 private var highlightedRowCount: Int = 0 private var highlightedStartPosition: Int = 0 private var highlightType: HighlightType? = null private val expandedTafseerAyahs = mutableSetOf<Pair<Int, Int>>() private val expandedHyperlinks = mutableSetOf<Pair<Int, Int>>() private val defaultClickListener = View.OnClickListener { this.handleClick(it) } private val defaultLongClickListener = View.OnLongClickListener { this.selectVerseRows(it) } private val expandClickListener = View.OnClickListener { v -> toggleExpandTafseer(v) } private val expandHyperlinkClickListener = View.OnClickListener { v -> toggleExpandTafseer(v) } fun getSelectedVersePopupPosition(): IntArray? { return if (highlightedStartPosition > -1) { val highlightedEndPosition = highlightedStartPosition + highlightedRowCount // find the row with the verse number val versePosition = data.withIndex().firstOrNull { it.index in highlightedStartPosition until highlightedEndPosition && it.value.type == TranslationViewRow.Type.VERSE_NUMBER } // find out where to position the popup based on the center of the box versePosition?.let { positionForViewHolderIndex(versePosition.index) } } else { null } } fun getSelectedVersePopupPosition(sura: Int, ayah: Int): IntArray? { val (startPosition, _) = adapterInfoForAyah(sura, ayah) return if (startPosition > -1) { positionForViewHolderIndex(startPosition) } else { null } } private fun positionForViewHolderIndex(index: Int): IntArray? { val viewHolder = recyclerView.findViewHolderForAdapterPosition(index) as RowViewHolder? return viewHolder?.ayahNumber?.let { ayahNumberView -> val x = (ayahNumberView.left + ayahNumberView.boxCenterX) val y = (ayahNumberView.top + ayahNumberView.boxBottomY) intArrayOf(x, y) } } fun setData(data: List<TranslationViewRow>) { this.data.clear() expandedTafseerAyahs.clear() this.data.addAll(data) if (highlightedAyah > 0) { highlightAyah(highlightedAyah, true, highlightType ?: HighlightTypes.SELECTION, true) } } fun setHighlightedAyah(ayahId: Int, highlightType: HighlightType) { highlightAyah(ayahId, true, highlightType) } fun highlightedAyahInfo(): QuranAyahInfo? { return data.firstOrNull { it.ayahInfo.ayahId == highlightedAyah }?.ayahInfo } private fun adapterInfoForAyah(sura: Int, ayah: Int): Pair<Int, Int> { val matches = data.withIndex().filter { it.value.ayahInfo.sura == sura && it.value.ayahInfo.ayah == ayah && // don't factor in basmalah or sura name it.value.type > 1 } return (matches.firstOrNull()?.index ?: -1) to matches.size } private fun highlightAyah(ayahId: Int, notify: Boolean, highlightedType: HighlightType, force: Boolean = false) { if (ayahId != highlightedAyah || force) { val matches = data.withIndex().filter { it.value.ayahInfo.ayahId == ayahId } val (startPosition, count) = (matches.firstOrNull()?.index ?: -1) to matches.size // highlight the newly highlighted ayah if (count > 0 && notify) { var startChangeCount = count var startChangeRange = startPosition if (highlightedRowCount > 0) { when { // merge the requests for notifyItemRangeChanged when we're either the next ayah highlightedStartPosition + highlightedRowCount + 1 == startPosition -> { startChangeRange = highlightedStartPosition startChangeCount += highlightedRowCount } // ... or when we're the previous ayah highlightedStartPosition - 1 == startPosition + count -> startChangeCount += highlightedRowCount else -> { // otherwise, unhighlight val start = highlightedStartPosition val changeCount = highlightedRowCount recyclerView.handler.post { notifyItemRangeChanged(start, changeCount, HIGHLIGHT_CHANGE) } } } } // and update rows to be highlighted recyclerView.handler.post { notifyItemRangeChanged(startChangeRange, startChangeCount, HIGHLIGHT_CHANGE) val layoutManager = recyclerView.layoutManager if ((force || highlightedType == HighlightTypes.AUDIO) && layoutManager is LinearLayoutManager) { layoutManager.scrollToPositionWithOffset(startPosition, 64) } else { recyclerView.smoothScrollToPosition(startPosition) } } } highlightedAyah = ayahId highlightedStartPosition = startPosition highlightedRowCount = count highlightType = highlightedType } } fun unhighlight() { if (highlightedAyah > 0 && highlightedRowCount > 0) { val start = highlightedStartPosition val count = highlightedRowCount recyclerView.handler.post { notifyItemRangeChanged(start, count) } } highlightedAyah = 0 highlightedRowCount = 0 highlightedStartPosition = -1 } fun refresh(quranSettings: QuranSettings) { this.fontSize = quranSettings.translationTextSize isNightMode = quranSettings.isNightMode if (isNightMode) { val originalTextBrightness = quranSettings.nightModeTextBrightness val backgroundBrightness = quranSettings.nightModeBackgroundBrightness // avoid damaging the looks of the Quran page val adjustedBrightness = (50 * ln1p(backgroundBrightness.toDouble()) + originalTextBrightness).toInt() val textBrightness = min(adjustedBrightness.toFloat(), 255f).toInt() this.textColor = Color.rgb(textBrightness, textBrightness, textBrightness) this.arabicTextColor = textColor this.dividerColor = textColor this.suraHeaderColor = ContextCompat.getColor(context, R.color.translation_sura_header_night) this.ayahSelectionColor = ContextCompat.getColor(context, R.color.translation_ayah_selected_color_night) } else { this.textColor = ContextCompat.getColor(context, R.color.translation_text_color) this.dividerColor = ContextCompat.getColor(context, R.color.translation_divider_color) this.arabicTextColor = Color.BLACK this.suraHeaderColor = ContextCompat.getColor(context, R.color.translation_sura_header) this.ayahSelectionColor = ContextCompat.getColor(context, R.color.translation_ayah_selected_color) } if (this.data.isNotEmpty()) { notifyDataSetChanged() } } private fun handleClick(view: View) { val position = recyclerView.getChildAdapterPosition(view) if (highlightedAyah != 0 && position != RecyclerView.NO_POSITION) { val ayahInfo = data[position].ayahInfo if (ayahInfo.ayahId != highlightedAyah && highlightType == HighlightTypes.SELECTION) { onVerseSelectedListener.onVerseSelected(ayahInfo) return } } onClickListener.onClick(view) } private fun selectVerseRows(view: View): Boolean { val position = recyclerView.getChildAdapterPosition(view) if (position != RecyclerView.NO_POSITION) { val ayahInfo = data[position].ayahInfo highlightAyah(ayahInfo.ayahId, true, HighlightTypes.SELECTION) onVerseSelectedListener.onVerseSelected(ayahInfo) return true } return false } private fun toggleExpandTafseer(view: View) { val position = recyclerView.getChildAdapterPosition(view) if (position != RecyclerView.NO_POSITION) { val data = data[position] val what = data.ayahInfo.ayahId to data.translationIndex if (expandedTafseerAyahs.contains(what)) { expandedTafseerAyahs.remove(what) } else { expandedTafseerAyahs.add(what) } notifyItemChanged(position) } } override fun getItemViewType(position: Int): Int { return data[position].type } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RowViewHolder { @LayoutRes val layout = when (viewType) { TranslationViewRow.Type.SURA_HEADER -> R.layout.quran_translation_header_row TranslationViewRow.Type.BASMALLAH, TranslationViewRow.Type.QURAN_TEXT -> R.layout.quran_translation_arabic_row TranslationViewRow.Type.SPACER -> R.layout.quran_translation_spacer_row TranslationViewRow.Type.VERSE_NUMBER -> R.layout.quran_translation_verse_number_row TranslationViewRow.Type.TRANSLATOR -> R.layout.quran_translation_translator_row else -> R.layout.quran_translation_text_row } val view = inflater.inflate(layout, parent, false) return RowViewHolder(view) } override fun onBindViewHolder(holder: RowViewHolder, position: Int) { val row = data[position] when { // a row with text holder.text != null -> { // reset click listener on the text holder.text.setOnClickListener(defaultClickListener) val text: CharSequence? if (row.type == TranslationViewRow.Type.SURA_HEADER) { text = row.data holder.text.setBackgroundColor(suraHeaderColor) } else if (row.type == TranslationViewRow.Type.BASMALLAH || row.type == TranslationViewRow.Type.QURAN_TEXT) { val str = SpannableString( if (row.type == TranslationViewRow.Type.BASMALLAH) { ArabicDatabaseUtils.AR_BASMALLAH } else { ArabicDatabaseUtils.getAyahWithoutBasmallah( row.ayahInfo.sura, row.ayahInfo.ayah, row.ayahInfo.arabicText ) } ) str.setSpan(UthmaniSpan(context), 0, str.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) text = str holder.text.setTextColor(arabicTextColor) holder.text.textSize = ARABIC_MULTIPLIER * fontSize } else { if (row.type == TranslationViewRow.Type.TRANSLATOR) { text = row.data } else { // translation text = row.data?.let { rowText -> val length = rowText.length val expandHyperlink = expandedHyperlinks.contains(row.ayahInfo.ayahId to row.translationIndex) if (row.link != null && !expandHyperlink) { holder.text.setOnClickListener(expandHyperlinkClickListener) } when { row.link != null && !expandHyperlink -> getAyahLink(row.link) length > MAX_TAFSEER_LENGTH -> truncateTextIfNeeded(rowText, row.ayahInfo.ayahId, row.translationIndex) else -> rowText } } // determine text directionality val isRtl = when { row.isArabic -> true text != null -> SearchTextUtil.isRtl(text.toString()) else -> false } // reset the typeface holder.text.typeface = null if (isRtl) { // rtl tafseer, style it (SDK is always >= 21 now) holder.text.layoutDirection = View.LAYOUT_DIRECTION_RTL // allow the tafseer font for api 19 because it's fine there and // is much better than the stock font (this is more lenient than // the api 21 restriction on the hafs font). only allow this for // Arabic though since the Arabic font isn't compatible with other // RTL languages that share some Arabic characters. // SDK is always >= 21 now if (row.isArabic) { holder.text.typeface = TypefaceManager.getTafseerTypeface(context) } } else { holder.text.layoutDirection = View.LAYOUT_DIRECTION_INHERIT val settings = QuranSettings.getInstance(context) if (settings.wantDyslexicFontInTranslationView()){ holder.text.typeface = TypefaceManager.getDyslexicTypeface(context) } } holder.text.movementMethod = LinkMovementMethod.getInstance() holder.text.setTextColor(textColor) holder.text.textSize = fontSize.toFloat() } } holder.text.text = text } // a divider row holder.divider != null -> { var showLine = true if (position + 1 < data.size) { val nextRow = data[position + 1] if (nextRow.ayahInfo.sura != row.ayahInfo.sura) { showLine = false } } else { showLine = false } holder.divider.toggleLine(showLine) holder.divider.setDividerColor(dividerColor) } // ayah number row holder.ayahNumber != null -> { val text = context.getString(R.string.sura_ayah, row.ayahInfo.sura, row.ayahInfo.ayah) holder.ayahNumber.setAyahString(text) holder.ayahNumber.setTextColor(textColor) holder.ayahNumber.setNightMode(isNightMode) } } updateHighlight(row, holder) } private fun getAyahLink(link: SuraAyah): CharSequence { return context.getString(R.string.see_tafseer_of_verse, link.ayah) } private fun truncateTextIfNeeded( text: CharSequence, ayahId: Int, translationIndex: Int ): CharSequence { if (text.length > MAX_TAFSEER_LENGTH && !expandedTafseerAyahs.contains(ayahId to translationIndex) ) { // let's truncate val lastSpace = text.indexOf(' ', MAX_TAFSEER_LENGTH) if (lastSpace != -1) { return SpannableStringBuilder(text.subSequence(0, lastSpace + 1)).apply { append(context.getString(R.string.more_arabic)) setSpan( ExpandTafseerSpan(expandClickListener), lastSpace + 1, this.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } } } return text } override fun onBindViewHolder(holder: RowViewHolder, position: Int, payloads: List<Any>) { if (payloads.contains(HIGHLIGHT_CHANGE)) { updateHighlight(data[position], holder) } else { super.onBindViewHolder(holder, position, payloads) } } private fun updateHighlight(row: TranslationViewRow, holder: RowViewHolder) { // toggle highlighting of the ayah, but not for sura headers and basmallah val isHighlighted = row.ayahInfo.ayahId == highlightedAyah if (row.type != TranslationViewRow.Type.SURA_HEADER && row.type != TranslationViewRow.Type.BASMALLAH && row.type != TranslationViewRow.Type.SPACER ) { holder.wrapperView.setBackgroundColor( if (isHighlighted) ayahSelectionColor else 0 ) } else if (holder.divider != null) { // SPACER type if (isHighlighted) { holder.divider.highlight(ayahSelectionColor) } else { holder.divider.unhighlight() } } } override fun getItemCount(): Int = data.size internal inner class RowViewHolder(val wrapperView: View) : RecyclerView.ViewHolder(wrapperView) { val text: TextView? = wrapperView.findViewById(R.id.text) val divider: DividerView? = wrapperView.findViewById(R.id.divider) val ayahNumber: AyahNumberView? = wrapperView.findViewById(R.id.ayah_number) init { wrapperView.setOnClickListener(defaultClickListener) wrapperView.setOnLongClickListener(defaultLongClickListener) } } internal interface OnVerseSelectedListener { fun onVerseSelected(ayahInfo: QuranAyahInfo) } companion object { const val ARABIC_MULTIPLIER = 1.4f private const val MAX_TAFSEER_LENGTH = 750 private const val HIGHLIGHT_CHANGE = 1 } }
gpl-3.0
f676ebb27e8f242a9ec7aeda53eb6cf5
37.19181
117
0.677953
4.766272
false
false
false
false
blhps/lifeograph-android
app/src/main/java/net/sourceforge/lifeograph/FragmentEntry.kt
1
54854
/* ********************************************************************************* Copyright (C) 2012-2021 Ahmet Öztürk ([email protected]) This file is part of Lifeograph. Lifeograph 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. Lifeograph 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 Lifeograph. If not, see <http://www.gnu.org/licenses/>. ***********************************************************************************/ package net.sourceforge.lifeograph import android.annotation.SuppressLint import android.content.DialogInterface import android.content.Intent import android.graphics.Color import android.graphics.Typeface import android.net.Uri import android.os.Bundle import android.text.* import android.text.method.LinkMovementMethod import android.text.style.* import android.util.Log import android.view.* import android.view.inputmethod.EditorInfo import android.widget.Button import android.widget.EditText import android.widget.TextView import androidx.appcompat.widget.SearchView import androidx.core.view.MenuItemCompat import net.sourceforge.lifeograph.FragmentEntry.ParserEditText.SpanNull import net.sourceforge.lifeograph.FragmentEntry.ParserEditText.SpanOther import net.sourceforge.lifeograph.ToDoAction.ToDoObject import java.util.* import kotlin.collections.ArrayList class FragmentEntry : FragmentDiaryEditor(), ToDoObject, DialogInquireText.Listener { // private enum class LinkStatus { // LS_OK, LS_ENTRY_UNAVAILABLE, LS_INVALID, // separator: to check a valid entry link: // // // linkstatus < LS_INVALID // LS_CYCLIC, LS_FILE_OK, LS_FILE_INVALID, LS_FILE_UNAVAILABLE, LS_FILE_UNKNOWN // } // VARIABLES =================================================================================== override val mLayoutId: Int = R.layout.fragment_entry override val mMenuId: Int = R.menu.menu_entry private lateinit var mEditText: EditText private lateinit var mButtonHighlight: Button private val mParser = ParserEditText(this) var mFlagSetTextOperation = false private var mFlagEditorActionInProgress = false var mFlagEntryChanged = false private var mFlagDismissOnExit = false var mFlagSearchIsOpen = false private val mBrowsingHistory = ArrayList<Int>() companion object { lateinit var mEntry: Entry } // METHODS ===================================================================================== override fun onViewCreated(view: View, savedInstanceState: Bundle?) { ActivityMain.mViewCurrent = this //Lifeograph.updateScreenSizes( this ); mEditText = view.findViewById(R.id.editTextEntry) mEditText.movementMethod = LinkMovementMethod.getInstance() //mKeyListener = mEditText.keyListener if(!Diary.d.is_in_edit_mode) { mEditText.setRawInputType( InputType.TYPE_NULL ) mEditText.isFocusable = false //mEditText.setTextIsSelectable(true) --above seems to work better //mEditText.keyListener = null view.findViewById<View>(R.id.toolbar_text_edit).visibility = View.GONE } if(Lifeograph.screenHeight >= Lifeograph.MIN_HEIGHT_FOR_NO_EXTRACT_UI) mEditText.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI // set custom font as the default font may lack the necessary chars such as check marks: /*Typeface font = Typeface.createFromAsset( getAssets(), "OpenSans-Regular.ttf" ); mEditText.setTypeface( font );*/ mEditText.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable) {} override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { if(!mFlagSetTextOperation) { // if( start > 0 ) { // m_pos_start = mEditText.getText().toString().indexOf( '\n', start - 1 ); // if( m_pos_start == -1 ) // m_pos_start = 0; // } // // if( start < m_pos_end ) { // m_pos_end = mEditText.getText().toString().indexOf( '\n', start + count ); // if( m_pos_end == -1 ) // m_pos_end = mEditText.getText().length(); // } mFlagEntryChanged = true mEntry._text = mEditText.text.toString() } reparse() } }) mEditText.setOnEditorActionListener { v: TextView, _: Int, _: KeyEvent? -> if(mFlagEditorActionInProgress) { mFlagEditorActionInProgress = false return@setOnEditorActionListener false } val iterEnd = v.selectionStart var iterStart = v.text.toString().lastIndexOf('\n', iterEnd - 1) if(iterStart < 0 || iterStart == v.text.length - 1) return@setOnEditorActionListener false iterStart++ // get rid of the new line char val offsetStart = iterStart // save for future if(v.text[iterStart] == '\t') { val text = StringBuilder("\n\t") var value = 0 var charLf = '*' iterStart++ // first tab is already handled, so skip it while(iterStart != iterEnd) { when(v.text[iterStart]) { '•' -> { if(charLf != '*') return@setOnEditorActionListener false charLf = ' ' text.append("• ") } '[' -> { if(charLf != '*') return@setOnEditorActionListener false charLf = 'c' } '~', '+', 'x', 'X' -> { if(charLf != 'c') return@setOnEditorActionListener false charLf = ']' } ']' -> { if(charLf != ']') return@setOnEditorActionListener false charLf = ' ' text.append("[ ] ") } '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> { if(charLf != '*' && charLf != '1') return@setOnEditorActionListener false charLf = '1' value *= 10 value += v.text[iterStart] - '0' } '-' -> { if(charLf == '*') { text.append("- ") break } if(charLf != '1') return@setOnEditorActionListener false charLf = ' ' text.append(++value) .append(v.text[iterStart]) .append(' ') } '.', ')' -> { if(charLf != '1') return@setOnEditorActionListener false charLf = ' ' text.append(++value) .append(v.text[iterStart]) .append(' ') } '\t' -> { if(charLf != '*') return@setOnEditorActionListener false text.append('\t') } ' ' -> { if(charLf == 'c') { break } else if(charLf != ' ') return@setOnEditorActionListener false // remove the last bullet if no text follows it: if(iterStart == iterEnd - 1) { iterStart = offsetStart mFlagEditorActionInProgress = true mEditText.text.delete(iterStart, iterEnd) mEditText.text.insert(iterStart, "\n") } else { mFlagEditorActionInProgress = true mEditText.text.insert(iterEnd, text) iterStart = iterEnd + text.length if(value > 0) { iterStart++ while(incrementNumberedLine( iterStart, value++, v).also { iterStart = it } > 0) { iterStart++ } } } return@setOnEditorActionListener true } else -> return@setOnEditorActionListener false } ++iterStart } } false } // mEditText.customSelectionActionModeCallback = object : ActionMode.Callback { // override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { // return true // } // // override fun onDestroyActionMode(mode: ActionMode) {} // override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { // menu.add(Menu.NONE, R.id.visit_link, Menu.FIRST, R.string.go) // return true // } // // override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { // if(item.itemId == R.id.visit_link) { // val buffer = mEditText.editableText // val link = buffer.getSpans(mEditText.selectionStart, // mEditText.selectionEnd, // ClickableSpan::class.java) // if(link.isNotEmpty()) // link[0].onClick(mEditText) // else // Log.i(Lifeograph.TAG, "No link in the selection") // return true // } // return false // } // } val mButtonBold = view.findViewById<Button>(R.id.buttonBold) mButtonBold.setOnClickListener { toggleFormat("*") } val mButtonItalic = view.findViewById<Button>(R.id.buttonItalic) mButtonItalic.setOnClickListener { toggleFormat("_") } val mButtonStrikethrough = view.findViewById<Button>(R.id.buttonStrikethrough) val spanStringS = SpannableString("S") spanStringS.setSpan(StrikethroughSpan(), 0, 1, 0) mButtonStrikethrough.text = spanStringS mButtonStrikethrough.setOnClickListener { toggleFormat("=") } mButtonHighlight = view.findViewById(R.id.buttonHighlight) mButtonHighlight.setOnClickListener { toggleFormat("#") } val mButtonIgnore = view.findViewById<Button>(R.id.button_ignore) mButtonIgnore.setOnClickListener { toggleIgnoreParagraph() } val mButtonComment = view.findViewById<Button>(R.id.button_comment) mButtonComment.setOnClickListener { addComment() } val mButtonList = view.findViewById<Button>(R.id.button_list) mButtonList.setOnClickListener { showStatusPickerDlg() } if(mEntry._size > 0) { requireActivity().window.setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) } show(savedInstanceState == null) } /*@Override protected void onPause() { super.onPause(); Log.d( Lifeograph.TAG, "ActivityEntry.onPause()" ); }*/ override fun onStop() { super.onStop() Log.d(Lifeograph.TAG, "ActivityEntry.onStop()") if(mFlagDismissOnExit) Diary.d.dismiss_entry(mEntry, false) else sync() Diary.d.writeLock() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) var item = menu.findItem(R.id.search_text) val searchView = item.actionView as SearchView item.setOnActionExpandListener(object : MenuItem.OnActionExpandListener { override fun onMenuItemActionExpand(menuItem: MenuItem): Boolean { searchView.setQuery(Diary.d._search_text, false) return true } override fun onMenuItemActionCollapse(menuItem: MenuItem): Boolean { return true } }) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(s: String): Boolean { return true } override fun onQueryTextChange(s: String): Boolean { if(mFlagSearchIsOpen) { Diary.d.set_search_text(s.toLowerCase(Locale.ROOT), false) reparse() } return true } }) searchView.setOnQueryTextFocusChangeListener { _: View?, b: Boolean -> mFlagSearchIsOpen = b } item = menu.findItem(R.id.change_todo_status) val toDoAction = MenuItemCompat.getActionProvider(item) as ToDoAction toDoAction.mObject = this } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId) { R.id.enable_edit -> { Lifeograph.enableEditing(this) return true } R.id.home -> { //NavUtils.navigateUpFromSameTask( this ); //finish(); return true } R.id.toggle_favorite -> { toggleFavorite() return true } R.id.change_todo_status -> { return false } R.id.set_theme -> { showThemePickerDlg() return true } R.id.edit_date -> { DialogInquireText(requireContext(), R.string.edit_date, mEntry._date.format_string(), R.string.apply, this).show() return true } R.id.dismiss -> { dismiss() return true } } return super.onOptionsItemSelected(item) } override fun updateMenuVisibilities() { super.updateMenuVisibilities() val flagWritable = Diary.d.is_in_edit_mode mMenu.findItem(R.id.enable_edit).isVisible = !flagWritable && Diary.d.can_enter_edit_mode() mMenu.findItem(R.id.change_todo_status).isVisible = flagWritable mMenu.findItem(R.id.toggle_favorite).isVisible = flagWritable mMenu.findItem(R.id.edit_date).isVisible = flagWritable mMenu.findItem(R.id.set_theme).isVisible = flagWritable mMenu.findItem(R.id.dismiss).isVisible = flagWritable } // DiaryEditor interface methods override fun enableEditing() { super.enableEditing() mEditText.setRawInputType(InputType.TYPE_CLASS_TEXT) mEditText.isFocusable = true // force soft keyboard to be shown: // if(mEditText.requestFocus()) { // val imm = requireContext().getSystemService( // Context.INPUT_METHOD_SERVICE) as InputMethodManager // imm.showSoftInput(mEditText, InputMethodManager.SHOW_IMPLICIT) // } requireActivity().findViewById<View>(R.id.toolbar_text_edit).visibility = View.VISIBLE reparse() } override fun handleBack(): Boolean { mBrowsingHistory.removeLast() if(mBrowsingHistory.isEmpty()) { return false } else { val entry = Diary.d.get_entry_by_id(mBrowsingHistory.last()) if(entry != null) { mEntry = entry show(true) } } return true } private fun updateIcon() { /*if( m_ptr2entry.is_favored() ) { Bitmap bmp = BitmapFactory.decodeResource( getResources(), m_ptr2entry.get_icon() ) .copy( Bitmap.Config.ARGB_8888, true ); // make the bitmap mutable Canvas canvas = new Canvas( bmp ); Bitmap bmp2 = BitmapFactory.decodeResource( getResources(), R.drawable.ic_action_favorite ); Rect rectDest = new Rect( bmp.getWidth()/2, bmp.getHeight()/2, bmp.getWidth()-1, bmp.getHeight()-1 ); canvas.drawBitmap( bmp2, null, rectDest, null ); BitmapDrawable bd = new BitmapDrawable( bmp ); bd.setTargetDensity( getResources().getDisplayMetrics().densityDpi ); mActionBar.setIcon( bd ); } else mActionBar.setIcon( m_ptr2entry.get_icon() );*/ if(isMenuInitialized) { mMenu.findItem(R.id.toggle_favorite).setIcon( if(mEntry.is_favored) R.drawable.ic_favorite_active else R.drawable.ic_favorite_inactive) mMenu.findItem(R.id.change_todo_status).setIcon( when(mEntry._todo_status_effective) { Entry.ES_TODO -> R.drawable.ic_todo_open_inactive Entry.ES_PROGRESSED -> R.drawable.ic_todo_progressed_inactive Entry.ES_DONE -> R.drawable.ic_todo_done_inactive Entry.ES_CANCELED -> R.drawable.ic_todo_canceled_inactive else -> R.drawable.ic_todo_auto_inactive } ) } } private fun updateTheme() { mParser.mP2Theme = mEntry._theme mEditText.setBackgroundColor(mParser.mP2Theme.color_base) mEditText.setTextColor(mParser.mP2Theme.color_text) mButtonHighlight.setTextColor(mParser.mP2Theme.color_text) val spanStringH = SpannableString("H") spanStringH.setSpan(BackgroundColorSpan(mParser.mP2Theme.color_highlight), 0, 1, 0) mButtonHighlight.text = spanStringH } private fun sync() { if(mFlagEntryChanged) { mEntry.m_date_edited = (System.currentTimeMillis() / 1000L) mEntry._text = mEditText.text.toString() mFlagEntryChanged = false } } fun show(flagParse: Boolean) { mFlagDismissOnExit = false // THEME updateTheme() // SETTING TEXT // mFlagSetTextOperation = true; if(flagParse) mEditText.setText(mEntry._text) // mFlagSetTextOperation = false; // if( flagParse ) // parse(); Lifeograph.getActionBar().subtitle = mEntry._title_str updateIcon() //invalidateOptionsMenu(); // may be redundant here // BROWSING HISTORY if(mBrowsingHistory.isEmpty() || mEntry.m_id != mBrowsingHistory.last()) // not going back mBrowsingHistory.add(mEntry.m_id) } private fun toggleFavorite() { mEntry.toggle_favored() updateIcon() } private fun dismiss() { Lifeograph.showConfirmationPrompt( requireContext(), R.string.entry_dismiss_confirm, R.string.dismiss ) { _: DialogInterface?, _: Int -> mFlagDismissOnExit = true } } fun showStatusPickerDlg() { DialogPicker(requireContext(), object: DialogPicker.Listener{ override fun onItemClick(item: RViewAdapterBasic.Item) { setListItemMark( item.mId[0]) } override fun populateItems(list: RVBasicList) { list.clear() list.add(RViewAdapterBasic.Item(Lifeograph.getStr(R.string.bullet), "*", R.drawable.ic_bullet)) list.add(RViewAdapterBasic.Item(Lifeograph.getStr(R.string.todo_open), " ", R.drawable.ic_todo_open)) list.add(RViewAdapterBasic.Item(Lifeograph.getStr(R.string.todo_progressed), "~", R.drawable.ic_todo_progressed)) list.add(RViewAdapterBasic.Item(Lifeograph.getStr(R.string.todo_done), "+", R.drawable.ic_todo_done)) list.add(RViewAdapterBasic.Item(Lifeograph.getStr(R.string.todo_canceled), "x", R.drawable.ic_todo_canceled)) } }).show() } private fun showThemePickerDlg() { DialogPicker(requireContext(), object: DialogPicker.Listener{ override fun onItemClick(item: RViewAdapterBasic.Item) { val theme = Diary.d.get_theme(item.mId) mEntry._theme = theme updateTheme() reparse() } override fun populateItems(list: RVBasicList) { list.clear() for(theme in Diary.d.m_themes.values) list.add(RViewAdapterBasic.Item(theme.m_name, theme.m_name, R.drawable.ic_theme)) } }).show() } override fun setTodoStatus(s: Int) { mEntry._todo_status = s mEntry.m_date_status = (System.currentTimeMillis() / 1000L) updateIcon() } // InquireListener methods override fun onInquireAction(id: Int, text: String) { if(id == R.string.edit_date) { val date = Date(text) if(date.m_date != Date.NOT_SET) { if(!date.is_ordinal) date._order_3rd = 1 try { Diary.d.set_entry_date(mEntry, date) } catch(e: Exception) { e.printStackTrace() } Lifeograph.getActionBar().subtitle = mEntry._info_str } } } override fun onInquireTextChanged(id: Int, text: String): Boolean { if(id == R.string.edit_date) { val date = Date.parse_string(text) return date > 0 && date != mEntry.m_date.m_date } return true } private fun incrementNumberedLine(pos_bgn: Int, expected_value: Int, v: TextView): Int { var pos = pos_bgn if(pos >= v.text.length) return -1 var iterEnd = v.text.toString().indexOf('\n', pos) if(iterEnd == -1) iterEnd = v.text.length - 1 val text = StringBuilder() var value = 0 var charLf = 't' while(pos != iterEnd) { when(v.text[pos]) { '\t' -> { if(charLf != 't' && charLf != '1') return -1 charLf = '1' text.append('\t') } '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> { if(charLf != '1' && charLf != '-') return -1 charLf = '-' value *= 10 value += v.text[pos] - '0' } '-', '.', ')' -> { if(charLf != '-' || value != expected_value) return -1 charLf = ' ' value++ text.append(value).append(v.text[pos]).append(' ') } ' ' -> { if(charLf != ' ') return -1 mFlagEditorActionInProgress = true mEditText.text.delete(pos_bgn, pos + 1) mEditText.text.insert(pos_bgn, text) return iterEnd + text.length - (pos - pos_bgn + 1) } else -> return -1 } ++pos } return -1 } // FORMATTING BUTTONS ========================================================================== private fun calculateMultiParaBounds(bounds: IntArray): Boolean { val str = mEditText.text.toString() if(mEditText.hasSelection()) { bounds[0] = mEditText.selectionStart bounds[1] = mEditText.selectionEnd } else { bounds[1] = mEditText.selectionStart bounds[0] = bounds[1] if(bounds[0] <= 0) return true if(str[bounds[0] - 1] == '\n') { if(bounds[0] == str.length) return false if(str[bounds[0]] == '\n') return false } } bounds[0]-- if(str.lastIndexOf('\n', bounds[0]) == -1) { if(str.indexOf('\n', bounds[0]) == -1) return true else bounds[0] = str.indexOf('\n', bounds[0]) + 1 } else bounds[0] = str.lastIndexOf('\n', bounds[0]) + 1 if(str.indexOf('\n', bounds[1]) == -1) bounds[1] = str.length - 1 else bounds[1] = str.indexOf('\n', bounds[1]) - 1 return bounds[0] > bounds[1] } private fun toggleFormat(markup: String) { var pStart: Int var pEnd: Int if(mEditText.hasSelection()) { var start = -2 var end = -1 var properlySeparated = false pStart = mEditText.selectionStart pEnd = mEditText.selectionEnd - 1 val pFirstNl = mEditText.text.toString().indexOf('\n') when { pFirstNl == -1 -> // there is only heading return pEnd <= pFirstNl -> return pStart > pFirstNl -> pStart-- // also evaluate the previous character else -> { // p_start <= p_first_nl pStart = pFirstNl + 1 properlySeparated = true start = -1 } } while(true) { val theSpan = hasSpan(pStart, markup[0]) if(theSpan.type == '*' || theSpan.type == '_' || theSpan.type == '#' || theSpan.type == '=') return when(mEditText.text[pStart]) { '\n' -> { if(start >= 0) { if(properlySeparated) { mEditText.text.insert(start, markup) end += 2 pStart += 2 pEnd += 2 } else { mEditText.text.insert(start, " $markup") end += 3 pStart += 3 pEnd += 3 } mEditText.text.insert(end, markup) properlySeparated = true start = -1 break } if(start == -2) { properlySeparated = true start = -1 } } ' ', '\t' -> if(start == -2) { properlySeparated = true start = -1 } else -> { if(start == -2) start = -1 else if(start == -1) start = pStart end = pStart } } if(pStart == pEnd) break pStart++ } // add markup chars to the beginning and end: if(start >= 0) { end += if(properlySeparated) { mEditText.text.insert(start, markup) 2 } else { mEditText.text.insert(start, " $markup") 3 } mEditText.text.insert(end, markup) // TODO place_cursor( get_iter_at_offset( end ) ); } } else { // no selection case pEnd = mEditText.selectionStart pStart = pEnd if(isSpace(pStart) || pStart == mEditText.length() - 1) { if(startsLine(pStart)) return pStart-- if(hasSpan(pStart, 'm').type == 'm') pStart-- } else if(hasSpan(pStart, 'm').type == 'm') { if(startsLine(pStart)) return pStart-- if(isSpace(pStart)) pStart += 2 } val theSpan = hasSpan(pStart, markup[0]) // if already has the markup remove it if(theSpan.type == markup[0]) { pStart = mEditText.text.getSpanStart(theSpan) pEnd = mEditText.text.getSpanEnd(theSpan) mEditText.text.delete(pStart - 1, pStart) mEditText.text.delete(pEnd - 1, pEnd) } else if(theSpan.type == ' ') { // find word boundaries: while(pStart > 0) { val c = mEditText.text[pStart] if(c == '\n' || c == ' ' || c == '\t') { pStart++ break } pStart-- } mEditText.text.insert(pStart, markup) while(pEnd < mEditText.text.length) { val c = mEditText.text[pEnd] if(c == '\n' || c == ' ' || c == '\t') break pEnd++ } mEditText.text.insert(pEnd, markup) // TODO (if necessary) place_cursor( offset ); } } } private fun setListItemMark(target_item_type: Char) { val bounds = intArrayOf(0, 0) if(calculateMultiParaBounds(bounds)) return var pos = bounds[0] if(bounds[0] == bounds[1]) { // empty line when(target_item_type) { '*' -> mEditText.text.insert(pos, "\t• ") ' ' -> mEditText.text.insert(pos, "\t[ ] ") '~' -> mEditText.text.insert(pos, "\t[~] ") '+' -> mEditText.text.insert(pos, "\t[+] ") 'x' -> mEditText.text.insert(pos, "\t[x] ") '1' -> mEditText.text.insert(pos, "\t1- ") } return } var posEnd = bounds[1] var posEraseBegin = pos var itemType = 0.toChar() // none var charLf = 't' // tab var value = 1 // for numeric lists mainloop@ while(pos <= posEnd) { when(mEditText.text.toString()[pos]) { '\t' -> if(charLf == 't' || charLf == '[') { charLf = '[' // opening bracket posEraseBegin = pos } else charLf = 'n' '•', '-' -> { charLf = if(charLf == '[') 's' else 'n' itemType = if(charLf == 's') '*' else 0.toChar() } '[' -> charLf = (if(charLf == '[') 'c' else 'n') ' ' -> { if(charLf == 's') { // separator space if(itemType != target_item_type) { mEditText.text.delete(posEraseBegin, pos + 1) val diff = pos + 1 - posEraseBegin pos -= diff posEnd -= diff charLf = 'a' continue@mainloop } else { charLf ='n' } } else { charLf = if(charLf == 'c') ']' else 'n' itemType = mEditText.text.toString()[pos] // same as below. unfortunately no fallthrough in Kotlin } } '~', '+', 'x', 'X' -> { charLf = if(charLf == 'c') ']' else 'n' itemType = mEditText.text.toString()[pos] } ']' -> charLf = (if(charLf == ']') 's' else 'n') '\n' -> { itemType = 0.toChar() charLf = 't' // tab } else -> { if(charLf == 'a' || charLf == 't' || charLf == '[') { when(target_item_type) { '*' -> { mEditText.text.insert(pos, "\t• ") pos += 3 posEnd += 3 } ' ' -> { mEditText.text.insert(pos, "\t[ ] ") pos += 5 posEnd += 5 } '~' -> { mEditText.text.insert(pos, "\t[~] ") pos += 5 posEnd += 5 } '+' -> { mEditText.text.insert(pos, "\t[+] ") pos += 5 posEnd += 5 } 'x' -> { mEditText.text.insert(pos, "\t[x] ") pos += 5 posEnd += 5 } '1' -> { mEditText.text.insert(pos, "\t$value- ") value++ } } } charLf = 'n' } } pos++ } } private fun addComment() { val pStart: Int = mEditText.selectionStart if(pStart>=0) return if(mEditText.hasSelection()) { val pEnd: Int = mEditText.selectionEnd - 1 mEditText.text.insert(pStart, "[[") mEditText.text.insert(pEnd + 2, "]]") } else { // no selection case mEditText.text.insert(pStart, "[[]]") mEditText.setSelection(pStart + 2) } } private fun toggleIgnoreParagraph() { val bounds = intArrayOf(0, 0) if(calculateMultiParaBounds(bounds)) return if(bounds[0] == bounds[1]) { // empty line mEditText.text.insert(bounds[0], ".\t") return } var pos = bounds[0] var posEnd = bounds[1] var posEraseBegin = pos var charLf = '.' while(pos <= posEnd) { when(mEditText.text.toString()[pos]) { '.' -> if(charLf == '.') { posEraseBegin = pos charLf = 't' // tab } else charLf = 'n' '\n' -> charLf = '.' '\t' -> { if(charLf == 't') { mEditText.text.delete(posEraseBegin, pos + 1) val diff = pos + 1 - posEraseBegin pos -= diff posEnd -= diff } if(charLf == '.') { mEditText.text.insert(pos, ".\t") pos += 2 posEnd += 2 } charLf = 'n' } 0.toChar() -> { if(charLf == '.') { mEditText.text.insert(pos, ".\t") pos += 2 posEnd += 2 } charLf = 'n' } else -> { if(charLf == '.') { mEditText.text.insert(pos, ".\t") pos += 2 posEnd += 2 } charLf = 'n' } } pos++ } } // PARSING ===================================================================================== fun reparse() { mParser.parse(0, mEditText.text.length) } private interface AdvancedSpan { val type: Char } internal class ParserEditText(private val mHost: FragmentEntry) : ParserText() { lateinit var mP2Theme: Theme private val sMarkupScale = 0.7f private val mSpans = Vector<Any?>() override fun get_char_at(i: Int): Char { return mHost.mEditText.text[i] } private fun getSlice(bgn: Int, end: Int): String { return mHost.mEditText.text.subSequence(bgn, end).toString() } private fun addSpan(span: Any?, start: Int, end: Int, styles: Int) { mSpans.add(span) mHost.mEditText.text.setSpan(span, start, end, styles) } override fun reset(bgn: Int, end: Int){ super.reset(bgn, end) // COMPLETELY CLEAR THE PARSING REGION // TODO: only remove spans within the parsing boundaries... // mEditText.getText().clearSpans(); <-- problematic!! for(span in mSpans) mHost.mEditText.text.removeSpan(span) mSpans.clear() // Following must come after reset as m_pos_para_bgn is reset there // when bgn != 0, 1 added to the m_pos_para_bgn to skip the \n at the beginning m_p2para_cur = mEntry.get_paragraph( if( m_pos_para_bgn > 0 ) m_pos_para_bgn + 1 else 0 ) mEntry.clear_paragraph_data( m_pos_para_bgn, end ) } public override fun parse(bgn: Int, end: Int) { mHost.updateTodoStatus() super.parse(bgn, end) } public override fun process_paragraph() { if(m_p2para_cur == null) return when(m_p2para_cur.m_justification) { Paragraph.JT_LEFT -> addSpan(AlignmentSpan.Standard(Layout.Alignment.ALIGN_NORMAL), m_pos_para_bgn, m_pos_cur, 0) Paragraph.JT_CENTER -> addSpan(AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), m_pos_para_bgn, m_pos_cur, 0) Paragraph.JT_RIGHT -> addSpan(AlignmentSpan.Standard(Layout.Alignment.ALIGN_OPPOSITE), m_pos_para_bgn, m_pos_cur, 0) } m_p2para_cur = m_p2para_cur._next } // SPANS =================================================================================== class SpanOther : AdvancedSpan { override val type: Char get() = 'O' } class SpanNull : AdvancedSpan { override val type: Char get() = ' ' } @SuppressLint("ParcelCreator") private class SpanBold : StyleSpan(Typeface.BOLD), AdvancedSpan { override val type: Char get() = '*' } @SuppressLint("ParcelCreator") private class SpanItalic : StyleSpan(Typeface.ITALIC), AdvancedSpan { override val type: Char get() = '_' } @SuppressLint("ParcelCreator") private inner class SpanHighlight : BackgroundColorSpan(mP2Theme.color_highlight), AdvancedSpan { override val type: Char get() = '#' } @SuppressLint("ParcelCreator") private class SpanStrikethrough : StrikethroughSpan(), AdvancedSpan { override val type: Char get() = '=' } @SuppressLint("ParcelCreator") private inner class SpanMarkup : ForegroundColorSpan(mP2Theme.m_color_mid), AdvancedSpan { override val type: Char get() = 'm' } private class LinkDate(private val mDate: Long) : ClickableSpan(), AdvancedSpan { override fun onClick(widget: View) { Log.d( Lifeograph.TAG, "Clicked on Date link") var entry = Diary.d.get_entry_by_date(mDate) if(entry == null) entry = Diary.d.create_entry(mDate, "") Lifeograph.showElem(entry!!) } override val type: Char get() = 'd' } private class LinkUri(private val mUri: String) : ClickableSpan(), AdvancedSpan { override fun onClick(widget: View) { Log.d( Lifeograph.TAG, "Clicked on Uri link") val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(mUri)) Lifeograph.mActivityMain.startActivity(browserIntent) } override val type: Char get() = 'u' } private class LinkID(private val mId: Int) : ClickableSpan(), AdvancedSpan { override fun onClick(widget: View) { Log.d( Lifeograph.TAG, "Clicked on ID link") val elem = Diary.d.get_element(mId) if(elem != null) { if(elem._type != DiaryElement.Type.ENTRY) Log.d(Lifeograph.TAG, "Target is not entry") else Lifeograph.showElem(elem) } } override val type: Char get() = 'i' } private class LinkCheck(val mHost: FragmentEntry) : ClickableSpan(), AdvancedSpan { override fun onClick(widget: View) { mHost.showStatusPickerDlg() } override val type: Char get() = 'c' } // APPLIERS ==================================================================================== public override fun apply_heading() { var end = 0 if(mHost.mEditText.text[0] != '\n') end = mHost.mEditText.text.toString().indexOf('\n') if(end == -1) end = mHost.mEditText.text.length addSpan(TextAppearanceSpan(mHost.requireContext(), R.style.headingSpan), 0, end, Spanned.SPAN_INTERMEDIATE) addSpan(ForegroundColorSpan(mEntry._theme.color_heading), 0, end, 0) if(!mHost.mFlagSetTextOperation) { mEntry.m_name = mHost.mEditText.text.toString().substring(0, end) // handle_entry_title_changed() will not be used here in Android } } public override fun apply_subheading() { val bgn = m_recipe_cur.m_pos_bgn var end = mHost.mEditText.text.toString().indexOf('\n', bgn) if(end == -1) end = mHost.mEditText.text.length addSpan(TextAppearanceSpan(mHost.requireContext(), R.style.subheadingSpan), bgn, end, Spanned.SPAN_INTERMEDIATE) addSpan(ForegroundColorSpan(mEntry._theme.color_subheading), bgn, end, 0) if(m_p2para_cur != null) m_p2para_cur.m_heading_level = 2 } public override fun apply_bold() { applyMarkup(SpanBold()) } public override fun apply_italic() { applyMarkup(SpanItalic()) } public override fun apply_strikethrough() { applyMarkup(SpanStrikethrough()) } public override fun apply_highlight() { applyMarkup(SpanHighlight()) } private fun applyMarkup(span: Any) { val bgn = m_recipe_cur.m_pos_bgn val mid = bgn + 1 val cur = m_pos_cur addSpan(RelativeSizeSpan(sMarkupScale), bgn, mid, Spanned.SPAN_INTERMEDIATE) addSpan(SpanMarkup(), bgn, mid, 0) addSpan(span, mid, cur, 0) addSpan(RelativeSizeSpan(sMarkupScale), cur, cur + 1, Spanned.SPAN_INTERMEDIATE) addSpan(SpanMarkup(), cur, cur + 1, 0) } public override fun apply_comment() { addSpan(TextAppearanceSpan(mHost.requireContext(), R.style.commentSpan), m_recipe_cur.m_pos_bgn, m_pos_cur + 1, Spanned.SPAN_INTERMEDIATE) addSpan(ForegroundColorSpan(mP2Theme.m_color_mid), m_recipe_cur.m_pos_bgn, m_pos_cur + 1, Spanned.SPAN_INTERMEDIATE) addSpan(SuperscriptSpan(), m_recipe_cur.m_pos_bgn, m_pos_cur + 1, 0) } public override fun apply_ignore() { var end = mHost.mEditText.text.toString().indexOf('\n', m_recipe_cur.m_pos_bgn) if(end < 0) end = mHost.mEditText.text.length addSpan(ForegroundColorSpan(mP2Theme.m_color_mid), m_recipe_cur.m_pos_bgn, end, 0) } private fun applyHiddenLinkTags(end: Int, spanLink: Any?) { addSpan(RelativeSizeSpan(sMarkupScale), m_recipe_cur.m_pos_bgn, m_recipe_cur.m_pos_mid, Spanned.SPAN_INTERMEDIATE) addSpan(SpanMarkup(), m_recipe_cur.m_pos_bgn, m_recipe_cur.m_pos_mid, 0) addSpan(RelativeSizeSpan(sMarkupScale), m_pos_cur, end, Spanned.SPAN_INTERMEDIATE) addSpan(SpanMarkup(), m_pos_cur, end, 0) addSpan(spanLink, m_recipe_cur.m_pos_mid + 1, m_pos_cur, 0) } public override fun apply_link_hidden() { //remove_tag( m_tag_misspelled, it_uri_bgn, it_tab ); var span: Any? = null when(m_recipe_cur.m_id) { RID_URI -> span = LinkUri(getSlice(m_recipe_cur.m_pos_bgn + 1, m_recipe_cur.m_pos_mid)) RID_ID -> { val element = Diary.d.get_element(m_recipe_cur.m_int_value) span = if(element != null && element._type == DiaryElement.Type.ENTRY) LinkID(m_recipe_cur.m_int_value) else // indicate dead links ForegroundColorSpan(Color.RED) } } applyHiddenLinkTags(m_pos_cur + 1, span) } public override fun apply_link() { //remove_tag( m_tag_misspelled, it_bgn, it_cur ); when(m_recipe_cur.m_id) { RID_DATE -> applyDate() RID_LINK_AT -> { val uri = "mailto:" + getSlice(m_recipe_cur.m_pos_bgn, m_pos_cur) addSpan(LinkUri(uri), m_recipe_cur.m_pos_bgn, m_pos_cur, 0) } RID_URI -> { val uri = getSlice(m_recipe_cur.m_pos_bgn, m_pos_cur) addSpan(LinkUri(uri), m_recipe_cur.m_pos_bgn, m_pos_cur, 0) } RID_ID -> { Log.d(Lifeograph.TAG, "********** m_int_value: " + m_recipe_cur.m_int_value) val element = Diary.d.get_element(m_recipe_cur.m_int_value) val span: Any span = if(element != null && element._type == DiaryElement.Type.ENTRY) LinkID(element.m_id) else // indicate dead links ForegroundColorSpan(Color.RED) addSpan(span, m_recipe_cur.m_pos_bgn, m_pos_cur, 0) } } } private fun applyDate() { // DO NOT FORGET TO COPY UPDATES HERE TO TextbufferDiarySearch::apply_date() addSpan(LinkDate(m_date_last.m_date), m_recipe_cur.m_pos_bgn, m_pos_cur + 1, 0) if(m_p2para_cur != null) m_p2para_cur.m_date = m_date_last.m_date } private fun applyCheck(tag_box: Any, tag: Any?) { val posBgn = m_pos_cur - 3 val posBox = m_pos_cur var posEnd = mHost.mEditText.text.toString().indexOf('\n', m_pos_cur) if(posEnd == -1) posEnd = mHost.mEditText.text.length if(Diary.d.is_in_edit_mode) addSpan(LinkCheck(mHost), posBgn, posBox, Spanned.SPAN_INTERMEDIATE) addSpan(tag_box, posBgn, posBox, Spanned.SPAN_INTERMEDIATE) addSpan(TypefaceSpan("monospace"), posBgn, posBox, 0) if(tag != null) addSpan(tag, posBox + 1, posEnd, 0) // ++ to skip separating space char } public override fun apply_check_unf() { applyCheck(ForegroundColorSpan(Theme.s_color_todo), SpanBold()) } public override fun apply_check_prg() { applyCheck(ForegroundColorSpan(Theme.s_color_progressed), null) } public override fun apply_check_fin() { applyCheck(ForegroundColorSpan(Theme.s_color_done), BackgroundColorSpan(Theme.s_color_done)) } public override fun apply_check_ccl() { applyCheck(ForegroundColorSpan(Theme.s_color_canceled), SpanStrikethrough()) } public override fun apply_match() { addSpan(BackgroundColorSpan(mP2Theme.m_color_match_bg), m_pos_search, m_pos_cur + 1, Spanned.SPAN_INTERMEDIATE) addSpan(ForegroundColorSpan(mP2Theme.color_base), m_pos_search, m_pos_cur + 1, 0) } public override fun apply_inline_tag() { // m_pos_mid is used to determine if a value is assigned to the tag var pEnd = if(m_recipe_cur.m_pos_mid > 0) m_recipe_cur.m_pos_mid else m_pos_cur val pNameBgn = m_recipe_cur.m_pos_bgn + 1 val pNameEnd = pEnd - 1 val tagName = getSlice(pNameBgn, pNameEnd) val entries = Diary.d.get_entries_by_name(tagName) if(entries == null || entries.isEmpty()) addSpan(ForegroundColorSpan(Color.RED), m_recipe_cur.m_pos_bgn, pEnd, 0) else { if(m_recipe_cur.m_pos_mid == 0) { addSpan(SpanMarkup(), m_recipe_cur.m_pos_bgn, pNameBgn, 0) addSpan(BackgroundColorSpan(mP2Theme.m_color_inline_tag), m_recipe_cur.m_pos_bgn, pEnd, 0) addSpan(LinkID(entries[0]._id), pNameBgn, pNameEnd, 0) addSpan(SpanMarkup(), pNameEnd, pEnd, 0) if(m_p2para_cur != null) m_p2para_cur.set_tag(tagName, 1.0) } else { val pBgn = m_recipe_cur.m_pos_mid + 1 pEnd = m_pos_extra_2 + 1 addSpan(BackgroundColorSpan(mP2Theme.m_color_inline_tag), pBgn, pEnd, 0) if(m_p2para_cur == null) return if(m_pos_extra_1 > m_recipe_cur.m_pos_bgn) { // has planned value val vReal = Lifeograph.getDouble(getSlice(pBgn, m_pos_extra_1)) val vPlan = Lifeograph.getDouble(getSlice(m_pos_extra_1 + 1, pEnd)) m_p2para_cur.set_tag(tagName, vReal, vPlan) } else m_p2para_cur.set_tag(tagName, Lifeograph.getDouble(getSlice(pBgn, pEnd))) } } } } // PARSING HELPER FUNCTIONS ==================================================================== private fun isSpace(offset: Int): Boolean { if(offset < 0 || offset >= mEditText.text.length) return false return when(mEditText.text[offset]) { '\n', '\t', ' ' -> true else -> false } } private fun startsLine(offset: Int): Boolean { if(offset < 0 || offset >= mEditText.text.length) return false return offset == 0 || mEditText.text[offset - 1] == '\n' } private fun hasSpan(offset: Int, type: Char): AdvancedSpan { val spans = mEditText.text.getSpans(offset, offset, Any::class.java) var hasNoOtherSpan = true for(span in spans) { if(span is AdvancedSpan) { hasNoOtherSpan = if(span.type == type) { return span } else false } } return if(hasNoOtherSpan) SpanNull() else SpanOther() } private fun updateTodoStatus() { if(mEntry._status and DiaryElement.ES_NOT_TODO != 0) { Entry.calculate_todo_status(mEntry._text) updateIcon() // Not relevant now: panel_diary->handle_elem_changed( m_ptr2entry ); } } }
gpl-3.0
674ec8933d8b70d45c508cce2af37065
39.926866
123
0.463167
4.972978
false
false
false
false
grote/Liberario
app/src/main/java/de/grobox/transportr/trips/detail/StopViewHolder.kt
1
2869
/* * Transportr * * Copyright (c) 2013 - 2018 Torsten Grote * * This program is Free Software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.grobox.transportr.trips.detail import android.view.View import android.view.View.* import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import de.grobox.transportr.trips.BaseViewHolder import de.grobox.transportr.utils.DateUtils.getTime import de.grobox.transportr.utils.TransportrUtils.getLocationName import de.schildbach.pte.dto.Stop import kotlinx.android.synthetic.main.list_item_stop.view.* import java.util.Date internal class StopViewHolder(v: View, private val listener : LegClickListener) : BaseViewHolder(v) { private val circle: ImageView = v.circle private val stopLocation: TextView = v.stopLocation private val stopButton: ImageButton = v.stopButton fun bind(stop: Stop, color: Int) { if (stop.arrivalTime != null) { setArrivalTimes(fromTime, fromDelay, stop) fromTime.visibility = VISIBLE } else { fromDelay.visibility = GONE if (stop.departureTime == null) { // insert dummy time field for stops without times set, so that stop circles align fromTime.text = getTime(context, Date()) fromTime.visibility = INVISIBLE } else { fromTime.visibility = GONE } } if (stop.departureTime != null) { if (stop.departureTime == stop.arrivalTime) { toTime.visibility = GONE toDelay.visibility = GONE } else { setDepartureTimes(toTime, toDelay, stop) toTime.visibility = VISIBLE } } else { toTime.visibility = GONE toDelay.visibility = GONE } circle.setColorFilter(color) stopLocation.text = getLocationName(stop.location) stopLocation.setOnClickListener { listener.onLocationClick(stop.location) } stopLocation.addPlatform(stop.arrivalPosition) // show popup on button click stopButton.setOnClickListener { LegPopupMenu(stopButton.context, stopButton, stop).show() } } }
gpl-3.0
2c22e3159ee660e27ecf4b385e225d45
34.8625
101
0.66504
4.503925
false
false
false
false
dmitryustimov/weather-kotlin
app/src/main/java/ru/ustimov/weather/ui/forecast/ForecastFragment.kt
1
7545
package ru.ustimov.weather.ui.forecast import android.Manifest import android.arch.lifecycle.Lifecycle import android.arch.lifecycle.LifecycleOwner import android.arch.lifecycle.OnLifecycleEvent import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.Settings import android.support.design.widget.Snackbar import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.arellomobile.mvp.MvpAppCompatFragment import com.arellomobile.mvp.presenter.InjectPresenter import com.arellomobile.mvp.presenter.ProvidePresenter import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationSettingsRequest import com.google.android.gms.location.LocationSettingsStatusCodes import com.tbruyelle.rxpermissions2.RxPermissions import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.rxkotlin.subscribeBy import pl.charmas.android.reactivelocation2.ReactiveLocationProvider import ru.ustimov.weather.R import ru.ustimov.weather.appState import ru.ustimov.weather.content.data.City import ru.ustimov.weather.rx.RxIntent import ru.ustimov.weather.rx.RxLifecycleObserver import ru.ustimov.weather.util.println import java.util.concurrent.TimeUnit class ForecastFragment : MvpAppCompatFragment(), LifecycleOwner, LocationView { companion object Factory { private const val EXTRA_CITY_ID = "city_id" private const val UNKNOWN_CITY_ID = -1L private const val REQUEST_CODE_SETTINGS = 1000 private const val REQUEST_CODE_PLAY_SERVICES = 1001 fun create(): ForecastFragment { val fragment = ForecastFragment() fragment.arguments = Bundle() return fragment } fun create(city: City): ForecastFragment { val fragment = ForecastFragment() val args = Bundle() args.putLong(EXTRA_CITY_ID, city.id()) fragment.arguments = args return fragment } } @InjectPresenter lateinit var locationPresenter: LocationPresenter private lateinit var rxPermissions: RxPermissions private lateinit var locationLifecycleObserver: LocationLifecycleObserver @ProvidePresenter fun provideLocationPresenter(): LocationPresenter { val appState = context.appState() val cityId = getCityId() return if (cityId != UNKNOWN_CITY_ID) { CityLocationPresenter(appState, cityId) } else { GeoBasedLocationPresenter(appState) } } fun getCityId(): Long = arguments.getLong(EXTRA_CITY_ID, UNKNOWN_CITY_ID) override fun onAttach(context: Context) { super.onAttach(context) rxPermissions = RxPermissions(activity) locationLifecycleObserver = LocationLifecycleObserver() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_forecast, container, false) override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) } override fun requestAccessCoarseLocationPermission() { val appState = context.appState() rxPermissions.requestEach(Manifest.permission.ACCESS_COARSE_LOCATION) .observeOn(AndroidSchedulers.mainThread()) .doOnError({ it.println(appState.logger) }) .subscribe(locationPresenter::onAccessCoarseLocationPermissionResult) } override fun onAccessCoarseLocationGranted() { lifecycle.addObserver(locationLifecycleObserver) } override fun showAccessCoarseLocationRationale() { Snackbar.make(view!!, R.string.rationale_access_coarse_location, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.action_ok, { onAccessCoarseLocationRationaleActionClick() }) .show() } private fun onAccessCoarseLocationRationaleActionClick() { locationPresenter.setViewState(`LocationView$$State`()) requestAccessCoarseLocationPermission() } override fun showAccessCoarseLocationDenied() { Snackbar.make(view!!, R.string.rationale_access_coarse_location, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.action_open_settings, { onOpenApplicationDetailsClick() }) .show() } private fun onOpenApplicationDetailsClick() { locationPresenter.setViewState(`LocationView$$State`()) val appState = context.appState() val data = Uri.parse("package:" + context.packageName) val detailsIntent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).setData(data) val fallbackIntent = Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS) RxIntent.resolveActivity(context, detailsIntent) .onErrorResumeNext(RxIntent.resolveActivity(context, fallbackIntent)) .subscribeBy(onSuccess = { startActivityForResult(it, REQUEST_CODE_SETTINGS) }, onError = { it.println(appState.logger) }) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) = when (requestCode) { REQUEST_CODE_SETTINGS -> requestAccessCoarseLocationPermission() else -> super.onActivityResult(requestCode, resultCode, data) } override fun onLocationFound(city: City) { Toast.makeText(context, "$city", Toast.LENGTH_SHORT).show() } override fun onLocationNotFound() { Toast.makeText(context, "Location not found", Toast.LENGTH_SHORT).show() } override fun onDestroy() { super.onDestroy() lifecycle.removeObserver(locationLifecycleObserver) } inner class LocationLifecycleObserver : RxLifecycleObserver() { private val locationProvider = ReactiveLocationProvider(context.applicationContext) private val locationRequest = LocationRequest.create() .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY) .setMaxWaitTime(TimeUnit.SECONDS.toMillis(10L)) .setInterval(TimeUnit.MINUTES.toMillis(1L)) .setSmallestDisplacement(1000F) // http://stackoverflow.com/questions/29824408/google-play-services-locationservices-api-new-option-never0 private val locationSettingsRequest = LocationSettingsRequest.Builder() .addLocationRequest(locationRequest) .setAlwaysShow(true) .build() @OnLifecycleEvent(Lifecycle.Event.ON_START) fun start() { val appState = context.appState() locationProvider .checkLocationSettings(locationSettingsRequest) .doOnNext({ if (it.status.statusCode == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) { it.status.startResolutionForResult(activity, REQUEST_CODE_PLAY_SERVICES) } }) .flatMap({ locationProvider.getUpdatedLocation(locationRequest) }) .compose(bindUntilStop()) .observeOn(appState.schedulers.mainThread()) .subscribe({ locationPresenter.onLocationChanged(it) }, { it.println(appState.logger) }) } } }
apache-2.0
b49a6f4e251d8b8f7d9d30ac0c5afff2
38.925926
114
0.68827
5.178449
false
false
false
false
antoniolg/Kotlin-for-Android-Developers
app/src/main/java/com/antonioleiva/weatherapp/extensions/DatabaseExtensions.kt
1
799
package com.antonioleiva.weatherapp.extensions import android.database.sqlite.SQLiteDatabase import org.jetbrains.anko.db.MapRowParser import org.jetbrains.anko.db.SelectQueryBuilder fun <T : Any> SelectQueryBuilder.parseList(parser: (Map<String, Any?>) -> T): List<T> = parseList(object : MapRowParser<T> { override fun parseRow(columns: Map<String, Any?>): T = parser(columns) }) fun <T : Any> SelectQueryBuilder.parseOpt(parser: (Map<String, Any?>) -> T): T? = parseOpt(object : MapRowParser<T> { override fun parseRow(columns: Map<String, Any?>): T = parser(columns) }) fun SQLiteDatabase.clear(tableName: String) { execSQL("delete from $tableName") } fun SelectQueryBuilder.byId(id: Long) = whereSimple("_id = ?", id.toString())
apache-2.0
ab464c55c5b4c3441d549d1b942fe096
37.047619
87
0.685857
3.78673
false
false
false
false
facebook/fresco
imagepipeline/src/main/java/com/facebook/imagepipeline/cache/BitmapMemoryCacheKey.kt
2
1505
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.cache import android.net.Uri import com.facebook.cache.common.CacheKey import com.facebook.common.time.RealtimeSinceBootClock import com.facebook.common.util.HashCodeUtil import com.facebook.imagepipeline.common.ImageDecodeOptions import com.facebook.imagepipeline.common.ResizeOptions import com.facebook.imagepipeline.common.RotationOptions /** Cache key for BitmapMemoryCache */ data class BitmapMemoryCacheKey( val sourceString: String, val resizeOptions: ResizeOptions?, val rotationOptions: RotationOptions, val imageDecodeOptions: ImageDecodeOptions, val postprocessorCacheKey: CacheKey?, val postprocessorName: String?, ) : CacheKey { var callerContext: Any? = null private val hash: Int = HashCodeUtil.hashCode( sourceString.hashCode(), resizeOptions?.hashCode() ?: 0, rotationOptions.hashCode(), imageDecodeOptions, postprocessorCacheKey, postprocessorName) val inBitmapCacheSince: Long = RealtimeSinceBootClock.get().now() override fun hashCode(): Int = hash override fun containsUri(uri: Uri): Boolean { return uriString.contains(uri.toString()) } override fun getUriString(): String = sourceString override fun isResourceIdForDebugging() = false }
mit
679ab877c59e39f6e5cfddfc64ac661f
29.714286
67
0.746844
4.602446
false
false
false
false
davinkevin/Podcast-Server
backend/src/test/kotlin/com/github/davinkevin/podcastserver/service/storage/FileStorageServiceTest.kt
1
24886
package com.github.davinkevin.podcastserver.service.storage import com.github.davinkevin.podcastserver.cover.Cover import com.github.davinkevin.podcastserver.cover.DeleteCoverRequest import com.github.davinkevin.podcastserver.cover.DeleteCoverRequest.* import com.github.davinkevin.podcastserver.entity.Status import com.github.davinkevin.podcastserver.fileAsByteArray import com.github.davinkevin.podcastserver.item.DeleteItemRequest import com.github.davinkevin.podcastserver.item.Item import com.github.davinkevin.podcastserver.podcast.DeletePodcastRequest import com.github.davinkevin.podcastserver.podcast.Podcast import com.github.davinkevin.podcastserver.tag.Tag import com.github.tomakehurst.wiremock.client.WireMock.* import com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig import com.github.tomakehurst.wiremock.http.RequestMethod import com.github.tomakehurst.wiremock.junit5.WireMockExtension import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder.newRequestPattern import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.io.TempDir import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.ImportAutoConfiguration import org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration import org.springframework.context.annotation.Import import org.springframework.http.codec.multipart.FilePart import org.springframework.test.context.TestPropertySource import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.util.DigestUtils import org.springframework.web.reactive.function.client.WebClient import reactor.kotlin.core.publisher.toMono import reactor.test.StepVerifier import java.net.URI import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.time.OffsetDateTime import java.time.ZoneOffset import java.util.* import kotlin.io.path.writeText import kotlin.io.path.Path /** * Created by kevin on 2019-02-12 */ const val s3MockBackendPort = 1234 @Suppress("HttpUrlsUsage") @Import(FileStorageConfig::class) @TestPropertySource(properties = [ "podcastserver.storage.bucket=data", "podcastserver.storage.username=foo", "podcastserver.storage.password=bar", "podcastserver.storage.url=http://localhost:$s3MockBackendPort/", ]) @ExtendWith(SpringExtension::class) @ImportAutoConfiguration(WebClientAutoConfiguration::class) class FileStorageServiceTest( @Autowired val fileService: FileStorageService ) { @JvmField @RegisterExtension val s3Backend: WireMockExtension = WireMockExtension.newInstance() .options(wireMockConfig().port(s3MockBackendPort)) .build() @Nested @DisplayName("should delete podcast") inner class ShouldDeletePodcast { val request = DeletePodcastRequest(id = UUID.randomUUID(), title = "podcast-title") @Test fun `with success`() { /* Given */ s3Backend.stubFor(get("/data?prefix=podcast-title").willReturn(okXml(""" <?xml version="1.0" encoding="UTF-8"?> <ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <Name>data</Name> <IsTruncated>false</IsTruncated> <Contents> <Key>podcast-title/first.mp3</Key> </Contents> <Contents> <Key>podcast-title/second.mp3</Key> </Contents> </ListBucketResult> """.trimIndent()))) s3Backend.stubFor(delete("/data/podcast-title/first.mp3").willReturn(ok())) s3Backend.stubFor(delete("/data/podcast-title/second.mp3").willReturn(ok())) /* When */ StepVerifier.create(fileService.deletePodcast(request)) /* Then */ .expectSubscription() .expectNext(true) .verifyComplete() } @Test fun `with error because one item can't be deleted`() { /* Given */ s3Backend.stubFor(get("/data?prefix=podcast-title").willReturn(okXml(""" <?xml version="1.0" encoding="UTF-8"?> <ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <Name>data</Name> <IsTruncated>false</IsTruncated> <Contents> <Key>podcast-title/first.mp3</Key> </Contents> <Contents> <Key>podcast-title/second.mp3</Key> </Contents> </ListBucketResult> """.trimIndent()))) s3Backend.stubFor(delete("/data/podcast-title/first.mp3").willReturn(ok())) s3Backend.stubFor(delete("/data/podcast-title/second.mp3").willReturn(notFound())) /* When */ StepVerifier.create(fileService.deletePodcast(request)) /* Then */ .expectSubscription() .expectNext(false) .verifyComplete() } @Test fun `with error because podcast is not present`() { /* Given */ s3Backend.stubFor(get("/data?prefix=podcast-title").willReturn(notFound())) /* When */ StepVerifier.create(fileService.deletePodcast(request)) /* Then */ .expectSubscription() .expectNext(false) .verifyComplete() } } @Nested @DisplayName("should delete item file") inner class ShouldDeleteItemFile { val request = DeleteItemRequest(UUID.randomUUID(), Path("foo.txt"), "podcast-title") @Test fun `with success`() { /* Given */ s3Backend.stubFor(delete("/data/podcast-title/foo.txt").willReturn(ok())) /* When */ StepVerifier.create(fileService.deleteItem(request)) .expectSubscription() /* Then */ .expectNext(true) .verifyComplete() } @Test fun `with error`() { /* Given */ s3Backend.stubFor(delete("/data/podcast-title/foo.txt").willReturn(notFound())) /* When */ StepVerifier.create(fileService.deleteItem(request)) .expectSubscription() /* Then */ .expectNext(false) .verifyComplete() } } @Nested @DisplayName("should delete cover") inner class ShouldDeleteCover { private val request = DeleteCoverRequest( UUID.randomUUID(), "png", Item(UUID.fromString("4ab252dc-1cf4-4f60-ba18-1d91d1917ee6"), "foo"), Podcast(UUID.randomUUID(), "podcast-title") ) @Test fun `with success`() { /* Given */ s3Backend.stubFor(delete("/data/podcast-title/4ab252dc-1cf4-4f60-ba18-1d91d1917ee6.png") .willReturn(ok())) /* When */ StepVerifier.create(fileService.deleteCover(request)) .expectSubscription() /* Then */ .expectNext(true) .verifyComplete() } @Test fun `with error`() { /* Given */ s3Backend.stubFor(delete("/data/podcast-title/4ab252dc-1cf4-4f60-ba18-1d91d1917ee6.png") .willReturn(notFound())) /* When */ StepVerifier.create(fileService.deleteCover(request)) .expectSubscription() /* Then */ .expectNext(false) .verifyComplete() } } @Nested @DisplayName("should check if cover exists") inner class ShouldCheckIfCoverExists { @Nested @DisplayName("for Podcast") inner class ForPodcast { val podcast = Podcast( id = UUID.fromString("dd16b2eb-657e-4064-b470-5b99397ce729"), title = "podcast-title", description = "desc", signature = null, url = "https://foo.bar.com/app/file.rss", hasToBeDeleted = true, lastUpdate = OffsetDateTime.of(2019, 3, 31, 11, 21, 32, 45, ZoneOffset.ofHours(1)), type = "RSS", tags = setOf(Tag(UUID.fromString("f9d92927-1c4c-47a5-965d-efbb2d422f0c"), "Cinéma")), cover = Cover( id = UUID.fromString("1e275238-4cbe-4abb-bbca-95a0e4ebbeea"), url = URI("https://external.domain.tld/cover.png"), height = 200, width = 200 ) ) @Test fun `and it exists`() { /* Given */ s3Backend.stubFor(head(urlEqualTo("/data/podcast-title/dd16b2eb-657e-4064-b470-5b99397ce729.png")) .willReturn(ok())) /* When */ StepVerifier.create(fileService.coverExists(podcast)) .expectSubscription() /* Then */ .expectNext(Path("dd16b2eb-657e-4064-b470-5b99397ce729.png")) .verifyComplete() } @Test fun `and it exists with default extension`() { /* Given */ val specificPodcast = podcast.copy( cover = podcast.cover.copy(url = URI.create("https://external.domain.tld/cover")) ) s3Backend.stubFor(head(urlEqualTo("/data/podcast-title/dd16b2eb-657e-4064-b470-5b99397ce729.jpg")) .willReturn(ok())) /* When */ StepVerifier.create(fileService.coverExists(specificPodcast)) .expectSubscription() /* Then */ .expectNext(Path("dd16b2eb-657e-4064-b470-5b99397ce729.jpg")) .verifyComplete() } @Test fun `and it doesn't exist`() { /* Given */ s3Backend.stubFor(head(urlEqualTo("/data/podcast-title/dd16b2eb-657e-4064-b470-5b99397ce729.png")) .willReturn(notFound())) /* When */ StepVerifier.create(fileService.coverExists(podcast)) .expectSubscription() /* Then */ .verifyComplete() } } @Nested @DisplayName("for Item") inner class ForItem { val item = Item( id = UUID.fromString("27184b1a-7642-4ffd-ac7e-14fb36f7f15c"), title = "Foo", url = "https://external.domain.tld/foo/bar.mp4", pubDate = OffsetDateTime.now(), downloadDate = OffsetDateTime.now(), creationDate = OffsetDateTime.now(), description = "desc", mimeType = "audio/mp3", length = 100, fileName = null, status = Status.NOT_DOWNLOADED, podcast = Item.Podcast( id = UUID.fromString("8e2df56f-959b-4eb4-b5fa-0fd6027ae0f9"), title = "podcast-title", url = "https://external.domain.tld/bar.rss" ), cover = Item.Cover( id = UUID.fromString("f4efe8db-7abf-4998-b15c-9fa2e06096a1"), url = URI("https://external.domain.tld/foo/bar.png"), width = 200, height = 200 ) ) @Test fun `and it exists`() { /* Given */ s3Backend.stubFor(head(urlEqualTo("/data/podcast-title/27184b1a-7642-4ffd-ac7e-14fb36f7f15c.png")) .willReturn(ok())) /* When */ StepVerifier.create(fileService.coverExists(item)) .expectSubscription() /* Then */ .expectNext(Path("27184b1a-7642-4ffd-ac7e-14fb36f7f15c.png")) .verifyComplete() } @Test fun `and it exists with default extension`() { /* Given */ val specificItem = item.copy( cover = item.cover.copy( url = URI.create("https://external.domain.tld/foo/bar") ) ) s3Backend.stubFor(head(urlEqualTo("/data/podcast-title/27184b1a-7642-4ffd-ac7e-14fb36f7f15c.jpg")) .willReturn(ok())) /* When */ StepVerifier.create(fileService.coverExists(specificItem)) .expectSubscription() /* Then */ .expectNext(Path("27184b1a-7642-4ffd-ac7e-14fb36f7f15c.jpg")) .verifyComplete() } @Test fun `and it doesn't exist`() { /* Given */ s3Backend.stubFor(head(urlEqualTo("/data/podcast-title/27184b1a-7642-4ffd-ac7e-14fb36f7f15c.png")) .willReturn(notFound())) /* When */ StepVerifier.create(fileService.coverExists(item)) .expectSubscription() /* Then */ .verifyComplete() } } } @Nested @DisplayName("should download cover") inner class ShouldDownloadCover { @JvmField @RegisterExtension val externalBackend: WireMockExtension = WireMockExtension.newInstance() .options(wireMockConfig().port(8089)) .build() @Nested @DisplayName("for podcast") inner class ForPodcast { private val podcast = Podcast( id = UUID.fromString("dd16b2eb-657e-4064-b470-5b99397ce729"), title = "podcast-title", description = "desc", signature = null, url = "https://foo.bar.com/app/file.rss", hasToBeDeleted = true, lastUpdate = OffsetDateTime.of(2019, 3, 31, 11, 21, 32, 45, ZoneOffset.ofHours(1)), type = "RSS", tags = setOf(Tag(UUID.fromString("f9d92927-1c4c-47a5-965d-efbb2d422f0c"), "Cinéma")), cover = Cover( id = UUID.fromString("1e275238-4cbe-4abb-bbca-95a0e4ebbeea"), url = URI("http://localhost:8089/img/image.png"), height = 200, width = 200 ) ) @Test fun `and save it to file`() { /* Given */ externalBackend.stubFor(get("/img/image.png").willReturn(ok().withBody(fileAsByteArray("/__files/img/image.png")))) s3Backend.stubFor(put("/data/podcast-title/dd16b2eb-657e-4064-b470-5b99397ce729.png").willReturn(ok())) /* When */ StepVerifier.create(fileService.downloadPodcastCover(podcast)) /* Then */ .expectSubscription() .verifyComplete() val bodyDigest = s3Backend.findAll(newRequestPattern(RequestMethod.PUT, urlEqualTo("/data/podcast-title/dd16b2eb-657e-4064-b470-5b99397ce729.png"))) .first().body .let(DigestUtils::md5DigestAsHex) assertThat(bodyDigest).isEqualTo("1cc21d3dce8bfedbda2d867a3238e8db") } } @Nested @DisplayName("for item") inner class ForItem { private val item = Item( id = UUID.fromString("f47421c2-f7fd-480a-b266-635a97c301dd"), title = "Item title", url = "http://foo.bar.com/item.1.mp3", pubDate = null, downloadDate = null, creationDate = null, description = null, mimeType = "audio/mp3", length = null, fileName = Path("item.1.mp3"), status = Status.NOT_DOWNLOADED, podcast = Item.Podcast( id = UUID.fromString("096fc02f-e3d8-46a0-a523-6a479c573c73"), title = "podcast-title", url = null ), cover = Item.Cover( id = UUID.fromString("054b45d2-4f7a-4161-98ba-7050630ee000"), url = URI("http://localhost:8089/img/image.png"), width = 100, height = 200 ) ) @Test fun `and save it in podcast folder with specific name`() { /* Given */ val urlInBucket = "/data/podcast-title/f47421c2-f7fd-480a-b266-635a97c301dd.png" externalBackend.stubFor(get("/img/image.png") .willReturn(ok().withBody(fileAsByteArray("/__files/img/image.png")))) s3Backend.stubFor(put(urlInBucket).willReturn(ok())) /* When */ StepVerifier.create(fileService.downloadItemCover(item)) /* Then */ .expectSubscription() .verifyComplete() // val resultingFile = dir // .resolve(item.podcast.title) // .resolve("${item.id}.png") // // assertThat(resultingFile) // .exists() // .hasDigest("MD5", "1cc21d3dce8bfedbda2d867a3238e8db") val bodyDigest = s3Backend.findAll(newRequestPattern(RequestMethod.PUT, urlEqualTo(urlInBucket))) .first().body .let(DigestUtils::md5DigestAsHex) assertThat(bodyDigest).isEqualTo("1cc21d3dce8bfedbda2d867a3238e8db") } } } @Nested @DisplayName("should move podcast") inner class ShouldMovePodcastDetails { private val moveOperation = MovePodcastRequest( id = UUID.fromString("1d677bae-f58a-48e4-91ad-c95745e86d31"), from = "origin", to = "destination" ) @Test fun `with item in it`() { /* Given */ s3Backend.apply { stubFor(get("/data?prefix=origin").willReturn(okXml(""" <?xml version="1.0" encoding="UTF-8"?> <ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <Name>data</Name> <IsTruncated>false</IsTruncated> <Contents> <Key>origin/first.mp3</Key> </Contents> <Contents> <Key>origin/second.mp3</Key> </Contents> </ListBucketResult> """.trimIndent()))) stubFor(put("/data/destination/first.mp3") .withHeader("x-amz-copy-source", equalTo("/data/origin/first.mp3")) .willReturn(ok())) stubFor(put("/data/destination/second.mp3") .withHeader("x-amz-copy-source", equalTo("/data/origin/second.mp3")) .willReturn(ok())) stubFor(delete("/data/origin/first.mp3").willReturn(ok())) stubFor(delete("/data/origin/second.mp3").willReturn(ok())) } /* When */ StepVerifier.create(fileService.movePodcast(moveOperation)) /* Then */ .expectSubscription() .verifyComplete() } } @Nested @DisplayName("should cache") inner class ShouldCache { @Test fun `with success`() { /* Given */ val file = mock<FilePart>() whenever(file.transferTo(org.mockito.kotlin.any<Path>())) .then { Files.createFile(it.getArgument(0)).toMono().then() } /* When */ StepVerifier.create(fileService.cache(file, Paths.get("foo.mp3"))) /* Then */ .expectSubscription() .assertNext { assertThat(it).exists() } .verifyComplete() } } @Nested @DisplayName("should upload file") inner class ShouldUploadFile { @Test fun `with success`(@TempDir dir: Path) { /* Given */ val file = dir.resolve("toUpload.txt").apply { writeText("text is here !") } s3Backend.stubFor(put("/data/podcast-title/toUpload.txt").willReturn(ok())) /* When */ StepVerifier.create(fileService.upload("podcast-title", file)) /* Then */ .expectSubscription() .expectNextCount(1) .verifyComplete() val textContent = s3Backend.findAll(newRequestPattern(RequestMethod.PUT, urlEqualTo("/data/podcast-title/toUpload.txt"))) .first().body .decodeToString() assertThat(textContent).isEqualTo("text is here !") } } @Nested @DisplayName("should fetch metadata") inner class ShouldFetchMetadata { @Test fun `with success`() { /* Given */ s3Backend.stubFor(head(urlEqualTo("/data/podcast-title/dd16b2eb-657e-4064-b470-5b99397ce729.png")) .willReturn(ok() .withHeader("Content-Type", "image/png") .withHeader("Content-Length", "123") )) /* When */ StepVerifier.create(fileService.metadata("podcast-title", Paths.get("dd16b2eb-657e-4064-b470-5b99397ce729.png"))) /* Then */ .expectSubscription() .expectNext( FileMetaData( contentType = "image/png", size = 123L ) ) .verifyComplete() } } @Nested @DisplayName("should init bucket") inner class ShouldInitBucket { @Test fun `with no bucket before`() { /* Given */ s3Backend.apply { stubFor(head(urlEqualTo("/data")).willReturn(notFound())) stubFor(put("/data").willReturn(ok())) } /* When */ StepVerifier.create(fileService.initBucket()) /* Then */ .expectSubscription() .verifyComplete() } @Test fun `with an already existing bucket`() { /* Given */ s3Backend.stubFor(head(urlEqualTo("/data")).willReturn(ok())) /* When */ StepVerifier.create(fileService.initBucket()) /* Then */ .expectSubscription() .verifyComplete() } } @Nested @DisplayName("should sign url") inner class ShouldSignUrl { private val storageProperties = StorageProperties( bucket = "foo", username = "name", password = "pass", url = URI.create("https://storage.local/"), isInternal = true ) @Test fun `with domain from request`() { /* Given */ val onDemandFileStorageService = FileStorageConfig().fileStorageService( WebClient.builder(), storageProperties.copy(isInternal = true) ) /* When */ val uri = onDemandFileStorageService.toExternalUrl( FileDescriptor("foo", Path("bar")), URI.create("https://request.local/") ) /* Then */ assertThat(uri.host).isEqualTo("request.local") } @Test fun `with domain from storage`() { /* Given */ val onDemandFileStorageService = FileStorageConfig().fileStorageService( WebClient.builder(), storageProperties.copy(isInternal = false) ) /* When */ val uri = onDemandFileStorageService.toExternalUrl( FileDescriptor("foo", Path("bar")), URI.create("https://request.local/") ) /* Then */ assertThat(uri.host).isEqualTo("storage.local") } } }
apache-2.0
2bfb42380b6a413f3557ca4cdb83a29a
35.380117
164
0.533033
4.624419
false
false
false
false
frendyxzc/KotlinNews
video/src/main/java/vip/frendy/video/fragment/FragmentVideoList.kt
1
4182
package vip.frendy.video.fragment import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.fragment_video_list.* import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread import vip.frendy.model.entity.News import vip.frendy.model.net.Request import vip.frendy.model.router.Router import vip.frendy.video.R import vip.frendy.video.adapter.VideoListAdapter /** * 视频列表页 */ class FragmentVideoList : Fragment(), View.OnClickListener, SwipeRefreshLayout.OnRefreshListener { private var rootView: View? = null private var uid: String = "0" private var cid: String = "0" private var mVideoList: ArrayList<News> = ArrayList() companion object { fun getInstance(bundle: Bundle): FragmentVideoList { val fragment = FragmentVideoList() fragment.arguments = bundle return fragment } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { if (rootView == null) { rootView = inflater?.inflate(R.layout.fragment_video_list, container, false) initData(arguments) initView() } // 缓存的rootView需要判断是否已经被加过parent, 如果有parent需要从parent删除,要不然会发生这个rootview已经有parent的错误 (rootView?.parent as? ViewGroup)?.removeView(rootView) return rootView } private fun initData(args: Bundle) { uid = args.getString("uid") cid = args.getString("cid") loadVideo(uid, cid) } private fun initView() { val swipeRefreshLayout = rootView?.findViewById(R.id.swipeRefreshLayout) as SwipeRefreshLayout swipeRefreshLayout.setOnRefreshListener(this) val videoList = rootView?.findViewById(R.id.videoList) as RecyclerView val mLayoutManager: LinearLayoutManager = LinearLayoutManager(activity) videoList.layoutManager = mLayoutManager videoList.setOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val visibleItemCount = mLayoutManager.getChildCount() val totalItemCount = mLayoutManager.getItemCount() val pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition() if (visibleItemCount + pastVisiblesItems >= totalItemCount - 3) { loadMore(uid, cid) } } }) } override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) if (isVisibleToUser) { } else { } } override fun onDestroy() { super.onDestroy() } override fun onClick(view: View) { } override fun onRefresh() { refresh(uid, cid) } private fun loadVideo(uid: String, cid: String) = doAsync { val list = Request(activity).getVideoList(uid, cid) mVideoList.clear() mVideoList.addAll(list) uiThread { videoList.adapter = VideoListAdapter(mVideoList) { Router.intentToVideoDetail( activity, it.url, it.title) } } } private fun loadMore(uid: String, cid: String) = doAsync { val list = Request(activity).getVideoList(uid, cid) mVideoList.addAll(list) uiThread { videoList.adapter.notifyDataSetChanged() } } private fun refresh(uid: String, cid: String) = doAsync { val list = Request(activity).getVideoList(uid, cid) mVideoList.addAll(0, list) uiThread { videoList.adapter.notifyDataSetChanged() swipeRefreshLayout?.isRefreshing = false } } }
mit
12a67b9746184511ee31566a66544ecd
31.251969
117
0.657227
4.796253
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/traktapi/QuickCheckInActivity.kt
1
2795
package com.battlelancer.seriesguide.traktapi import android.content.Context import android.content.Intent import android.os.Bundle import androidx.core.app.NotificationManagerCompat import com.battlelancer.seriesguide.R import com.battlelancer.seriesguide.SgApp import com.battlelancer.seriesguide.notifications.NotificationService import com.battlelancer.seriesguide.traktapi.GenericCheckInDialogFragment.CheckInDialogDismissedEvent import com.battlelancer.seriesguide.traktapi.TraktTask.TraktActionCompleteEvent import com.battlelancer.seriesguide.ui.BaseThemeActivity import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe /** * Blank activity, just used to quickly check into a show/episode. */ class QuickCheckInActivity : BaseThemeActivity() { override fun getCustomTheme(): Int { // make the activity show the wallpaper, nothing else return R.style.Theme_SeriesGuide_Wallpaper } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val episodeId = intent.getLongExtra(EXTRA_LONG_EPISODE_ID, 0) if (episodeId == 0L) { finish() return } // show check-in dialog if (!CheckInDialogFragment.show(this, supportFragmentManager, episodeId)) { finish() } } override fun onStart() { super.onStart() EventBus.getDefault().register(this) } override fun onStop() { super.onStop() EventBus.getDefault().unregister(this) } @Subscribe fun onEvent(@Suppress("UNUSED_PARAMETER") event: CheckInDialogDismissedEvent?) { // if check-in dialog is dismissed, finish ourselves as well finish() } @Subscribe fun onEvent(event: TraktActionCompleteEvent) { if (event.traktAction != TraktAction.CHECKIN_EPISODE) { return } // display status toast about trakt action event.handle(this) // dismiss notification on successful check-in if (event.wasSuccessful) { val manager = NotificationManagerCompat.from(applicationContext) manager.cancel(SgApp.NOTIFICATION_EPISODE_ID) // replicate delete intent NotificationService.handleDeleteIntent(this, intent) } } companion object { private const val EXTRA_LONG_EPISODE_ID = "episode_id" @JvmStatic fun intent(episodeId: Long, context: Context): Intent { return Intent(context, QuickCheckInActivity::class.java) .putExtra(EXTRA_LONG_EPISODE_ID, episodeId) .addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS ) } } }
apache-2.0
256b5ba832154d4c2d81335821748085
31.137931
101
0.678354
4.946903
false
false
false
false
crunchersaspire/worshipsongs
app/src/main/java/org/worshipsongs/service/SongBookService.kt
1
2560
package org.worshipsongs.service import android.content.Context import android.database.Cursor import org.apache.commons.lang3.StringUtils import org.worshipsongs.domain.SongBook import java.util.ArrayList /** * Author : Madasamy * Version : 3.x.x */ class SongBookService(context: Context) { var allColumns = arrayOf("id", "name", "publisher") private val databaseService: DatabaseService private val userPreferenceSettingService: UserPreferenceSettingService init { databaseService = DatabaseService(context) userPreferenceSettingService = UserPreferenceSettingService(context) } fun findAll(): List<SongBook> { val songBooks = ArrayList<SongBook>() val query = "select songbook.id, songbook.name, songbook.publisher, count(songbook.id) " + "from songs as song inner join songs_songbooks as songsongbooks on " + "songsongbooks.song_id=song.id inner join song_books as songbook on " + "songbook.id=songsongbooks.songbook_id group by songbook.name" val cursor = databaseService.database!!.rawQuery(query, null) cursor.moveToFirst() while (!cursor.isAfterLast) { val songBook = cursorToSongBook(cursor) songBooks.add(songBook) cursor.moveToNext() } cursor.close() return songBooks } private fun cursorToSongBook(cursor: Cursor): SongBook { val songBook = SongBook() songBook.id = cursor.getInt(0) songBook.name = parseName(cursor.getString(1)) songBook.publisher = cursor.getString(2) songBook.noOfSongs = cursor.getInt(3) return songBook } internal fun parseName(name: String): String { return if (userPreferenceSettingService.isTamil) { databaseService.parseTamilName(name) } else { databaseService.parseEnglishName(name) } } fun filteredSongBooks(query: String, songBooks: List<SongBook>): List<SongBook> { val filteredTextList = ArrayList<SongBook>() if (StringUtils.isBlank(query)) { filteredTextList.addAll(songBooks) } else { for (songBook in songBooks) { if (songBook.name!!.toLowerCase().contains(query.toLowerCase())) { filteredTextList.add(songBook) } } } return filteredTextList } companion object { val TABLE_NAME = "song_books" } }
apache-2.0
48a918fd336e6fd03ca4ae27f60341de
27.764045
304
0.630859
4.620939
false
false
false
false
burntcookie90/Sleep-Cycle-Alarm
mobile/src/main/kotlin/io/dwak/sleepcyclealarm/ui/times/WakeUpTimesAdapter.kt
1
1342
package io.dwak.sleepcyclealarm.ui.times import android.content.Context import android.support.v7.widget.RecyclerView import android.view.ViewGroup import io.dwak.sleepcyclealarm.model.WakeUpTime import rx.Observable import rx.Subscription import rx.subjects.PublishSubject import java.util.ArrayList import java.util.Date class WakeUpTimesAdapter(val context : Context) : RecyclerView.Adapter<WakeUpTimeViewHolder>() { val items = ArrayList<WakeUpTime>() lateinit var sleepTime : Date private val clicks = PublishSubject.create<Date>() private var clickSubscription : Subscription? = null val observable : Observable<Date> get() = clicks.asObservable() fun addTime(wakeUpTime : WakeUpTime) { items.add(wakeUpTime) notifyItemInserted(itemCount) } override fun onCreateViewHolder(parent : ViewGroup?, viewType : Int) : WakeUpTimeViewHolder? = WakeUpTimeViewHolder.create(context, parent) override fun onBindViewHolder(holder : WakeUpTimeViewHolder?, position : Int) { holder?.bind(sleepTime, items[position], clicks); } override fun getItemCount() : Int = items.size fun subscribe(onNext : (Date) -> Unit) { clickSubscription = observable.subscribe(onNext) } fun unubscribe() { clickSubscription?.unsubscribe() } }
apache-2.0
39ec96b6f16c77d32abaa896ae80ef78
29.522727
96
0.726528
4.533784
false
false
false
false
j2ghz/tachiyomi-extensions
src/vi/iutruyentranh/src/eu/kanade/tachiyomi/extension/vi/iutruyentranh/Iutruyentranh.kt
1
6948
package eu.kanade.tachiyomi.extension.vi.iutruyentranh import android.util.Log import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.* import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.Request import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat /** * Created by Nam Nguyen on 29/4/2017. */ class Iutruyentranh : ParsedHttpSource() { override val name = "IuTruyenTranh" override val baseUrl = "http://iutruyentranh.com" override val lang = "vi" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient override fun popularMangaSelector() = "div.bbottom h4.media-heading" override fun latestUpdatesSelector() = "h4.media-heading" override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/genre/$page?popular", headers) } override fun latestUpdatesRequest(page: Int): Request { return GET("$baseUrl/latest/$page", headers) } override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() element.select("a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.text() } return manga } override fun latestUpdatesFromElement(element: Element): SManga { return popularMangaFromElement(element) } override fun popularMangaNextPageSelector() = "ul.pagination > li:contains(...»)" override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val url = HttpUrl.parse("$baseUrl/search/$page?")!!.newBuilder().addQueryParameter("name", query) val genres = mutableListOf<String>() val genresEx = mutableListOf<String>() (if (filters.isEmpty()) getFilterList() else filters).forEach { filter -> when (filter) { is Author -> url.addQueryParameter("autart", filter.state) is GenreList -> filter.state.forEach { genre -> when (genre.state) { Filter.TriState.STATE_INCLUDE -> genres.add(genre.name.toLowerCase()) Filter.TriState.STATE_EXCLUDE -> genresEx.add(genre.name.toLowerCase()) } } } } if (genres.isNotEmpty()) url.addQueryParameter("genres", genres.joinToString(",")) if (genresEx.isNotEmpty()) url.addQueryParameter("genres-exclude", genresEx.joinToString(",")) Log.i("tachiyomi", url.toString()) return GET(url.toString(), headers) } override fun searchMangaSelector() = popularMangaSelector() override fun searchMangaFromElement(element: Element): SManga { return popularMangaFromElement(element) } override fun searchMangaNextPageSelector() = popularMangaNextPageSelector() override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("section.manga article").first() val manga = SManga.create() manga.author = infoElement.select("span[itemprop=author]").first()?.text() manga.genre = infoElement.select("a[itemprop=genre]").text() manga.description = infoElement.select("p.box.box-danger").text() manga.status = infoElement.select("a[rel=nofollow]").last()?.text().orEmpty().let { parseStatus(it) } manga.thumbnail_url = infoElement.select("img[class^=thumbnail]").first()?.attr("src") return manga } fun parseStatus(status: String) = when { status.contains("Đang tiến hành") -> SManga.ONGOING status.contains("Đã hoàn thành") -> SManga.COMPLETED else -> SManga.UNKNOWN } override fun chapterListSelector() = "ul.list-unstyled > table > tbody > tr" override fun chapterFromElement(element: Element): SChapter { val urlElement = element.select("a").first() val chapter = SChapter.create() chapter.setUrlWithoutDomain(urlElement.attr("href") + "&load=all") chapter.name = urlElement.select("b").text() chapter.date_upload = element.select("td:eq(1)").first()?.text()?.let { SimpleDateFormat("dd/MM/yyyy").parse(it).time } ?: 0 return chapter } override fun pageListRequest(chapter: SChapter) = GET(baseUrl + chapter.url, headers) override fun pageListParse(document: Document): List<Page> { val pages = mutableListOf<Page>() var i = 0 document.select("img.img").forEach { pages.add(Page(i++, "", it.attr("src"))) } return pages } override fun imageUrlRequest(page: Page) = GET(page.url) override fun imageUrlParse(document: Document) = "" private class Author : Filter.Text("Tác giả") private class Genre(name: String) : Filter.TriState(name) private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Thể loại", genres) override fun getFilterList() = FilterList( Author(), GenreList(getGenreList()) ) private fun getGenreList() = listOf( Genre("Action"), Genre("Adult"), Genre("Adventure"), Genre("Anime"), Genre("Bishounen"), Genre("Comedy"), Genre("Cookin"), Genre("Demons"), Genre("Doujinshi"), Genre("Drama"), Genre("Ecchi"), Genre("Fantasy"), Genre("Gender Bender"), Genre("Harem"), Genre("Hentai"), Genre("Historical"), Genre("Horror"), Genre("Josei"), Genre("Live action"), Genre("Magic"), Genre("Manhua"), Genre("Manhwa"), Genre("Martial Arts"), Genre("Mature"), Genre("Mecha"), Genre("Medical"), Genre("Military"), Genre("Mystery"), Genre("One shot"), Genre("Oneshot"), Genre("Other"), Genre("Psychological"), Genre("Romance"), Genre("School Life"), Genre("Sci fi"), Genre("Seinen"), Genre("Shotacon"), Genre("Shoujo"), Genre("Shoujo Ai"), Genre("Shoujoai"), Genre("Shounen"), Genre("Shounen Ai"), Genre("Shounenai"), Genre("Slice of Life"), Genre("Smut"), Genre("Sports"), Genre("Super power"), Genre("Superma"), Genre("Supernatural"), Genre("Tragedy"), Genre("Vampire"), Genre("Webtoon"), Genre("Yaoi"), Genre("Yuri") ) }
apache-2.0
00d2c8ee11dd20c78b7f34124300da8b
33.492537
109
0.594634
4.744695
false
false
false
false
rpandey1234/kotlin-koans
src/iii_conventions/MyDateUtil.kt
1
1105
package iii_conventions import iii_conventions.TimeInterval.* import java.util.* fun MyDate.nextDay() = addTimeIntervals(DAY, 1) fun MyDate.addTimeIntervals(timeInterval: TimeInterval, number: Int): MyDate { val c = Calendar.getInstance() c.set(year, month, dayOfMonth) when (timeInterval) { TimeInterval.DAY -> c.add(Calendar.DAY_OF_MONTH, number) TimeInterval.WEEK -> c.add(Calendar.WEEK_OF_MONTH, number) TimeInterval.YEAR -> c.add(Calendar.YEAR, number) } return MyDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE)) // c.set(year + if (timeInterval == YEAR) number else 0, month, dayOfMonth) // var timeInMillis = c.timeInMillis // val millisecondsInADay = 24 * 60 * 60 * 1000L // timeInMillis += number * when (timeInterval) { // DAY -> millisecondsInADay // WEEK -> 7 * millisecondsInADay // YEAR -> 0L // } // val result = Calendar.getInstance() // result.timeInMillis = timeInMillis // return MyDate(result.get(Calendar.YEAR), result.get(Calendar.MONTH), result.get(Calendar.DATE)) }
mit
d4a9df9a5cd39f1740cf78204f8cfe9c
37.137931
101
0.675113
3.708054
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/view/components/MyTable.kt
1
3778
package at.cpickl.gadsu.view.components import at.cpickl.gadsu.service.LOG import at.cpickl.gadsu.view.logic.IndexableModel import at.cpickl.gadsu.view.logic.findIndexByComparator import java.awt.Point import java.util.* import javax.swing.JTable import javax.swing.ListSelectionModel import javax.swing.table.AbstractTableModel // private val model = MyTableModel<Treatment>(listOf( // TableColumn<Treatment>("Nr", 20, { it.number }), // TableColumn<Treatment>("Datum", 100, { it.date.formatDateTime() }) // )) // private val table = MyTable<Treatment>(model, ViewNames.Treatment.TableInClientView) class TableColumn<in E>( val name: String, val transform: (value: E) -> Any, val width: Int, val minWidth: Int? = null, val maxWidth: Int? = null ) open class MyTable<out E>( private val _model: MyTableModel<E>, viewName: String, columnResizeMode: Int = JTable.AUTO_RESIZE_LAST_COLUMN ) : JTable(_model) { val log = LOG(javaClass) init { name = viewName setAutoResizeMode(columnResizeMode) for (i in 0.rangeTo(_model.columns.size - 1)) { val modelCol = _model.columns[i] val tableCol = columnModel.getColumn(i) tableCol.preferredWidth = modelCol.width if (modelCol.minWidth != null) { tableCol.minWidth = modelCol.minWidth } if (modelCol.maxWidth != null) { tableCol.maxWidth = modelCol.maxWidth } } // for (i in 0.rangeTo(_model.columns.size - 1)) { // if (i === _model.columns.size - 1) { // columnModel.getColumn(i).maxWidth = Int.MAX_VALUE // } else { // columnModel.getColumn(i).maxWidth = _model.columns[i].width // } // } // http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#selection selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION columnSelectionAllowed = false } fun getEntityAt(row: Int): E = _model.entityAt(row) fun elementAtPoint(point: Point): Pair<Int, E>? { log.trace("elementAtIndex(point={})", point) val row = rowAtPoint(point) if (row == -1) { return null } val entity = getEntityAt(row) return Pair(row, entity) } } class MyTableModel<E>(val columns: List<TableColumn<E>>) : AbstractTableModel(), IndexableModel<E> { private val data: MutableList<E> = ArrayList() override fun getRowCount() = data.size override fun getColumnCount() = columns.size override fun getColumnName(columnIndex: Int) = columns[columnIndex].name override fun isCellEditable(rowIndex: Int, columnIndex: Int) = false override fun getValueAt(rowIndex: Int, columnIndex: Int) = columns[columnIndex].transform(data[rowIndex]) override val indexableSize: Int get() = size override fun indexableElementAt(index: Int) = data[index] val size: Int get() = data.size fun resetData(newData: List<E>) { data.clear() data.addAll(newData) fireTableDataChanged() } fun add(index: Int, element: E) { data.add(index, element) } fun setElementByComparator(newValue: E, comparator: (current: E) -> Boolean) { val index = findIndexByComparator(comparator) data[index] = newValue fireTableDataChanged() } fun removeElementByComparator(comparator: (current: E) -> Boolean) { val index = findIndexByComparator(comparator) data.removeAt(index) fireTableDataChanged() } fun entityAt(index: Int): E = data[index] fun getData(): List<E> = data.toList() }
apache-2.0
e7fa75db5b171722061daf25cf94a7eb
30.747899
109
0.628639
4.128962
false
false
false
false
danrien/projectBlue
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/playback/file/exoplayer/preparation/ExoPlayerPlayableFilePreparationSourceProvider.kt
2
1800
package com.lasthopesoftware.bluewater.client.playback.file.exoplayer.preparation import android.content.Context import android.os.Handler import com.google.android.exoplayer2.DefaultLoadControl import com.lasthopesoftware.bluewater.client.browsing.items.media.files.uri.BestMatchUriProvider import com.lasthopesoftware.bluewater.client.playback.engine.preparation.IPlayableFilePreparationSourceProvider import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.preparation.mediasource.SpawnMediaSources import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.rendering.AudioRenderersFactory import org.joda.time.Minutes class ExoPlayerPlayableFilePreparationSourceProvider( private val context: Context, private val playbackHandler: Handler, private val eventHandler: Handler, private val mediaSourceProvider: SpawnMediaSources, private val bestMatchUriProvider: BestMatchUriProvider ) : IPlayableFilePreparationSourceProvider { companion object { private val maxBufferMs = lazy { Minutes.minutes(5).toStandardDuration().millis.toInt() } private val loadControl = lazy { val builder = DefaultLoadControl.Builder() builder .setBufferDurationsMs( DefaultLoadControl.DEFAULT_MIN_BUFFER_MS, maxBufferMs.value, DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_MS, DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS) .setPrioritizeTimeOverSizeThresholds(true) builder.build() } } private val renderersFactory = AudioRenderersFactory(context, eventHandler) override fun getMaxQueueSize() = 1 override fun providePlayableFilePreparationSource() = ExoPlayerPlaybackPreparer( context, mediaSourceProvider, loadControl.value, renderersFactory, playbackHandler, eventHandler, bestMatchUriProvider ) }
lgpl-3.0
e0fbaa997ec2dc3a577ac33f9bd6f7ec
36.5
111
0.828333
4.444444
false
false
false
false
world-federation-of-advertisers/common-jvm
src/main/kotlin/org/wfanet/measurement/gcloud/spanner/Statements.kt
1
5114
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.gcloud.spanner import com.google.cloud.ByteArray import com.google.cloud.Date import com.google.cloud.Timestamp import com.google.cloud.spanner.Statement import com.google.protobuf.Message import com.google.protobuf.ProtocolMessageEnum import org.wfanet.measurement.common.identity.ExternalId import org.wfanet.measurement.common.identity.InternalId /** Binds the value that should be bound to the specified param. */ @JvmName("bindBoolean") fun Statement.Builder.bind(paramValuePair: Pair<String, Boolean>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).to(value) } /** Binds the value that should be bound to the specified param. */ @JvmName("bindBooleanBoxed") fun Statement.Builder.bind(paramValuePair: Pair<String, Boolean?>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).to(value) } /** Binds the value that should be bound to the specified param. */ @JvmName("bindLong") fun Statement.Builder.bind(paramValuePair: Pair<String, Long>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).to(value) } /** Binds the value that should be bound to the specified param. */ @JvmName("bindLongBoxed") fun Statement.Builder.bind(paramValuePair: Pair<String, Long?>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).to(value) } /** Binds the value that should be bound to the specified param. */ @JvmName("bindDouble") fun Statement.Builder.bind(paramValuePair: Pair<String, Double>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).to(value) } /** Binds the value that should be bound to the specified param. */ @JvmName("bindDoubleBoxed") fun Statement.Builder.bind(paramValuePair: Pair<String, Double?>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).to(value) } /** Binds the value that should be bound to the specified param. */ @JvmName("bindString") fun Statement.Builder.bind(paramValuePair: Pair<String, String?>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).to(value) } /** Binds the value that should be bound to the specified param. */ @JvmName("bindTimestamp") fun Statement.Builder.bind(paramValuePair: Pair<String, Timestamp?>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).to(value) } /** Binds the value that should be bound to the specified param. */ @JvmName("bindDate") fun Statement.Builder.bind(paramValuePair: Pair<String, Date?>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).to(value) } /** Binds the value that should be bound to the specified param. */ @JvmName("bindBytes") fun Statement.Builder.bind(paramValuePair: Pair<String, ByteArray?>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).to(value) } /** Binds the value that should be bound to the specified param. */ @JvmName("bindInternalId") fun Statement.Builder.bind(paramValuePair: Pair<String, InternalId>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).to(value.value) } /** Binds the value that should be bound to the specified param. */ @JvmName("bindExternalId") fun Statement.Builder.bind(paramValuePair: Pair<String, ExternalId>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).to(value.value) } /** Binds the value that should be bound to the specified param. */ @JvmName("bindProtoEnum") fun Statement.Builder.bind(paramValuePair: Pair<String, ProtocolMessageEnum>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).toProtoEnum(value) } /** Binds the value that should be bound to the specified param. */ @JvmName("bindProtoMessageBytes") fun Statement.Builder.bind(paramValuePair: Pair<String, Message?>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).toProtoBytes(value) } /** Binds the JSON value that should be bound to the specified string param. */ fun Statement.Builder.bindJson(paramValuePair: Pair<String, Message?>): Statement.Builder { val (paramName, value) = paramValuePair return bind(paramName).toProtoJson(value) } /** Builds a [Statement]. */ inline fun statement(sql: String, bind: Statement.Builder.() -> Unit): Statement = Statement.newBuilder(sql).apply(bind).build()
apache-2.0
6555c5e9f2473a4769134aee14fb34c0
37.742424
98
0.758115
4.134196
false
false
false
false
mplatvoet/kovenant
projects/jvm/src/main/kotlin/throttle.kt
1
6538
/* * Copyright (c) 2015 Mark Platvoet<[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, * THE SOFTWARE. */ @file:JvmName("KovenantJvmThrottle") package nl.komponents.kovenant.jvm import nl.komponents.kovenant.* import java.util.concurrent.Semaphore import nl.komponents.kovenant.task as baseTask /** * A Throttle restricts the number of concurrent tasks that are being executed. This runs on top of * existing Dispatchers. This is useful for situations where some Promises represent large amount of memory. * * @constructor maxConcurrentTasks set the maximum of parallel processes, must be at least 1 * @constructor context the default context on which all tasks operate */ class Throttle(val maxConcurrentTasks: Int = 1, val context: Context = Kovenant.context) { private val semaphore = Semaphore(maxConcurrentTasks) init { if (maxConcurrentTasks < 1) throw ConfigurationException("maxConcurrentTasks must be at least 1, but was $maxConcurrentTasks") } private val workQueue = NonBlockingWorkQueue<Task>() /** * Registers an async task to be executed somewhere in the near future. Callers must ensure that they call * registerDone() with some promise that signals this process is done. */ fun <V> registerTask(context: Context = this.context, fn: () -> V): Promise<V, Exception> { if (semaphore.tryAcquire()) { if (workQueue.isEmpty()) { return baseTask(context, fn) } semaphore.release() } val asyncTask = AsyncTask(context, fn) workQueue.offer(asyncTask) val promise = asyncTask.promise tryScheduleTasks() return promise } /** * Registers an async task to be executed somewhere in the near future. When this task is done the process is * considered to be finished and other tasks are allowed to execute. */ fun <V> task(context: Context = this.context, fn: () -> V): Promise<V, Exception> { return registerTask(context, fn).addDone() } /** * Registers an async task to be executed somewhere in the near future based on an existing Promise. * Callers must ensure that they call registerDone() with some promise that signals this process is done. */ fun <V, R> registerTask(promise: Promise<V, Exception>, context: Context = promise.context, fn: (V) -> R): Promise<R, Exception> { if (promise.isDone() && workQueue.isEmpty() && semaphore.tryAcquire()) { return promise.then(context, fn) } val deferred = deferred<R, Exception>(context) if (promise.isDone()) { workQueue.offer(ThenTask(promise, deferred, fn)) tryScheduleTasks() } else { promise.success(DirectDispatcherContext) { workQueue.offer(ThenTask(promise, deferred, fn)) tryScheduleTasks() }.fail(DirectDispatcherContext) { //also schedule fails to maintain order workQueue.offer(ThenTask(promise, deferred, fn)) tryScheduleTasks() } } return deferred.promise } /** * Registers an async task to be executed somewhere in the near future based on a existing Promise. * When this task is done the process is considered to be finished and other tasks are allowed to execute. */ fun <V, R> task(promise: Promise<V, Exception>, context: Context = promise.context, fn: (V) -> R): Promise<R, Exception> { return registerTask(promise, context, fn).addDone() } /** * Register a promise that signals that a previous registered task has finished */ fun <V, E> registerDone(promise: Promise<V, E>): Promise<V, E> = promise.addDone() private fun <V, E> Promise<V, E>.addDone(): Promise<V, E> = this.always(DirectDispatcherContext) { semaphore.release() tryScheduleTasks() } private fun tryScheduleTasks() { while (workQueue.isNotEmpty() && semaphore.tryAcquire()) { val task = workQueue.poll() if (task != null) { task.schedule() } else { semaphore.release() } } } } private interface Task { fun schedule() } private class AsyncTask<V>(private val context: Context, private val fn: () -> V) : Task { private val deferred: Deferred<V, Exception> = deferred(context) val promise: Promise<V, Exception> get() = deferred.promise override fun schedule() { baseTask(context, fn).success(DirectDispatcherContext) { deferred.resolve(it) }.fail(DirectDispatcherContext) { deferred.reject(it) } } } private class ThenTask<V, R>(private val promise: Promise<V, Exception>, private val deferred: Deferred<R, Exception>, private val fn: (V) -> R) : Task { override fun schedule() { if (!promise.isDone()) throw KovenantException("state exception: promise should be done") if (promise.isFailure()) { deferred.reject(promise.getError()) } else { baseTask(deferred.promise.context) { fn(promise.get()) }.success(DirectDispatcherContext) { deferred.resolve(it) }.fail(DirectDispatcherContext) { deferred.reject(it) } } } }
mit
49fca3cdd5eac07007fc750ec31f89e4
36.58046
113
0.635515
4.734251
false
false
false
false
GyrosWorkshop/WukongAndroid
wukong/src/main/java/com/senorsen/wukong/ui/SignInWebViewActivity.kt
1
2498
package com.senorsen.wukong.ui import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.graphics.Bitmap import android.os.Build import android.os.Bundle import android.os.Handler import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.util.Log import android.webkit.* import com.senorsen.wukong.R import com.senorsen.wukong.network.ApiUrls import com.senorsen.wukong.network.HttpClient import kotlin.concurrent.thread class SignInWebViewActivity : AppCompatActivity() { private val TAG = javaClass.simpleName private lateinit var webView: WebView private val handler = Handler() @SuppressLint("SetJavaScriptEnabled") public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.webview) val toolbar = findViewById<Toolbar>(R.id.toolbar) title = "Sign In" setSupportActionBar(toolbar) webView = findViewById(R.id.webview) webView.settings.javaScriptEnabled = true CookieManager.getInstance().removeAllCookies(null) thread { HttpClient() }.join() webView.settings.userAgentString = "WukongAndroid" webView.loadUrl(ApiUrls.oAuthEndpoint) var loggedIn = false webView.webViewClient = object : WebViewClient() { override fun onPageFinished(view: WebView, url: String) { Log.d(TAG, "Navigate: $url") if (url in arrayOf(ApiUrls.base + "/", ApiUrls.base + "/#") && !loggedIn) { val cookies = CookieManager.getInstance().getCookie(url) Log.d(TAG, "All the cookies of $url: $cookies") if (cookies.isNotBlank()) { loggedIn = true handler.post { webView.destroy() setResult(Activity.RESULT_OK, Intent().putExtra("cookies", cookies)) finish() } } } } override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) { if (Build.VERSION.SDK_INT >= 23) Log.d(TAG, error.description.toString() + " " + request.url) super.onReceivedError(view, request, error) } } } }
agpl-3.0
aaac0bae710291b2a81db33d4bf0022d
32.77027
111
0.614892
4.946535
false
false
false
false