repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
smmribeiro/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/ui/SingleValueModel.kt | 10 | 1075 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.collaboration.ui
import com.intellij.util.EventDispatcher
import com.intellij.util.concurrency.annotations.RequiresEdt
class SingleValueModel<T>(initialValue: T) {
private val changeEventDispatcher = EventDispatcher.create(SimpleEventListener::class.java)
var value: T = initialValue
set(value) {
field = value
changeEventDispatcher.multicaster.eventOccurred()
}
@RequiresEdt
fun addAndInvokeListener(listener: (newValue: T) -> Unit) {
addListener(listener)
listener(value)
}
@RequiresEdt
fun addListener(listener: (newValue: T) -> Unit) {
SimpleEventListener.addListener(changeEventDispatcher) {
listener(value)
}
}
fun <R> map(mapper: (T) -> R): SingleValueModel<R> {
val mappedModel = SingleValueModel(value.let(mapper))
this.addListener {
mappedModel.value = value.let(mapper)
}
return mappedModel
}
} | apache-2.0 | 243c31b20866c9f625a39022f64b613b | 28.888889 | 158 | 0.725581 | 4.3 | false | false | false | false |
Wreulicke/spring-sandbox | flexy-pool/src/main/kotlin/com/github/wreulicke/flexypool/demo/FlexyPoolConfig.kt | 1 | 2811 | package com.github.wreulicke.flexypool.demo
import com.vladmihalcea.flexypool.FlexyPoolDataSource
import com.vladmihalcea.flexypool.adaptor.TomcatCPPoolAdapter
import com.vladmihalcea.flexypool.metric.AbstractMetrics
import com.vladmihalcea.flexypool.metric.micrometer.MicrometerHistogram
import com.vladmihalcea.flexypool.metric.micrometer.MicrometerTimer
import com.vladmihalcea.flexypool.strategy.IncrementPoolOnTimeoutConnectionAcquiringStrategy
import io.micrometer.core.instrument.Metrics
import org.apache.tomcat.jdbc.pool.DataSource
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.jdbc.DatabaseDriver
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
@Configuration
@EnableConfigurationProperties(DataSourceProperties::class)
class FlexyPoolConfig(val properties: DataSourceProperties) {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.tomcat")
fun dataSource(): DataSource {
val dataSource: DataSource = properties.initializeDataSourceBuilder()
.type(DataSource::class.java)
.build() as DataSource
val databaseDriver = DatabaseDriver
.fromJdbcUrl(properties.determineUrl())
val validationQuery = databaseDriver.validationQuery
if (validationQuery != null) {
dataSource.setTestOnBorrow(true)
dataSource.setValidationQuery(validationQuery)
}
return dataSource
}
@Bean
fun configuration(): com.vladmihalcea.flexypool.config.Configuration<DataSource>? {
return com.vladmihalcea.flexypool.config.Configuration.Builder<DataSource>(
"test", dataSource(), TomcatCPPoolAdapter.FACTORY)
.build()
}
@Bean(initMethod = "start", destroyMethod = "stop")
@Primary
fun pool(): FlexyPoolDataSource<DataSource> = FlexyPoolDataSource(configuration(),
IncrementPoolOnTimeoutConnectionAcquiringStrategy.Factory(5)
)
}
// for test
class EnhancedMicrometerMetrics(configurationProperties: com.vladmihalcea.flexypool.common.ConfigurationProperties<*, *, *>?, private val database: String)
: AbstractMetrics(configurationProperties) {
override fun stop() {
}
override fun timer(name: String): MicrometerTimer = MicrometerTimer(Metrics.globalRegistry.timer(name, "database", database))
override fun start() {
}
override fun histogram(name: String) = MicrometerHistogram(Metrics.globalRegistry.summary(name, "database", database))
}
| mit | 8fde86e6078482233c143db3eca7bb8c | 41.590909 | 155 | 0.76841 | 4.83821 | false | true | false | false |
smmribeiro/intellij-community | platform/util/src/com/intellij/util/io/writeAheadLog.kt | 5 | 18818 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.io
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.io.ByteArraySequence
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.CompressionUtil
import com.intellij.util.ConcurrencyUtil
import com.intellij.util.indexing.impl.IndexStorageUtil
import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet
import it.unimi.dsi.fastutil.ints.IntSet
import java.io.*
import java.nio.file.FileAlreadyExistsException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.util.concurrent.ExecutorService
import java.util.function.Function
import java.util.zip.CRC32
import java.util.zip.CheckedInputStream
import java.util.zip.CheckedOutputStream
import java.util.zip.Checksum
private const val VERSION = 0
internal enum class WalOpCode(internal val code: Int) {
PUT(0),
REMOVE(1),
APPEND(2);
companion object {
val size = values().size
}
}
private val checksumGen = { CRC32() }
@Volatile
var debugWalRecords = false
private val log = logger<WalRecord>()
private class CorruptionException(val reason: String): IOException(reason)
private class EndOfLog: IOException()
internal class PersistentEnumeratorWal<Data> @Throws(IOException::class) @JvmOverloads constructor(dataDescriptor: KeyDescriptor<Data>,
useCompression: Boolean,
file: Path,
walIoExecutor: ExecutorService,
compact: Boolean = false) : Closeable {
private val underlying = PersistentMapWal(dataDescriptor, integerExternalizer, useCompression, file, walIoExecutor, compact)
fun enumerate(data: Data, id: Int) = underlying.put(data, id)
fun flush() = underlying.flush()
override fun close() = underlying.close()
}
internal class PersistentMapWal<K, V> @Throws(IOException::class) @JvmOverloads constructor(private val keyDescriptor: KeyDescriptor<K>,
private val valueExternalizer: DataExternalizer<V>,
private val useCompression: Boolean,
private val file: Path,
private val walIoExecutor: ExecutorService /*todo ensure sequential*/,
compact: Boolean = false) : Closeable {
private val out: DataOutputStream
val version: Int = VERSION
init {
if (compact) {
tryCompact(file, keyDescriptor, valueExternalizer)?.let { compactedWal ->
FileUtil.deleteWithRenaming(file)
FileUtil.rename(compactedWal.toFile(), file.toFile())
}
}
ensureCompatible(version, useCompression, file)
out = DataOutputStream(Files.newOutputStream(file, StandardOpenOption.WRITE, StandardOpenOption.APPEND).buffered())
}
@Throws(IOException::class)
private fun ensureCompatible(expectedVersion: Int, useCompression: Boolean, file: Path) {
if (!Files.exists(file)) {
Files.createDirectories(file.parent)
DataOutputStream(Files.newOutputStream(file, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)).use {
DataInputOutputUtil.writeINT(it, expectedVersion)
it.writeBoolean(useCompression)
}
return
}
val (actualVersion, actualUsesCompression) = DataInputStream(Files.newInputStream(file, StandardOpenOption.READ)).use {
DataInputOutputUtil.readINT(it) to it.readBoolean()
}
if (actualVersion != expectedVersion) {
throw VersionUpdatedException(file, expectedVersion, actualVersion)
}
if (actualUsesCompression != useCompression) {
throw VersionUpdatedException(file, useCompression, actualUsesCompression)
}
}
private fun ByteArray.write(outputStream: DataOutputStream) {
if (useCompression) {
CompressionUtil.writeCompressed(outputStream, this, 0, size)
}
else {
outputStream.writeInt(size)
outputStream.write(this)
}
}
private fun AppendablePersistentMap.ValueDataAppender.writeToByteArray(): ByteArray {
val baos = UnsyncByteArrayOutputStream()
append(DataOutputStream(baos))
return baos.toByteArray()
}
private fun appendRecord(key: K, appender: AppendablePersistentMap.ValueDataAppender) = WalRecord.writeRecord(WalOpCode.APPEND) {
keyDescriptor.save(it, key)
appender.writeToByteArray().write(it)
}
private fun putRecord(key: K, value: V) = WalRecord.writeRecord(WalOpCode.PUT) {
keyDescriptor.save(it, key)
writeData(value, valueExternalizer).write(it)
}
private fun removeRecord(key: K) = WalRecord.writeRecord(WalOpCode.REMOVE) {
keyDescriptor.save(it, key)
}
private fun WalRecord.submitWrite() {
walIoExecutor.submit {
if (debugWalRecords) {
println("write: $this")
}
this.write(out)
}
}
@Throws(IOException::class)
fun appendData(key: K, appender: AppendablePersistentMap.ValueDataAppender) {
appendRecord(key, appender).submitWrite()
}
@Throws(IOException::class)
fun put(key: K, value: V) {
putRecord(key, value).submitWrite()
}
@Throws(IOException::class)
fun remove(key: K) {
removeRecord(key).submitWrite()
}
@Throws(IOException::class) // todo rethrow io exception
fun flush() {
walIoExecutor.submit {
out.flush()
}.get()
}
// todo rethrow io exception
@Throws(IOException::class)
override fun close() {
walIoExecutor.submit {
out.close()
}.get()
}
@Throws(IOException::class)
fun closeAndDelete() {
close()
FileUtil.deleteWithRenaming(file)
}
}
private val integerExternalizer: EnumeratorIntegerDescriptor
get() = EnumeratorIntegerDescriptor.INSTANCE
sealed class WalEvent<K, V> {
abstract val key: K
data class PutEvent<K, V>(override val key: K, val value: V): WalEvent<K, V>()
data class RemoveEvent<K, V>(override val key: K): WalEvent<K, V>()
data class AppendEvent<K, V>(override val key: K, val data: ByteArray): WalEvent<K, V>() {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AppendEvent<*, *>
if (key != other.key) return false
if (!data.contentEquals(other.data)) return false
return true
}
override fun hashCode(): Int {
var result = key?.hashCode() ?: 0
result = 31 * result + data.contentHashCode()
return result
}
}
object CorruptionEvent: WalEvent<Nothing, Nothing>() {
override val key: Nothing
get() = throw UnsupportedOperationException()
}
}
@Throws(IOException::class)
fun <Data> restoreMemoryEnumeratorFromWal(walFile: Path,
dataDescriptor: KeyDescriptor<Data>): List<Data> {
return restoreFromWal(walFile, dataDescriptor, integerExternalizer, object : Accumulator<Data, Int, List<Data>> {
val result = arrayListOf<Data>()
override fun get(key: Data): Int = error("get not supported")
override fun remove(key: Data) = error("remove not supported")
override fun put(key: Data, value: Int) {
assert(result.size == value)
result.add(key)
}
override fun result(): List<Data> = result
}).toList()
}
@Throws(IOException::class)
fun <Data> restorePersistentEnumeratorFromWal(walFile: Path,
outputMapFile: Path,
dataDescriptor: KeyDescriptor<Data>): PersistentEnumerator<Data> {
if (Files.exists(outputMapFile)) {
throw FileAlreadyExistsException(outputMapFile.toString())
}
return restoreFromWal(walFile, dataDescriptor, integerExternalizer, object : Accumulator<Data, Int, PersistentEnumerator<Data>> {
val result = PersistentEnumerator(outputMapFile, dataDescriptor, 1024)
override fun get(key: Data): Int = error("get not supported")
override fun remove(key: Data) = error("remove not supported")
override fun put(key: Data, value: Int) = assert(result.enumerate(key) == value)
override fun result(): PersistentEnumerator<Data> = result
})
}
@Throws(IOException::class)
fun <K, V> restorePersistentMapFromWal(walFile: Path,
outputMapFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>): PersistentMap<K, V> {
if (Files.exists(outputMapFile)) {
throw FileAlreadyExistsException(outputMapFile.toString())
}
return restoreFromWal(walFile, keyDescriptor, valueExternalizer, object : Accumulator<K, V, PersistentMap<K, V>> {
val result = PersistentHashMap(outputMapFile, keyDescriptor, valueExternalizer)
override fun get(key: K): V? = result.get(key)
override fun remove(key: K) = result.remove(key)
override fun put(key: K, value: V) = result.put(key, value)
override fun result(): PersistentMap<K, V> = result
})
}
@Throws(IOException::class)
fun <K, V> restoreHashMapFromWal(walFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>): Map<K, V> {
return restoreFromWal(walFile, keyDescriptor, valueExternalizer, object : Accumulator<K, V, Map<K, V>> {
private val map = linkedMapOf<K, V>()
override fun get(key: K): V? = map.get(key)
override fun remove(key: K) {
map.remove(key)
}
override fun put(key: K, value: V) {
map.put(key, value)
}
override fun result(): Map<K, V> = map
})
}
private fun <K, V> tryCompact(walFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>): Path? {
if (!Files.exists(walFile)) {
return null
}
val keyToLastEvent = IndexStorageUtil.createKeyDescriptorHashedMap<K, IntSet>(keyDescriptor)
val shouldCompact = PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use {
var eventCount = 0
for (walEvent in it.readWal()) {
when (walEvent) {
is WalEvent.AppendEvent -> keyToLastEvent.computeIfAbsent(walEvent.key, Function { IntLinkedOpenHashSet() }).add(eventCount)
is WalEvent.PutEvent -> keyToLastEvent.put(walEvent.key, IntLinkedOpenHashSet().also{ set -> set.add(eventCount) })
is WalEvent.RemoveEvent -> keyToLastEvent.put(walEvent.key, IntLinkedOpenHashSet())
is WalEvent.CorruptionEvent -> throw CorruptionException("wal has been corrupted")
}
keyToLastEvent.computeIfAbsent(walEvent.key, Function { IntLinkedOpenHashSet() }).add(eventCount)
eventCount++
}
keyToLastEvent.size * 2 < eventCount
}
if (!shouldCompact) return null
val compactedWalFile = walFile.resolveSibling("${walFile.fileName}_compacted")
PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use { walPlayer ->
PersistentMapWal(keyDescriptor, valueExternalizer, walPlayer.useCompression, compactedWalFile, ConcurrencyUtil.newSameThreadExecutorService()).use { compactedWal ->
walPlayer.readWal().forEachIndexed{index, walEvent ->
val key = walEvent.key
val events = keyToLastEvent.get(key) ?: throw IOException("No events found for key = $key")
if (events.contains(index)) {
when (walEvent) {
is WalEvent.AppendEvent -> compactedWal.appendData(key, AppendablePersistentMap.ValueDataAppender { out -> out.write(walEvent.data) })
is WalEvent.PutEvent -> compactedWal.put(key, walEvent.value)
is WalEvent.RemoveEvent -> {/*do nothing*/}
is WalEvent.CorruptionEvent -> throw CorruptionException("wal has been corrupted")
}
}
}
}
}
return compactedWalFile
}
private class ChecksumOutputStream(delegate: OutputStream, checksumGen: () -> Checksum): CheckedOutputStream(delegate, checksumGen()) {
fun checksum() = checksum.value
}
private class ChecksumInputStream(delegate: InputStream, checksumGen: () -> Checksum): CheckedInputStream(delegate, checksumGen()) {
fun checksum() = checksum.value
}
/**
* +-------------+---------------+---------------------+---------+
* | OpCode (1b) | Checksum (8b) | Payload Length (4b) | Payload |
* +-------------+---------------+---------------------+---------+
*
* TODO it makes sense to add header for each record
*/
private class WalRecord(val opCode: WalOpCode,
private val checksum: Long,
val payload: ByteArraySequence) {
override fun toString(): String {
return "record($opCode, checksum = $checksum, len = ${payload.length()}, payload = ${StringUtil.toHexString(payload.toBytes())})"
}
@Throws(IOException::class)
fun write(target: DataOutputStream) {
target.writeByte(opCode.code)
DataInputOutputUtil.writeLONG(target, checksum)
DataInputOutputUtil.writeINT(target, payload.length)
target.write(payload.internalBuffer, payload.offset, payload.length)
}
companion object {
@Throws(IOException::class)
fun writeRecord(opCode: WalOpCode, writer: (DataOutputStream) -> Unit): WalRecord {
val baos = UnsyncByteArrayOutputStream()
val cos = ChecksumOutputStream(baos, checksumGen)
DataOutputStream(cos).use { writer(it) }
return WalRecord(opCode, cos.checksum(), baos.toByteArraySequence())
}
@Throws(IOException::class)
fun read(input: DataInputStream): WalRecord {
val code: Int
try {
code = input.readByte().toInt()
}
catch (e: EOFException) {
throw EndOfLog()
}
if (code >= WalOpCode.size) {
throw CorruptionException("no opcode present for code $code")
}
val checksum = DataInputOutputUtil.readLONG(input)
val payloadLength = DataInputOutputUtil.readINT(input)
val cis = ChecksumInputStream(input, checksumGen)
val data = cis.readNBytes(payloadLength)
val actualChecksum = cis.checksum()
if (actualChecksum != checksum) {
throw CorruptionException("checksum is wrong for log record: expected = $checksum but actual = $actualChecksum")
}
return WalRecord(WalOpCode.values()[code], checksum, ByteArraySequence(data))
}
}
}
private fun <V> readData(array: ByteArray, valueExternalizer: DataExternalizer<V>): V {
return valueExternalizer.read(DataInputStream(ByteArrayInputStream(array)))
}
private fun <V> writeData(value: V, valueExternalizer: DataExternalizer<V>): ByteArray {
val baos = UnsyncByteArrayOutputStream()
valueExternalizer.save(DataOutputStream(baos), value)
return baos.toByteArray()
}
private interface Accumulator<K, V, R> {
fun get(key: K): V?
fun remove(key: K)
fun put(key: K, value: V)
fun result(): R
}
private fun <K, V, R> restoreFromWal(walFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>,
accumulator: Accumulator<K, V, R>): R {
return PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use {
for (walEvent in it.readWal()) {
when (walEvent) {
is WalEvent.AppendEvent -> {
val previous = accumulator.get(walEvent.key)
val currentData = if (previous == null) walEvent.data else writeData(previous, valueExternalizer) + walEvent.data
accumulator.put(walEvent.key, readData(currentData, valueExternalizer))
}
is WalEvent.PutEvent -> accumulator.put(walEvent.key, walEvent.value)
is WalEvent.RemoveEvent -> accumulator.remove(walEvent.key)
is WalEvent.CorruptionEvent -> throw CorruptionException("wal has been corrupted")
}
}
accumulator.result()
}
}
class PersistentMapWalPlayer<K, V> @Throws(IOException::class) constructor(private val keyDescriptor: KeyDescriptor<K>,
private val valueExternalizer: DataExternalizer<V>,
file: Path) : Closeable {
private val input: DataInputStream
internal val useCompression: Boolean
val version: Int = VERSION
init {
if (!Files.exists(file)) {
throw FileNotFoundException(file.toString())
}
input = DataInputStream(Files.newInputStream(file).buffered())
ensureCompatible(version, input, file)
useCompression = input.readBoolean()
}
@Throws(IOException::class)
private fun ensureCompatible(expectedVersion: Int, input: DataInputStream, file: Path) {
val actualVersion = DataInputOutputUtil.readINT(input)
if (actualVersion != expectedVersion) {
throw VersionUpdatedException(file, expectedVersion, actualVersion)
}
}
fun readWal(): Sequence<WalEvent<K, V>> = generateSequence {
readNextEvent()
}
@Throws(IOException::class)
override fun close() = input.close()
@Throws(IOException::class)
private fun readNextEvent(): WalEvent<K, V>? {
val record: WalRecord
try {
record = WalRecord.read(input)
}
catch (e: EndOfLog) {
return null
}
catch (e: IOException) {
return WalEvent.CorruptionEvent as WalEvent<K, V>
}
if (debugWalRecords) {
println("read: $record")
}
val recordStream = record.payload.toInputStream()
return when (record.opCode) {
WalOpCode.PUT -> WalEvent.PutEvent(keyDescriptor.read(recordStream), readData(readByteArray(recordStream), valueExternalizer))
WalOpCode.REMOVE -> WalEvent.RemoveEvent(keyDescriptor.read(recordStream))
WalOpCode.APPEND -> WalEvent.AppendEvent(keyDescriptor.read(recordStream), readByteArray(recordStream))
}
}
private fun readByteArray(inputStream: DataInputStream): ByteArray {
if (useCompression) {
return CompressionUtil.readCompressed(inputStream)
}
else {
return ByteArray(inputStream.readInt()).also { inputStream.readFully(it) }
}
}
} | apache-2.0 | 66e76cf50d1229081b4a4f6825227236 | 35.684211 | 168 | 0.651185 | 4.836289 | false | false | false | false |
firebase/firebase-android-sdk | encoders/protoc-gen-firebase-encoders/src/main/kotlin/com/google/firebase/encoders/proto/codegen/CodeGenerator.kt | 1 | 18858 | // 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.firebase.encoders.proto.codegen
import com.google.firebase.encoders.proto.CodeGenConfig
import com.google.firebase.encoders.proto.codegen.UserDefined.Message
import com.google.firebase.encoders.proto.codegen.UserDefined.ProtoEnum
import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse
import com.squareup.javapoet.AnnotationSpec
import com.squareup.javapoet.ArrayTypeName
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import java.io.IOException
import java.io.OutputStream
import javax.inject.Inject
import javax.lang.model.element.Modifier
private val ENCODER_CLASS = ClassName.get("com.google.firebase.encoders.proto", "ProtobufEncoder")
private val ENCODABLE_ANNOTATION =
ClassName.get("com.google.firebase.encoders.annotations", "Encodable")
private val PROTOBUF_ANNOTATION = ClassName.get("com.google.firebase.encoders.proto", "Protobuf")
private val FIELD_ANNOTATION = ENCODABLE_ANNOTATION.nestedClass("Field")
private val IGNORE_ANNOTATION = ENCODABLE_ANNOTATION.nestedClass("Ignore")
internal class Gen(
private val messages: Collection<UserDefined>,
private val vendorPackage: String
) {
private val rootEncoder = ClassName.get(vendorPackage, "ProtoEncoderDoNotUse")
private val index = mutableMapOf<UserDefined, TypeSpec.Builder>()
val rootClasses = mutableMapOf<UserDefined, TypeSpec.Builder>()
fun generate() {
if (messages.isEmpty()) {
return
}
rootClasses[
Message(
owner = Owner.Package(vendorPackage, vendorPackage, "unknown"),
name = "ProtoEncoderDoNotUse",
fields = listOf()
)] = protoEncoder()
for (message in messages) {
generate(message)
}
// Messages generated above are "shallow". Meaning that they don't include their nested
// message types. Below we are addressing that by nesting messages within their respective
// containing classes.
for (type in index.keys) {
(type.owner as? Owner.MsgRef)?.let { index[it.message]!!.addType(index[type]!!.build()) }
}
}
/**
* Generates the "root" `@Encodable` class.
*
* This class is the only `@Encodable`-annotated class in the codegen. This ensures that we
* generate an encoder exactly once per message and there is no code duplication.
*
* All "included" messages(as per plugin config) delegate to this class to implement encoding.
*/
private fun protoEncoder(): TypeSpec.Builder {
return TypeSpec.classBuilder(rootEncoder)
.addAnnotation(ENCODABLE_ANNOTATION)
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build())
.addField(
FieldSpec.builder(
ENCODER_CLASS,
"ENCODER",
Modifier.PRIVATE,
Modifier.STATIC,
Modifier.FINAL
)
.initializer(
"\$T.builder().configureWith(AutoProtoEncoderDoNotUseEncoder.CONFIG).build()",
ENCODER_CLASS
)
.build()
)
.addMethod(
MethodSpec.methodBuilder("encode")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(ArrayTypeName.of(TypeName.BYTE))
.addParameter(Any::class.java, "value")
.addCode("return ENCODER.encode(value);\n")
.build()
)
.addMethod(
MethodSpec.methodBuilder("encode")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addException(IOException::class.java)
.addParameter(Any::class.java, "value")
.addParameter(OutputStream::class.java, "output")
.addCode("ENCODER.encode(value, output);\n")
.build()
)
.apply {
for (message in messages) {
addMethod(
MethodSpec.methodBuilder("get${message.name.capitalize()}")
.returns(message.toTypeName())
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.build()
)
}
}
}
private fun generate(type: UserDefined) {
if (type in index) return
index[type] = TypeSpec.classBuilder("Dummy")
val builder =
when (type) {
is ProtoEnum -> generateEnum(type)
is Message -> {
val classBuilder = generateClass(type)
classBuilder.addType(generateBuilder(type))
for (field in type.fields) {
(field.type as? UserDefined)?.let { generate(it) }
}
classBuilder
}
}
if (type.owner is Owner.Package) {
rootClasses[type] = builder
}
index[type] = builder
}
/**
* Generates an enum.
*
* Example generated enum:
*
* ```java
* import com.google.firebase.encoders.proto.ProtoEnum;
*
* public enum Foo implements ProtoEnum {
* DEFAULT(0),
* EXAMPLE(1);
*
* private final int number_;
* Foo(int number_) {
* this.number_ = number_;
* }
*
* @Override
* public int getNumber() {
* return number_;
* }
* }
* ```
*/
private fun generateEnum(type: ProtoEnum): TypeSpec.Builder {
val builder =
TypeSpec.enumBuilder(type.name).apply {
addModifiers(Modifier.PUBLIC)
this.addSuperinterface(ClassName.get("com.google.firebase.encoders.proto", "ProtoEnum"))
for (value in type.values) {
addEnumConstant("${value.name}(${value.value})")
}
}
builder.addField(
FieldSpec.builder(TypeName.INT, "number_", Modifier.PRIVATE, Modifier.FINAL).build()
)
builder.addMethod(
MethodSpec.constructorBuilder()
.addModifiers(Modifier.PRIVATE)
.addParameter(TypeName.INT, "number_")
.addCode("this.number_ = number_;\n")
.build()
)
builder.addMethod(
MethodSpec.methodBuilder("getNumber")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.returns(TypeName.INT)
.addCode("return number_;\n")
.build()
)
return builder
}
/**
* Generates a class that corresponds to a proto message.
*
* Example class:
* ```java
* public final class Foo {
* private final int field_;
* private final List<String> str_;
* private Foo(int field_, List<String> str_) {
* this.field_ = field_;
* this.str_ = str_;
* }
*
* @Protobuf(tag = 1)
* public int getField() { return field_; }
*
* @Protobuf(tag = 2)
* @Field(name = "str")
* public List<String> getStrList() { return field_; }
*
* // see generateBuilder() below
* public static class Builder {}
* public static Builder newBuilder() ;
*
* public static Foo getDefaultInstance();
*
* // these are generated only for types explicitly specified in the plugin config.
* public void writeTo(OutputStream output) throws IOException;
* public byte[] toByteArray();
*
* }
* ```
*/
// TODO(vkryachko): generate equals() and hashCode()
private fun generateClass(type: Message): TypeSpec.Builder {
val messageClass =
if (type.owner is Owner.Package) {
TypeSpec.classBuilder(type.name).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
} else {
TypeSpec.classBuilder(type.name)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC)
}
if (type in messages) {
messageClass
.addMethod(
MethodSpec.methodBuilder("toByteArray")
.addModifiers(Modifier.PUBLIC)
.returns(ArrayTypeName.of(TypeName.BYTE))
.addCode("return \$T.encode(this);\n", rootEncoder)
.build()
)
.addMethod(
MethodSpec.methodBuilder("writeTo")
.addModifiers(Modifier.PUBLIC)
.addException(IOException::class.java)
.addParameter(OutputStream::class.java, "output")
.addCode("\$T.encode(this, output);\n", rootEncoder)
.build()
)
}
val messageTypeName = ClassName.bestGuess(type.name)
val constructor = MethodSpec.constructorBuilder()
messageClass.addMethod(
MethodSpec.methodBuilder("newBuilder")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(ClassName.bestGuess("Builder"))
.addCode("return new Builder();\n")
.build()
)
for (field in type.fields) {
messageClass.addField(
FieldSpec.builder(field.typeName, "${field.name}_", Modifier.PRIVATE, Modifier.FINAL)
.build()
)
constructor.addParameter(field.typeName, "${field.name}_")
constructor.addCode("this.${field.name}_ = ${field.name}_;\n")
if (field.repeated || field.type !is Message) {
messageClass.addMethod(
MethodSpec.methodBuilder("get${field.camelCaseName}${if (field.repeated) "List" else ""}")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(
AnnotationSpec.builder(PROTOBUF_ANNOTATION)
.addMember("tag", "${field.number}")
.apply { field.type.intEncoding?.let { addMember("intEncoding", it) } }
.build()
)
.apply {
if (field.repeated) {
addAnnotation(
AnnotationSpec.builder(FIELD_ANNOTATION)
.addMember("name", "\$S", field.lowerCamelCaseName)
.build()
)
}
}
.returns(field.typeName)
.addCode("return ${field.name}_;\n")
.build()
)
} else {
// this method is for use as public API, it never returns null and falls back to
// returning default instances.
messageClass.addMethod(
MethodSpec.methodBuilder("get${field.camelCaseName}")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(AnnotationSpec.builder(IGNORE_ANNOTATION).build())
.returns(field.typeName)
.addCode(
"return ${field.name}_ == null ? \$T.getDefaultInstance() : ${field.name}_;\n",
field.typeName
)
.build()
)
// this method can return null and is needed by the encoder to make sure we don't
// try to encode default instances, which is:
// 1. inefficient
// 2. can lead to infinite recursion in case of self-referential types.
messageClass.addMethod(
MethodSpec.methodBuilder("get${field.camelCaseName}Internal")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(
AnnotationSpec.builder(PROTOBUF_ANNOTATION)
.addMember("tag", "${field.number}")
.build()
)
.addAnnotation(
AnnotationSpec.builder(FIELD_ANNOTATION)
.addMember("name", "\$S", field.lowerCamelCaseName)
.build()
)
.returns(field.typeName)
.addCode("return ${field.name}_;\n")
.build()
)
}
}
messageClass.addMethod(constructor.build())
messageClass.addField(
FieldSpec.builder(
messageTypeName,
"DEFAULT_INSTANCE",
Modifier.PRIVATE,
Modifier.STATIC,
Modifier.FINAL
)
.initializer("new Builder().build()", messageTypeName)
.build()
)
messageClass.addMethod(
MethodSpec.methodBuilder("getDefaultInstance")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(messageTypeName)
.addCode("return DEFAULT_INSTANCE;\n")
.build()
)
return messageClass
}
/**
* Generates a builder for a proto message.
*
* Example builder:
* ```java
* public static final class Builder {
* public Foo build();
* public Builder setField(int value);
* public Builder setStrList(List<String> value);
* public Builder addStr(String value);
* }
* ```
*/
// TODO(vkryachko): oneof setters should clear other oneof cases.
private fun generateBuilder(type: Message): TypeSpec {
val messageTypeName = ClassName.bestGuess(type.name)
val builder =
TypeSpec.classBuilder("Builder")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
val buildMethodArgs =
type.fields.joinToString(", ") {
if (it.repeated) "java.util.Collections.unmodifiableList(${it.name}_)" else "${it.name}_"
}
builder.addMethod(
MethodSpec.methodBuilder("build")
.addModifiers(Modifier.PUBLIC)
.returns(messageTypeName)
.addCode("return new \$T(\$L);\n", messageTypeName, buildMethodArgs)
.build()
)
val builderConstructor = MethodSpec.constructorBuilder()
for (field in type.fields) {
builder.addField(
FieldSpec.builder(field.typeName, "${field.name}_", Modifier.PRIVATE).build()
)
builderConstructor
.addCode("this.${field.name}_ = ")
.apply {
field.type.let { t ->
when (t) {
is Message ->
when {
field.repeated -> addCode("new \$T<>()", ClassName.get(ArrayList::class.java))
else -> addCode("null")
}
is Primitive ->
if (field.repeated) addCode("new \$T<>()", ClassName.get(ArrayList::class.java))
else addCode(t.defaultValue)
is ProtoEnum ->
if (field.repeated) addCode("new \$T<>()", ClassName.get(ArrayList::class.java))
else addCode(t.defaultValue.replace("$", "."))
is Unresolved -> TODO()
}
}
}
.addCode(";\n")
if (field.repeated) {
builder.addMethod(
MethodSpec.methodBuilder("add${field.camelCaseName}")
.addModifiers(Modifier.PUBLIC)
.returns(ClassName.bestGuess("Builder"))
.addParameter(field.type.toTypeName(), "${field.name}_")
.addCode("this.${field.name}_.add(${field.name}_);\n")
.addCode("return this;\n")
.build()
)
}
builder.addMethod(
MethodSpec.methodBuilder("set${field.camelCaseName}${if (field.repeated) "List" else ""}")
.addModifiers(Modifier.PUBLIC)
.returns(ClassName.bestGuess("Builder"))
.addParameter(field.typeName, "${field.name}_")
.addCode("this.${field.name}_ = ${field.name}_;\n")
.addCode("return this;\n")
.build()
)
}
builder.addMethod(builderConstructor.build())
return builder.build()
}
}
private fun ProtobufType.toTypeName(): TypeName {
return when (this) {
Primitive.INT32 -> TypeName.INT
Primitive.SINT32 -> TypeName.INT
Primitive.FIXED32 -> TypeName.INT
Primitive.SFIXED32 -> TypeName.INT
Primitive.FLOAT -> TypeName.FLOAT
Primitive.INT64 -> TypeName.LONG
Primitive.SINT64 -> TypeName.LONG
Primitive.FIXED64 -> TypeName.LONG
Primitive.SFIXED64 -> TypeName.LONG
Primitive.DOUBLE -> TypeName.DOUBLE
Primitive.BOOLEAN -> TypeName.BOOLEAN
Primitive.STRING -> ClassName.get(String::class.java)
Primitive.BYTES -> ArrayTypeName.of(TypeName.BYTE)
is Message -> {
return when (owner) {
is Owner.Package -> ClassName.get(owner.javaName, name)
is Owner.MsgRef -> (owner.message.toTypeName() as ClassName).nestedClass(name)
}
}
is ProtoEnum -> {
return when (owner) {
is Owner.Package -> ClassName.get(owner.javaName, name)
is Owner.MsgRef -> (owner.message.toTypeName() as ClassName).nestedClass(name)
}
}
is Unresolved -> throw AssertionError("Impossible!")
}
}
val ProtoField.typeName: TypeName
get() {
if (!repeated) {
return type.toTypeName()
}
return ParameterizedTypeName.get(ClassName.get(List::class.java), type.boxed)
}
private val ProtobufType.boxed: TypeName
get() {
return when (this) {
Primitive.INT32,
Primitive.SINT32,
Primitive.FIXED32,
Primitive.SFIXED32 -> ClassName.get("java.lang", "Integer")
Primitive.INT64,
Primitive.SINT64,
Primitive.FIXED64,
Primitive.SFIXED64 -> ClassName.get("java.lang", "Long")
Primitive.FLOAT -> ClassName.get("java.lang", "Float")
Primitive.DOUBLE -> ClassName.get("java.lang", "Double")
Primitive.BOOLEAN -> ClassName.get("java.lang", "Boolean")
Primitive.STRING -> ClassName.get("java.lang", "String")
Primitive.BYTES -> ArrayTypeName.of(TypeName.BYTE)
else -> toTypeName()
}
}
val ProtobufType.intEncoding: String?
get() {
return when (this) {
is Primitive.SINT32,
Primitive.SINT64 -> "com.google.firebase.encoders.proto.Protobuf.IntEncoding.SIGNED"
is Primitive.FIXED32,
Primitive.FIXED64,
Primitive.SFIXED32,
Primitive.SFIXED64 -> "com.google.firebase.encoders.proto.Protobuf.IntEncoding.FIXED"
else -> null
}
}
val ProtoEnum.defaultValue: String
get() = "$javaName.${values.find { it.value == 0 }?.name}"
class CodeGenerator @Inject constructor(private val config: CodeGenConfig) {
fun generate(messages: Collection<UserDefined>): CodeGeneratorResponse {
val gen = Gen(messages, config.vendorPackage)
gen.generate()
val responseBuilder = CodeGeneratorResponse.newBuilder()
for ((type, typeBuilder) in gen.rootClasses.entries) {
val typeSpec = typeBuilder.build()
val packageName = type.owner.javaName
val out = StringBuilder()
val file = JavaFile.builder(packageName, typeSpec).build()
file.writeTo(out)
val qualifiedName =
if (packageName.isEmpty()) typeSpec.name else "$packageName.${typeSpec.name}"
val fileName = "${qualifiedName.replace('.', '/')}.java"
responseBuilder.addFile(
CodeGeneratorResponse.File.newBuilder().setContent(out.toString()).setName(fileName)
)
}
return responseBuilder.build()
}
}
| apache-2.0 | 09e05618a206e5c6f1225f8bb6cf9444 | 33.039711 | 100 | 0.62032 | 4.447642 | false | false | false | false |
afollestad/assent | core/src/main/java/com/afollestad/assent/rationale/ShouldShowRationale.kt | 1 | 2573 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.assent.rationale
import android.app.Activity
import android.content.pm.PackageManager.PERMISSION_GRANTED
import androidx.annotation.CheckResult
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.afollestad.assent.Permission
import com.afollestad.assent.Prefs
interface ShouldShowRationale {
fun check(permission: Permission): Boolean
@CheckResult fun isPermanentlyDenied(permission: Permission): Boolean
}
internal class RealShouldShowRationale(
private val activity: Activity,
private val prefs: Prefs
) : ShouldShowRationale {
override fun check(permission: Permission): Boolean {
return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission.value)
.also { shouldShow ->
if (shouldShow) {
prefs.set(permission.key(), shouldShow)
}
}
}
/**
* Android provides a utility method, `shouldShowRequestPermissionRationale()`, that returns:
* - `true` if the user has previously denied the request...
* - `false` if a user has denied a permission and selected the "Don't ask again" option in
* the permission request dialog...
* - `false` if a device policy prohibits the permission.
*/
override fun isPermanentlyDenied(permission: Permission): Boolean {
val showRationaleWasTrue: Boolean = prefs[permission.key()] ?: false
// Using point 2 in the kdoc here...
return showRationaleWasTrue && !permission.isGranted() && !check(permission)
}
/**
* Provides a sanity check to avoid falsely returning true in [isPermanentlyDenied]. See
* [https://github.com/afollestad/assent/issues/16].
*/
private fun Permission.isGranted(): Boolean =
ContextCompat.checkSelfPermission(activity, value) == PERMISSION_GRANTED
private fun Permission.key() = "${KEY_SHOULD_SHOW_RATIONALE}_$value"
}
private const val KEY_SHOULD_SHOW_RATIONALE = "show_rationale_"
| apache-2.0 | 9e733339b0575fcaa1bebaae156cfc67 | 36.289855 | 95 | 0.739604 | 4.537919 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/services/apirequests/MessageBody.kt | 1 | 816 | package com.kickstarter.services.apirequests
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
class MessageBody private constructor(
private val body: String?
) : Parcelable {
fun body() = this.body
@Parcelize
data class Builder(
private var body: String? = null
) : Parcelable {
fun body(body: String?) = apply { this.body = body }
fun build() = MessageBody(
body = body
)
}
fun toBuilder() = Builder(
body = body
)
override fun equals(obj: Any?): Boolean {
var equals = super.equals(obj)
if (obj is MessageBody) {
equals = body() == obj.body()
}
return equals
}
companion object {
@JvmStatic
fun builder() = Builder()
}
}
| apache-2.0 | 8f2edf347611cd0169f2817c5afb9d9d | 20.473684 | 60 | 0.578431 | 4.363636 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/audio/synth/Pad.kt | 1 | 1158 | package de.fabmax.kool.modules.audio.synth
/**
* @author fabmax
*/
class Pad : SampleNode() {
private val lfo1 = Oscillator(Wave.SINE, 2f).apply { gain = 0.2f }
private val lfo2 = Oscillator(Wave.SINE, 2f).apply { gain = 150f }
private val osc1 = Oscillator(Wave.SAW).apply { gain = 5.1f }
private val osc2 = Oscillator(Wave.SAW).apply { gain = 3.9f }
private val osc3 = Oscillator(Wave.SAW).apply { gain = 4.0f }
private val osc4 = Oscillator(Wave.SQUARE).apply { gain = 3.0f }
private val highPass = HighPassFilter(0.5f, this)
private val moodFilter = MoodFilter(this)
private val chords = arrayOf(
intArrayOf( 7, 12, 17, 10),
intArrayOf(10, 15, 19, 24)
)
override fun generate(dt: Float): Float {
val n = chords[(t / 4).toInt() % chords.size]
val osc = osc1.next(dt, note(n[0], 1)) + osc2.next(dt, note(n[1], 2)) +
osc3.next(dt, note(n[2], 1)) + osc4.next(dt, note(n[3], 0)) + noise(0.7f)
val s = moodFilter.filter(lfo2.next(dt) + 1100, 0.05f, osc / 33f, dt)
return ((lfo1.next(dt) + 0.5f) * highPass.filter(s)) * 0.15f
}
}
| apache-2.0 | c4cbd70e36ef7f296bb460d422321282 | 35.1875 | 91 | 0.594991 | 2.916877 | false | false | false | false |
romannurik/muzei | android-client-common/src/main/java/com/google/android/apps/muzei/room/InstalledProviders.kt | 1 | 3769 | /*
* Copyright 2018 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.room
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.content.pm.ProviderInfo
import com.google.android.apps.muzei.api.provider.MuzeiArtProvider
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
fun ProviderInfo.getComponentName() = ComponentName(packageName, name)
private fun getProviders(context: Context, packageName: String? = null): List<ProviderInfo> {
val queryIntent = Intent(MuzeiArtProvider.ACTION_MUZEI_ART_PROVIDER)
if (packageName != null) {
queryIntent.`package` = packageName
}
val pm = context.packageManager
@Suppress("DEPRECATION")
return pm.queryIntentContentProviders(queryIntent, PackageManager.GET_META_DATA).filterNotNull().map {
it.providerInfo
}.filter {
it.enabled
}
}
/**
* Get a [Flow] for the list of currently installed [MuzeiArtProvider] instances.
*/
fun getInstalledProviders(context: Context): Flow<List<ProviderInfo>> = callbackFlow {
val currentProviders = HashMap<ComponentName, ProviderInfo>()
val packageChangeReceiver : BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (intent?.data == null) {
return
}
val packageName = intent.data?.schemeSpecificPart
when (intent.action) {
Intent.ACTION_PACKAGE_ADDED -> {
getProviders(context, packageName).forEach { providerInfo ->
currentProviders[providerInfo.getComponentName()] = providerInfo
}
}
Intent.ACTION_PACKAGE_CHANGED, Intent.ACTION_PACKAGE_REPLACED -> {
currentProviders.entries.removeAll { it.key.packageName == packageName }
getProviders(context, packageName).forEach { providerInfo ->
currentProviders[providerInfo.getComponentName()] = providerInfo
}
}
Intent.ACTION_PACKAGE_REMOVED -> {
currentProviders.entries.removeAll { it.key.packageName == packageName }
}
}
trySend(currentProviders.values.toList())
}
}
val packageChangeFilter = IntentFilter().apply {
addDataScheme("package")
addAction(Intent.ACTION_PACKAGE_ADDED)
addAction(Intent.ACTION_PACKAGE_CHANGED)
addAction(Intent.ACTION_PACKAGE_REPLACED)
addAction(Intent.ACTION_PACKAGE_REMOVED)
}
context.registerReceiver(packageChangeReceiver, packageChangeFilter)
// Populate the initial set of providers
getProviders(context).forEach { providerInfo ->
currentProviders[providerInfo.getComponentName()] = providerInfo
}
send(currentProviders.values.toList())
awaitClose {
context.unregisterReceiver(packageChangeReceiver)
}
} | apache-2.0 | 481140ddfba228d3b2db5e5ac5297ec5 | 39.106383 | 106 | 0.684532 | 5.052279 | false | false | false | false |
leafclick/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/untypedUnresolvedAccess/impl.kt | 1 | 3850 | // 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.
@file:JvmName("GroovyUnresolvedAccessChecker")
package org.jetbrains.plugins.groovy.codeInspection.untypedUnresolvedAccess
import com.intellij.codeInsight.daemon.HighlightDisplayKey
import com.intellij.codeInsight.daemon.QuickFixActionRegistrar
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.QuickFixFactory
import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider
import com.intellij.codeInspection.ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
import com.intellij.openapi.util.TextRange
import org.jetbrains.plugins.groovy.GroovyBundle.message
import org.jetbrains.plugins.groovy.codeInspection.GroovyQuickFixFactory
import org.jetbrains.plugins.groovy.highlighting.HighlightSink
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyReference
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil
fun checkUnresolvedReference(
expression: GrReferenceExpression,
highlightIfGroovyObjectOverridden: Boolean,
highlightIfMissingMethodsDeclared: Boolean,
highlightSink: HighlightSink
) {
val referenceNameElement = expression.referenceNameElement ?: return
val referenceName = expression.referenceName ?: return
val parent = expression.parent
val results: Collection<GroovyResolveResult> = getBestResolveResults(expression)
if (results.isNotEmpty()) {
val staticsOk = results.all(GrUnresolvedAccessChecker::isStaticOk)
if (!staticsOk) {
highlightSink.registerProblem(referenceNameElement, LIKE_UNKNOWN_SYMBOL, message("cannot.reference.non.static", referenceName))
}
return
}
if (ResolveUtil.isKeyOfMap(expression) || ResolveUtil.isClassReference(expression)) {
return
}
if (!highlightIfGroovyObjectOverridden && GrUnresolvedAccessChecker.areGroovyObjectMethodsOverridden(expression)) return
if (!highlightIfMissingMethodsDeclared && GrUnresolvedAccessChecker.areMissingMethodsDeclared(expression)) return
val actions = ArrayList<IntentionAction>()
if (parent is GrMethodCall) {
actions += GroovyQuickFixFactory.getInstance().createGroovyStaticImportMethodFix(parent)
}
else {
actions += generateCreateClassActions(expression)
actions += generateAddImportActions(expression)
}
actions += generateReferenceExpressionFixes(expression)
val registrar = object : QuickFixActionRegistrar {
override fun register(action: IntentionAction) {
actions += action
}
override fun register(fixRange: TextRange, action: IntentionAction, key: HighlightDisplayKey?) {
actions += action
}
}
UnresolvedReferenceQuickFixProvider.registerReferenceFixes(expression, registrar)
QuickFixFactory.getInstance().registerOrderEntryFixes(registrar, expression)
highlightSink.registerProblem(referenceNameElement, LIKE_UNKNOWN_SYMBOL, message("cannot.resolve", referenceName), actions)
}
private fun getBestResolveResults(ref: GroovyReference): Collection<GroovyResolveResult> = getBestResolveResults(ref.resolve(false))
private fun getBestResolveResults(results: Collection<GroovyResolveResult>): Collection<GroovyResolveResult> {
val staticsOk: Collection<GroovyResolveResult> = results.filter(GroovyResolveResult::isStaticsOK)
if (staticsOk.isEmpty()) {
return results
}
val accessibleStaticsOk: Collection<GroovyResolveResult> = staticsOk.filter(GroovyResolveResult::isAccessible)
if (accessibleStaticsOk.isEmpty()) {
return staticsOk
}
return accessibleStaticsOk
}
| apache-2.0 | 542a919bd9dd9b379ce90a8437dfb398 | 45.385542 | 140 | 0.818442 | 4.96134 | false | false | false | false |
siosio/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/generate/JavaUastCodeGenerationPlugin.kt | 1 | 19901 | // 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 org.jetbrains.uast.java.generate
import com.intellij.codeInsight.BlockUtils
import com.intellij.lang.Language
import com.intellij.lang.java.JavaLanguage
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.codeStyle.VariableKind
import com.intellij.psi.impl.PsiDiamondTypeUtil
import com.intellij.psi.impl.source.tree.CompositeElement
import com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl
import com.intellij.psi.util.PsiTypesUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.util.castSafelyTo
import com.siyeh.ig.psiutils.ParenthesesUtils
import org.jetbrains.uast.*
import org.jetbrains.uast.generate.UParameterInfo
import org.jetbrains.uast.generate.UastCodeGenerationPlugin
import org.jetbrains.uast.generate.UastElementFactory
import org.jetbrains.uast.java.*
internal class JavaUastCodeGenerationPlugin : UastCodeGenerationPlugin {
override fun getElementFactory(project: Project): UastElementFactory = JavaUastElementFactory(project)
override val language: Language
get() = JavaLanguage.INSTANCE
private fun cleanupMethodCall(methodCall: PsiMethodCallExpression): PsiMethodCallExpression {
if (methodCall.typeArguments.isNotEmpty()) {
val resolved = methodCall.resolveMethod() ?: return methodCall
if (methodCall.typeArguments.size == resolved.typeParameters.size &&
PsiDiamondTypeUtil.areTypeArgumentsRedundant(
methodCall.typeArguments,
methodCall,
false,
resolved,
resolved.typeParameters
)
) {
val emptyTypeArgumentsMethodCall = JavaPsiFacade.getElementFactory(methodCall.project)
.createExpressionFromText("foo()", null) as PsiMethodCallExpression
methodCall.typeArgumentList.replace(emptyTypeArgumentsMethodCall.typeArgumentList)
}
}
return JavaCodeStyleManager.getInstance(methodCall.project).shortenClassReferences(methodCall) as PsiMethodCallExpression
}
private fun adjustChainStyleToMethodCalls(oldPsi: PsiElement, newPsi: PsiElement) {
if (oldPsi is PsiMethodCallExpression && newPsi is PsiMethodCallExpression &&
oldPsi.methodExpression.qualifierExpression != null && newPsi.methodExpression.qualifier != null) {
if (oldPsi.methodExpression.children.getOrNull(1) is PsiWhiteSpace &&
newPsi.methodExpression.children.getOrNull(1) !is PsiWhiteSpace
) {
newPsi.methodExpression.addAfter(oldPsi.methodExpression.children[1], newPsi.methodExpression.children[0])
}
}
}
override fun <T : UElement> replace(oldElement: UElement, newElement: T, elementType: Class<T>): T? {
val oldPsi = oldElement.sourcePsi ?: return null
val newPsi = newElement.sourcePsi ?: return null
adjustChainStyleToMethodCalls(oldPsi, newPsi)
val factory = JavaPsiFacade.getElementFactory(oldPsi.project)
val updOldPsi = when {
(newPsi is PsiBlockStatement || newPsi is PsiCodeBlock) && oldPsi.parent is PsiExpressionStatement -> oldPsi.parent
else -> oldPsi
}
val updNewPsi = when {
updOldPsi is PsiStatement && newPsi is PsiExpression -> factory.createExpresionStatement(newPsi) ?: return null
updOldPsi is PsiCodeBlock && newPsi is PsiBlockStatement -> newPsi.codeBlock
else -> newPsi
}
return when (val replaced = updOldPsi.replace(updNewPsi)) {
is PsiExpressionStatement -> replaced.expression.toUElementOfExpectedTypes(elementType)
is PsiMethodCallExpression -> cleanupMethodCall(replaced).toUElementOfExpectedTypes(elementType)
else -> replaced.toUElementOfExpectedTypes(elementType)
}
}
}
private fun PsiElementFactory.createExpresionStatement(expression: PsiExpression): PsiStatement? {
val statement = createStatementFromText("x;", null) as? PsiExpressionStatement ?: return null
statement.expression.replace(expression)
return statement
}
class JavaUastElementFactory(private val project: Project) : UastElementFactory {
private val psiFactory: PsiElementFactory = JavaPsiFacade.getElementFactory(project)
override fun createQualifiedReference(qualifiedName: String, context: UElement?): UQualifiedReferenceExpression? =
createQualifiedReference(qualifiedName, context?.sourcePsi)
override fun createQualifiedReference(qualifiedName: String, context: PsiElement?): UQualifiedReferenceExpression? {
return psiFactory.createExpressionFromText(qualifiedName, context)
.castSafelyTo<PsiReferenceExpression>()
?.let { JavaUQualifiedReferenceExpression(it, null) }
}
override fun createIfExpression(condition: UExpression,
thenBranch: UExpression,
elseBranch: UExpression?,
context: PsiElement?): UIfExpression? {
val conditionPsi = condition.sourcePsi ?: return null
val thenBranchPsi = thenBranch.sourcePsi ?: return null
val ifStatement = psiFactory.createStatementFromText("if (a) b else c", null) as? PsiIfStatement ?: return null
ifStatement.condition?.replace(conditionPsi)
ifStatement.thenBranch?.replace(thenBranchPsi.branchStatement ?: return null)
elseBranch?.sourcePsi?.branchStatement?.let { ifStatement.elseBranch?.replace(it) } ?: ifStatement.elseBranch?.delete()
return JavaUIfExpression(ifStatement, null)
}
override fun createCallExpression(receiver: UExpression?,
methodName: String,
parameters: List<UExpression>,
expectedReturnType: PsiType?,
kind: UastCallKind,
context: PsiElement?): UCallExpression? {
if (kind != UastCallKind.METHOD_CALL) return null
val methodCall = psiFactory.createExpressionFromText(
if (receiver != null) "a.b()" else "a()", context
) as? PsiMethodCallExpression ?: return null
val methodIdentifier = psiFactory.createIdentifier(methodName)
if (receiver != null) {
methodCall.methodExpression.qualifierExpression?.replace(receiver.sourcePsi!!)
}
methodCall.methodExpression.referenceNameElement?.replace(methodIdentifier)
for (parameter in parameters) {
methodCall.argumentList.add(parameter.sourcePsi!!)
}
return if (expectedReturnType == null)
methodCall.toUElementOfType<UCallExpression>()
else
MethodCallUpgradeHelper(project, methodCall, expectedReturnType).tryUpgradeToExpectedType()
?.let { JavaUCallExpression(it, null) }
}
override fun createStringLiteralExpression(text: String, context: PsiElement?): ULiteralExpression? {
val literalExpr = psiFactory.createExpressionFromText(StringUtil.wrapWithDoubleQuote(text), context)
if (literalExpr !is PsiLiteralExpressionImpl) return null
return JavaULiteralExpression(literalExpr, null)
}
override fun createNullLiteral(context: PsiElement?): ULiteralExpression? {
val literalExpr = psiFactory.createExpressionFromText("null", context)
if (literalExpr !is PsiLiteralExpressionImpl) return null
return JavaULiteralExpression(literalExpr, null)
}
private class MethodCallUpgradeHelper(val project: Project, val methodCall: PsiMethodCallExpression, val expectedReturnType: PsiType) {
lateinit var resultType: PsiType
fun tryUpgradeToExpectedType(): PsiMethodCallExpression? {
resultType = methodCall.type ?: return null
if (expectedReturnType.isAssignableFrom(resultType)) return methodCall
if (!(resultType eqResolved expectedReturnType))
return null
return methodCall.methodExpression.qualifierExpression?.let { tryPickUpTypeParameters() }
}
private fun tryPickUpTypeParameters(): PsiMethodCallExpression? {
val expectedTypeTypeParameters = expectedReturnType.castSafelyTo<PsiClassType>()?.parameters ?: return null
val resultTypeTypeParameters = resultType.castSafelyTo<PsiClassType>()?.parameters ?: return null
val notEqualTypeParametersIndices = expectedTypeTypeParameters
.zip(resultTypeTypeParameters)
.withIndex()
.filterNot { (_, pair) -> PsiTypesUtil.compareTypes(pair.first, pair.second, false) }
.map { (i, _) -> i }
val resolvedMethod = methodCall.resolveMethod() ?: return null
val methodReturnTypeTypeParameters = (resolvedMethod.returnType.castSafelyTo<PsiClassType>())?.parameters ?: return null
val methodDefinitionTypeParameters = resolvedMethod.typeParameters
val methodDefinitionToReturnTypeParametersMapping = methodDefinitionTypeParameters.map {
it to methodReturnTypeTypeParameters.indexOfFirst { param -> it.name == param.canonicalText }
}
.filter { it.second != -1 }
.toMap()
val notMatchedTypesParametersNames = notEqualTypeParametersIndices
.map { methodReturnTypeTypeParameters[it].canonicalText }
.toSet()
val callTypeParametersSubstitutor = methodCall.resolveMethodGenerics().substitutor
val newParametersList = mutableListOf<PsiType>()
for (parameter in methodDefinitionTypeParameters) {
if (parameter.name in notMatchedTypesParametersNames) {
newParametersList += expectedTypeTypeParameters[methodDefinitionToReturnTypeParametersMapping[parameter] ?: return null]
}
else {
newParametersList += callTypeParametersSubstitutor.substitute(parameter) ?: return null
}
}
return buildMethodCallFromNewTypeParameters(newParametersList)
}
private fun buildMethodCallFromNewTypeParameters(newParametersList: List<PsiType>): PsiMethodCallExpression? {
val factory = JavaPsiFacade.getElementFactory(project)
val expr = factory.createExpressionFromText(buildString {
append("a.<")
newParametersList.joinTo(this) { "T" }
append(">b()")
}, null) as? PsiMethodCallExpression ?: return null
for ((i, param) in newParametersList.withIndex()) {
val typeElement = factory.createTypeElement(param)
expr.typeArgumentList.typeParameterElements[i].replace(typeElement)
}
methodCall.typeArgumentList.replace(expr.typeArgumentList)
if (methodCall.type?.let { expectedReturnType.isAssignableFrom(it) } != true)
return null
return methodCall
}
infix fun PsiType.eqResolved(other: PsiType): Boolean {
val resolvedThis = this.castSafelyTo<PsiClassType>()?.resolve() ?: return false
val resolvedOther = other.castSafelyTo<PsiClassType>()?.resolve() ?: return false
return PsiManager.getInstance(project).areElementsEquivalent(resolvedThis, resolvedOther)
}
}
override fun createDeclarationExpression(declarations: List<UDeclaration>, context: PsiElement?): UDeclarationsExpression? {
return JavaUDeclarationsExpression(null, declarations)
}
override fun createReturnExpresion(expression: UExpression?,
inLambda: Boolean,
context: PsiElement?): UReturnExpression? {
val returnStatement = psiFactory.createStatementFromText("return ;", null) as? PsiReturnStatement ?: return null
expression?.sourcePsi?.node?.let { (returnStatement as CompositeElement).addChild(it, returnStatement.lastChild.node) }
return JavaUReturnExpression(returnStatement, null)
}
private fun PsiVariable.setMutability(immutable: Boolean) {
if (immutable && !this.hasModifier(JvmModifier.FINAL)) {
PsiUtil.setModifierProperty(this, PsiModifier.FINAL, true)
}
if (!immutable && this.hasModifier(JvmModifier.FINAL)) {
PsiUtil.setModifierProperty(this, PsiModifier.FINAL, false)
}
}
override fun createLocalVariable(suggestedName: String?,
type: PsiType?,
initializer: UExpression,
immutable: Boolean,
context: PsiElement?): ULocalVariable? {
val initializerPsi = initializer.sourcePsi as? PsiExpression ?: return null
val name = createNameFromSuggested(
suggestedName,
VariableKind.LOCAL_VARIABLE,
type,
initializer = initializerPsi,
context = initializerPsi
) ?: return null
val variable = (type ?: initializer.getExpressionType())?.let { variableType ->
psiFactory.createVariableDeclarationStatement(name, variableType, initializerPsi,
initializerPsi.context).declaredElements.firstOrNull() as? PsiLocalVariable
} ?: return null
variable.setMutability(immutable)
return JavaULocalVariable(variable, null)
}
override fun createBlockExpression(expressions: List<UExpression>, context: PsiElement?): UBlockExpression? {
val blockStatement = BlockUtils.createBlockStatement(project)
for (expression in expressions) {
if (expression is JavaUDeclarationsExpression) {
for (declaration in expression.declarations) {
if (declaration.sourcePsi is PsiLocalVariable) {
blockStatement.codeBlock.add(declaration.sourcePsi?.parent as? PsiDeclarationStatement ?: return null)
}
}
continue
}
expression.sourcePsi?.let { psi ->
psi as? PsiStatement ?: (psi as? PsiExpression)?.let { psiFactory.createExpresionStatement(it) }
}?.let { blockStatement.codeBlock.add(it) } ?: return null
}
return JavaUBlockExpression(blockStatement, null)
}
override fun createLambdaExpression(parameters: List<UParameterInfo>, body: UExpression, context: PsiElement?): ULambdaExpression? {
//TODO: smart handling cases, when parameters types should exist in code
val lambda = psiFactory.createExpressionFromText(
buildString {
parameters.joinTo(this, separator = ",", prefix = "(", postfix = ")") { "x x" }
append("->{}")
},
null
) as? PsiLambdaExpression ?: return null
val needsType = parameters.all { it.type != null }
lambda.parameterList.parameters.forEachIndexed { i, parameter ->
parameters[i].also { parameterInfo ->
val name = createNameFromSuggested(
parameterInfo.suggestedName,
VariableKind.PARAMETER,
parameterInfo.type,
context = body.sourcePsi
) ?: return null
parameter.nameIdentifier?.replace(psiFactory.createIdentifier(name))
if (needsType) {
parameter.typeElement?.replace(psiFactory.createTypeElement(parameterInfo.type!!))
}
else {
parameter.removeTypeElement()
}
}
}
if (lambda.parameterList.parametersCount == 1) {
lambda.parameterList.parameters[0].removeTypeElement()
lambda.parameterList.firstChild.delete()
lambda.parameterList.lastChild.delete()
}
val normalizedBody = when (val bodyPsi = body.sourcePsi) {
is PsiExpression -> bodyPsi
is PsiCodeBlock -> normalizeBlockForLambda(bodyPsi)
is PsiBlockStatement -> normalizeBlockForLambda(bodyPsi.codeBlock)
else -> return null
}
lambda.body?.replace(normalizedBody) ?: return null
return JavaULambdaExpression(lambda, null)
}
private fun normalizeBlockForLambda(block: PsiCodeBlock): PsiElement =
block
.takeIf { block.statementCount == 1 }
?.let { block.statements[0] as? PsiReturnStatement }
?.returnValue
?: block
override fun createParenthesizedExpression(expression: UExpression, context: PsiElement?): UParenthesizedExpression? {
val parenthesizedExpression = psiFactory.createExpressionFromText("()", null) as? PsiParenthesizedExpression ?: return null
parenthesizedExpression.children.getOrNull(1)?.replace(expression.sourcePsi ?: return null) ?: return null
return JavaUParenthesizedExpression(parenthesizedExpression, null)
}
override fun createSimpleReference(name: String, context: PsiElement?): USimpleNameReferenceExpression? {
val reference = psiFactory.createExpressionFromText(name, null)
return JavaUSimpleNameReferenceExpression(reference, name, null)
}
override fun createSimpleReference(variable: UVariable, context: PsiElement?): USimpleNameReferenceExpression? {
return createSimpleReference(variable.name ?: return null, context)
}
override fun createBinaryExpression(leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?): UBinaryExpression? {
val leftPsi = leftOperand.sourcePsi ?: return null
val rightPsi = rightOperand.sourcePsi ?: return null
val operatorSymbol = when (operator) {
UastBinaryOperator.LOGICAL_AND -> "&&"
UastBinaryOperator.PLUS -> "+"
else -> return null
}
val psiBinaryExpression = psiFactory.createExpressionFromText("a $operatorSymbol b", null) as? PsiBinaryExpression
?: return null
psiBinaryExpression.lOperand.replace(leftPsi)
psiBinaryExpression.rOperand?.replace(rightPsi)
return JavaUBinaryExpression(psiBinaryExpression, null)
}
override fun createFlatBinaryExpression(leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?): UPolyadicExpression? {
val binaryExpression = createBinaryExpression(leftOperand, rightOperand, operator, context) ?: return null
val binarySourcePsi = binaryExpression.sourcePsi as? PsiBinaryExpression ?: return null
val dummyParent = psiFactory.createStatementFromText("a;", null)
dummyParent.firstChild.replace(binarySourcePsi)
ParenthesesUtils.removeParentheses(dummyParent.firstChild as PsiExpression, false)
return when (val result = dummyParent.firstChild) {
is PsiBinaryExpression -> JavaUBinaryExpression(result, null)
is PsiPolyadicExpression -> JavaUPolyadicExpression(result, null)
else -> error("Unexpected type " + result.javaClass)
}
}
private val PsiElement.branchStatement: PsiStatement?
get() = when (this) {
is PsiExpression -> JavaPsiFacade.getElementFactory(project).createExpresionStatement(this)
is PsiCodeBlock -> BlockUtils.createBlockStatement(project).also { it.codeBlock.replace(this) }
is PsiStatement -> this
else -> null
}
private fun PsiVariable.removeTypeElement() {
this.typeElement?.delete()
if (this.children.getOrNull(1) !is PsiIdentifier) {
this.children.getOrNull(1)?.delete()
}
}
private fun createNameFromSuggested(suggestedName: String?,
variableKind: VariableKind,
type: PsiType? = null,
initializer: PsiExpression? = null,
context: PsiElement? = null): String? {
val codeStyleManager = JavaCodeStyleManager.getInstance(project)
val name = suggestedName ?: codeStyleManager.generateVariableName(type, initializer, variableKind) ?: return null
return codeStyleManager.suggestUniqueVariableName(name, context, false)
}
private fun JavaCodeStyleManager.generateVariableName(type: PsiType?, initializer: PsiExpression?, kind: VariableKind) =
suggestVariableName(kind, null, initializer, type).names.firstOrNull()
} | apache-2.0 | 1783240e815aee3be3d14eca2f9a2a91 | 43.424107 | 140 | 0.708055 | 5.63608 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdetsc/src/org/jetbrains/kotlin/js/inline/util/collectUtils.kt | 3 | 10373 | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.inline.util
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.backend.ast.metadata.staticRef
import org.jetbrains.kotlin.js.inline.util.collectors.InstanceCollector
import org.jetbrains.kotlin.js.translate.expression.InlineMetadata
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils
fun collectFunctionReferencesInside(scope: JsNode): List<JsName> =
collectReferencedNames(scope).filter { it.staticRef is JsFunction }
fun collectReferencedTemporaryNames(scope: JsNode): Set<JsName> {
val references = mutableSetOf<JsName>()
object : RecursiveJsVisitor() {
override fun visitElement(node: JsNode) {
if (node is HasName) {
node.name?.let { references += it }
}
super.visitElement(node)
}
}.accept(scope)
return references
}
private fun collectReferencedNames(scope: JsNode): Set<JsName> {
val references = mutableSetOf<JsName>()
object : RecursiveJsVisitor() {
override fun visitBreak(x: JsBreak) { }
override fun visitContinue(x: JsContinue) { }
override fun visit(x: JsVars.JsVar) {
val initializer = x.initExpression
if (initializer != null) {
accept(initializer)
}
}
override fun visitNameRef(nameRef: JsNameRef) {
super.visitNameRef(nameRef)
val name = nameRef.name
if (name != null) {
references += name
}
}
}.accept(scope)
return references
}
fun collectUsedNames(scope: JsNode): Set<JsName> {
val references = mutableSetOf<JsName>()
object : RecursiveJsVisitor() {
override fun visitBreak(x: JsBreak) { }
override fun visitContinue(x: JsContinue) { }
override fun visit(x: JsVars.JsVar) {
val initializer = x.initExpression
if (initializer != null) {
accept(initializer)
}
}
override fun visitNameRef(nameRef: JsNameRef) {
super.visitNameRef(nameRef)
val name = nameRef.name
if (name != null && nameRef.qualifier == null) {
references.add(name)
}
}
override fun visitFunction(x: JsFunction) {
references += x.collectFreeVariables()
}
}.accept(scope)
return references
}
fun collectDefinedNames(scope: JsNode): Set<JsName> {
val names = mutableSetOf<JsName>()
object : RecursiveJsVisitor() {
override fun visit(x: JsVars.JsVar) {
val initializer = x.initExpression
if (initializer != null) {
accept(initializer)
}
names += x.name
}
override fun visitExpressionStatement(x: JsExpressionStatement) {
val expression = x.expression
if (expression is JsFunction) {
val name = expression.name
if (name != null) {
names += name
}
}
super.visitExpressionStatement(x)
}
// Skip function expression, since it does not introduce name in scope of containing function.
// The only exception is function statement, that is handled with the code above.
override fun visitFunction(x: JsFunction) { }
}.accept(scope)
return names
}
fun JsFunction.collectFreeVariables() = collectUsedNames(body) - collectDefinedNames(body) - parameters.map { it.name }
fun JsFunction.collectLocalVariables() = collectDefinedNames(body) + parameters.map { it.name }
fun collectNamedFunctions(scope: JsNode) = collectNamedFunctionsAndMetadata(scope).mapValues { it.value.first }
fun collectNamedFunctionsOrMetadata(scope: JsNode) = collectNamedFunctionsAndMetadata(scope).mapValues { it.value.second }
fun collectNamedFunctionsAndMetadata(scope: JsNode): Map<JsName, Pair<JsFunction, JsExpression>> {
val namedFunctions = mutableMapOf<JsName, Pair<JsFunction, JsExpression>>()
scope.accept(object : RecursiveJsVisitor() {
override fun visitBinaryExpression(x: JsBinaryOperation) {
val assignment = JsAstUtils.decomposeAssignment(x)
if (assignment != null) {
val (left, right) = assignment
if (left is JsNameRef) {
val name = left.name
val function = extractFunction(right)
if (function != null && name != null) {
namedFunctions[name] = Pair(function, right)
}
}
}
super.visitBinaryExpression(x)
}
override fun visit(x: JsVars.JsVar) {
val initializer = x.initExpression
val name = x.name
if (initializer != null && name != null) {
val function = extractFunction(initializer)
if (function != null) {
namedFunctions[name] = Pair(function, initializer)
}
}
super.visit(x)
}
override fun visitFunction(x: JsFunction) {
val name = x.name
if (name != null) {
namedFunctions[name] = Pair(x, x)
}
super.visitFunction(x)
}
private fun extractFunction(expression: JsExpression) = when (expression) {
is JsFunction -> expression
else -> InlineMetadata.decompose(expression)?.function
}
})
return namedFunctions
}
fun collectAccessors(scope: JsNode): Map<String, JsFunction> {
val accessors = hashMapOf<String, JsFunction>()
scope.accept(object : RecursiveJsVisitor() {
override fun visitInvocation(invocation: JsInvocation) {
InlineMetadata.decompose(invocation)?.let {
accessors[it.tag.value] = it.function
}
super.visitInvocation(invocation)
}
})
return accessors
}
fun <T : JsNode> collectInstances(klass: Class<T>, scope: JsNode): List<T> {
return with(InstanceCollector(klass, visitNestedDeclarations = false)) {
accept(scope)
collected
}
}
fun JsNode.collectBreakContinueTargets(): Map<JsContinue, JsStatement> {
val targets = mutableMapOf<JsContinue, JsStatement>()
accept(object : RecursiveJsVisitor() {
var defaultBreakTarget: JsStatement? = null
var breakTargets = mutableMapOf<JsName, JsStatement?>()
var defaultContinueTarget: JsStatement? = null
var continueTargets = mutableMapOf<JsName, JsStatement?>()
override fun visitLabel(x: JsLabel) {
val inner = x.statement
when (inner) {
is JsDoWhile -> handleLoop(inner, inner.body, x.name)
is JsWhile -> handleLoop(inner, inner.body, x.name)
is JsFor -> handleLoop(inner, inner.body, x.name)
is JsSwitch -> handleSwitch(inner, x.name)
else -> {
withBreakAndContinue(x.name, x.statement, null) {
accept(inner)
}
}
}
}
override fun visitWhile(x: JsWhile) = handleLoop(x, x.body, null)
override fun visitDoWhile(x: JsDoWhile) = handleLoop(x, x.body, null)
override fun visitFor(x: JsFor) = handleLoop(x, x.body, null)
override fun visit(x: JsSwitch) = handleSwitch(x, null)
private fun handleSwitch(statement: JsSwitch, label: JsName?) {
withBreakAndContinue(label, statement) {
statement.cases.forEach { accept(it) }
}
}
private fun handleLoop(loop: JsStatement, body: JsStatement, label: JsName?) {
withBreakAndContinue(label, loop, loop) {
body.accept(this)
}
}
override fun visitBreak(x: JsBreak) {
val targetLabel = x.label?.name
targets[x] = if (targetLabel == null) {
defaultBreakTarget!!
}
else {
breakTargets[targetLabel]!!
}
}
override fun visitContinue(x: JsContinue) {
val targetLabel = x.label?.name
targets[x] = if (targetLabel == null) {
defaultContinueTarget!!
}
else {
continueTargets[targetLabel]!!
}
}
private fun withBreakAndContinue(
label: JsName?,
breakTargetStatement: JsStatement,
continueTargetStatement: JsStatement? = null,
action: () -> Unit
) {
val oldDefaultBreakTarget = defaultBreakTarget
val oldDefaultContinueTarget = defaultContinueTarget
val (oldBreakTarget, oldContinueTarget) = if (label != null) {
Pair(breakTargets[label], continueTargets[label])
}
else {
Pair(null, null)
}
defaultBreakTarget = breakTargetStatement
if (label != null) {
breakTargets[label] = breakTargetStatement
continueTargets[label] = continueTargetStatement
}
if (continueTargetStatement != null) {
defaultContinueTarget = continueTargetStatement
}
action()
defaultBreakTarget = oldDefaultBreakTarget
defaultContinueTarget = oldDefaultContinueTarget
if (label != null) {
breakTargets[label] = oldBreakTarget
continueTargets[label] = oldContinueTarget
}
}
})
return targets
} | apache-2.0 | b8082c60eb030af23424af5a8d83f2a2 | 32.038217 | 122 | 0.589029 | 4.941877 | false | false | false | false |
HomeMods/Relay | core/src/com/homemods/relay/pin/OutputPin.kt | 1 | 402 | package com.homemods.relay.pin
/**
* @author sergeys
*/
interface OutputPin {
fun set(state: PinState)
fun get(): PinState
fun on() = set(PinState.ON)
fun off() = set(PinState.OFF)
fun toggle() = set(if (get() == PinState.ON) {
PinState.OFF
} else {
PinState.ON
})
fun pulse(millis: Int)
fun setShutdownState(state: PinState)
} | mit | b14810ef2b52144432caec22024462d8 | 17.318182 | 50 | 0.569652 | 3.621622 | false | false | false | false |
dahlstrom-g/intellij-community | platform/lang-impl/src/com/intellij/platform/ModuleAttachProcessor.kt | 4 | 5638 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.platform
import com.intellij.CommonBundle
import com.intellij.configurationStore.StoreUtil
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.lang.LangBundle
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.PrimaryModuleManager
import com.intellij.openapi.module.impl.ModuleManagerEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.project.modifyModules
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsSafe
import com.intellij.platform.ModuleAttachProcessor.Companion.getPrimaryModule
import com.intellij.projectImport.ProjectAttachProcessor
import com.intellij.projectImport.ProjectOpenedCallback
import com.intellij.util.io.directoryStreamIfExists
import com.intellij.util.io.exists
import com.intellij.util.io.systemIndependentPath
import java.nio.file.Path
private val LOG = logger<ModuleAttachProcessor>()
class ModuleAttachProcessor : ProjectAttachProcessor() {
companion object {
@JvmStatic
fun getPrimaryModule(project: Project) = if (canAttachToProject()) PrimaryModuleManager.findPrimaryModule(project) else null
@JvmStatic
fun getSortedModules(project: Project): List<Module> {
val primaryModule = getPrimaryModule(project)
val result = ArrayList<Module>()
ModuleManager.getInstance(project).modules.filterTo(result) { it !== primaryModule}
result.sortBy(Module::getName)
primaryModule?.let {
result.add(0, it)
}
return result
}
/**
* @param project the project
* @return `null` if either multi-projects are not enabled or the project has only one module
*/
@JvmStatic
@NlsSafe
fun getMultiProjectDisplayName(project: Project): String? {
if (!canAttachToProject()) {
return null
}
val modules = ModuleManager.getInstance(project).modules
if (modules.size <= 1) {
return null
}
val primaryModule = getPrimaryModule(project) ?: modules.first()
val result = StringBuilder(primaryModule.name)
.append(", ")
.append(modules.asSequence().filter { it !== primaryModule }.first().name)
if (modules.size > 2) {
result.append("...")
}
return result.toString()
}
}
override fun attachToProject(project: Project, projectDir: Path, callback: ProjectOpenedCallback?): Boolean {
LOG.info(String.format("Attaching directory: \"%s\"", projectDir))
val dotIdeaDir = projectDir.resolve(Project.DIRECTORY_STORE_FOLDER)
if (!dotIdeaDir.exists()) {
val options = OpenProjectTask(useDefaultProjectAsTemplate = true, isNewProject = true)
val newProject = ProjectManagerEx.getInstanceEx().newProject(projectDir, options) ?: return false
PlatformProjectOpenProcessor.runDirectoryProjectConfigurators(projectDir, newProject, true)
StoreUtil.saveSettings(newProject)
runWriteAction { Disposer.dispose(newProject) }
}
val newModule = try {
findMainModule(project, dotIdeaDir) ?: findMainModule(project, projectDir)
}
catch (e: Exception) {
LOG.info(e)
Messages.showErrorDialog(project,
LangBundle.message("module.attach.dialog.message.cannot.attach.project", e.message),
CommonBundle.getErrorTitle())
return false
}
LifecycleUsageTriggerCollector.onProjectModuleAttached(project)
if (newModule != null) {
callback?.projectOpened(project, newModule)
return true
}
return Messages.showYesNoDialog(project,
LangBundle.message("module.attach.dialog.message.project.uses.non.standard.layout", projectDir),
LangBundle.message("module.attach.dialog.title.open.project"),
Messages.getQuestionIcon()) != Messages.YES
}
override fun beforeDetach(module: Module) {
module.project.messageBus.syncPublisher(ModuleAttachListener.TOPIC).beforeDetach(module)
}
}
private fun findMainModule(project: Project, projectDir: Path): Module? {
projectDir.directoryStreamIfExists({ path -> path.fileName.toString().endsWith(ModuleManagerEx.IML_EXTENSION) }) { directoryStream ->
for (file in directoryStream) {
return attachModule(project, file)
}
}
return null
}
private fun attachModule(project: Project, imlFile: Path): Module {
val module = project.modifyModules {
loadModule(imlFile.systemIndependentPath)
}
val newModule = ModuleManager.getInstance(project).findModuleByName(module.name)!!
val primaryModule = addPrimaryModuleDependency(project, newModule)
module.project.messageBus.syncPublisher(ModuleAttachListener.TOPIC).afterAttach(newModule, primaryModule, imlFile)
return newModule
}
private fun addPrimaryModuleDependency(project: Project, newModule: Module): Module? {
val module = getPrimaryModule(project)
if (module != null && module !== newModule) {
ModuleRootModificationUtil.addDependency(module, newModule)
return module
}
return null
}
| apache-2.0 | 228d59cb8d08c64daad629d6f1bc7bbb | 38.426573 | 140 | 0.733239 | 4.868739 | false | false | false | false |
OpenConference/DroidconBerlin2017 | app/src/main/java/de/droidcon/berlin2018/ui/home/HomeViewBinding.kt | 1 | 1895 | package de.droidcon.berlin2018.ui.home
import android.support.design.widget.BottomNavigationView
import android.view.ViewGroup
import de.droidcon.berlin2018.R
import de.droidcon.berlin2018.ui.disableShiftMode
import de.droidcon.berlin2018.ui.searchbox.SearchBox
import de.droidcon.berlin2018.ui.viewbinding.LifecycleAwareRef
import de.droidcon.berlin2018.ui.viewbinding.ViewBinding
/**
* Binds the UI to [HomeController]
*
* @author Hannes Dorfmann
*/
class HomeViewBinding : ViewBinding(), HomeView {
private var bottomNavigationView: BottomNavigationView by LifecycleAwareRef(this)
private var searchBox: SearchBox by LifecycleAwareRef(this)
private val navigationListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
searchBox.slideInIfNeeded()
when (item.itemId) {
R.id.nav_sessions -> {
navigator.showSessions()
true
}
R.id.nav_my_schedule -> {
navigator.showMySchedule()
true
}
R.id.nav_speakers -> {
navigator.showSpeakers()
true
}
R.id.nav_twitter -> {
navigator.showTweets()
true
}
R.id.nav_barcamp -> {
navigator.showBarcamp()
true
}
else -> false
}
}
override fun bindView(rootView: ViewGroup) {
searchBox = rootView.findViewById(R.id.searchBox)
searchBox.showInput = false
searchBox.setOnClickListener { navigator.showSearch() }
searchBox.overflowMenuClickListener = {
when (it) {
0 -> navigator.showSourceCode()
1 -> navigator.showLicences()
}
}
bottomNavigationView = rootView.findViewById(R.id.navigation)
bottomNavigationView.setOnNavigationItemSelectedListener(navigationListener)
bottomNavigationView.disableShiftMode()
bottomNavigationView.setOnNavigationItemReselectedListener { } // Disallow reselect
}
}
| apache-2.0 | 6e109eb6fd73f2423e7c10c722d510f9 | 26.867647 | 98 | 0.704485 | 4.555288 | false | false | false | false |
androidx/androidx | core/core-splashscreen/src/main/java/androidx/core/splashscreen/SplashScreen.kt | 3 | 21780 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.splashscreen
import android.R.attr
import android.annotation.SuppressLint
import android.app.Activity
import android.content.res.Resources
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Build.VERSION.SDK_INT
import android.util.TypedValue
import android.view.View
import android.view.View.OnLayoutChangeListener
import android.view.ViewGroup
import android.view.ViewTreeObserver.OnPreDrawListener
import android.view.WindowInsets
import android.view.WindowManager.LayoutParams
import android.widget.ImageView
import android.window.SplashScreenView
import androidx.annotation.MainThread
import androidx.annotation.RequiresApi
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.splashscreen.SplashScreen.KeepOnScreenCondition
/**
* Provides control over the splash screen once the application is started.
*
* On API 31+ (Android 12+) this class calls the platform methods.
*
* Prior API 31, the platform behavior is replicated with the exception of the Animated Vector
* Drawable support on the launch screen.
*
* # Usage of the `core-splashscreen` library:
*
* To replicate the splash screen behavior from Android 12 on older APIs the following steps need to
* be taken:
* 1. Create a new Theme (e.g `Theme.App.Starting`) and set its parent to `Theme.SplashScreen` or
* `Theme.SplashScreen.IconBackground`
*
* 2. In your manifest, set the `theme` attribute of the whole `<application>` or just the
* starting `<activity>` to `Theme.App.Starting`
*
* 3. In the `onCreate` method the starting activity, call [installSplashScreen] just before
* `super.onCreate()`. You also need to make sure that `postSplashScreenTheme` is set
* to the application's theme. Alternatively, this call can be replaced by [Activity#setTheme]
* if a [SplashScreen] instance isn't needed.
*
* ## Themes
*
* The library provides two themes: [R.style.Theme_SplashScreen] and
* [R.style.Theme_SplashScreen_IconBackground]. If you wish to display a background right under
* your icon, the later needs to be used. This ensure that the scale and masking of the icon are
* similar to the Android 12 Splash Screen.
*
* `windowSplashScreenAnimatedIcon`: The splash screen icon. On API 31+ it can be an animated
* vector drawable.
*
* `windowSplashScreenAnimationDuration`: Duration of the Animated Icon Animation. The value
* needs to be > 0 if the icon is animated.
*
* **Note:** This has no impact on the time during which the splash screen is displayed and is
* only used in [SplashScreenViewProvider.iconAnimationDurationMillis]. If you need to display the
* splash screen for a longer time, you can use [SplashScreen.setKeepOnScreenCondition]
*
* `windowSplashScreenIconBackgroundColor`: _To be used in with
* `Theme.SplashScreen.IconBackground`_. Sets a background color under the splash screen icon.
*
* `windowSplashScreenBackground`: Background color of the splash screen. Defaults to the theme's
* `?attr/colorBackground`.
*
* `postSplashScreenTheme`* Theme to apply to the Activity when [installSplashScreen] is called.
*
* **Known incompatibilities:**
* - On API < 31, `windowSplashScreenAnimatedIcon` cannot be animated. If you want to provide an
* animated icon for API 31+ and a still icon for API <31, you can do so by overriding the still
* icon with an animated vector drawable in `res/drawable-v31`.
*
* - On API < 31, if the value of `windowSplashScreenAnimatedIcon` is an
* [adaptive icon](http://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive)
* , it will be cropped and scaled. The workaround is to respectively assign
* `windowSplashScreenAnimatedIcon` and `windowSplashScreenIconBackgroundColor` to the values of
* the adaptive icon `foreground` and `background`.
*
* - On API 21-22, The icon isn't displayed until the application starts, only the background is
* visible.
*
* # Design
* The splash screen icon uses the same specifications as
* [Adaptive Icons](https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive)
* . This means that the icon needs to fit within a circle whose diameter is 2/3 the size of the
* icon. The actual values don't really matter if you use a vector icon.
*
* ## Specs
* - With icon background (`Theme.SplashScreen.IconBackground`)
* + Image Size: 240x240 dp
* + Inner Circle diameter: 160 dp
* - Without icon background (`Theme.SplashScreen`)
* + Image size: 288x288 dp
* + Inner circle diameter: 192 dp
*
* _Example:_ if the full size of the image is 300dp*300dp, the icon needs to fit within a
* circle with a diameter of 200dp. Everything outside the circle will be invisible (masked).
*
*/
@SuppressLint("CustomSplashScreen")
class SplashScreen private constructor(activity: Activity) {
private val impl = when {
SDK_INT >= 31 -> Impl31(activity)
else -> Impl(activity)
}
public companion object {
private const val MASK_FACTOR = 2 / 3f
/**
* Creates a [SplashScreen] instance associated with this [Activity] and handles
* setting the theme to [R.attr.postSplashScreenTheme].
*
* This needs to be called before [Activity.setContentView] or other view operations on
* the root view (e.g setting flags).
*
* Alternatively, if a [SplashScreen] instance is not required, the theme can manually be
* set using [Activity.setTheme].
*/
@JvmStatic
public fun Activity.installSplashScreen(): SplashScreen {
val splashScreen = SplashScreen(this)
splashScreen.install()
return splashScreen
}
}
/**
* Sets the condition to keep the splash screen visible.
*
* The splash will stay visible until the condition isn't met anymore.
* The condition is evaluated before each request to draw the application, so it needs to be
* fast to avoid blocking the UI.
*
* @param condition The condition evaluated to decide whether to keep the splash screen on
* screen
*/
public fun setKeepOnScreenCondition(condition: KeepOnScreenCondition) {
impl.setKeepOnScreenCondition(condition)
}
/**
* Sets a listener that will be called when the splashscreen is ready to be removed.
*
* If a listener is set, the splashscreen won't be automatically removed and the application
* needs to manually call [SplashScreenViewProvider.remove].
*
* IF no listener is set, the splashscreen will be automatically removed once the app is
* ready to draw.
*
* The listener will be called on the ui thread.
*
* @param listener The [OnExitAnimationListener] that will be called when the splash screen
* is ready to be dismissed.
*
* @see setKeepOnScreenCondition
* @see OnExitAnimationListener
* @see SplashScreenViewProvider
*/
@SuppressWarnings("ExecutorRegistration") // Always runs on the MainThread
public fun setOnExitAnimationListener(listener: OnExitAnimationListener) {
impl.setOnExitAnimationListener(listener)
}
private fun install() {
impl.install()
}
/**
* Listener to be passed in [SplashScreen.setOnExitAnimationListener].
*
* The listener will be called once the splash screen is ready to be removed and provides a
* reference to a [SplashScreenViewProvider] that can be used to customize the exit
* animation of the splash screen.
*/
public fun interface OnExitAnimationListener {
/**
* Callback called when the splash screen is ready to be dismissed. The caller is
* responsible for animating and removing splash screen using the provided
* [splashScreenViewProvider].
*
* The caller **must** call [SplashScreenViewProvider.remove] once it's done with the
* splash screen.
*
* @param splashScreenViewProvider An object holding a reference to the displayed splash
* screen.
*/
@MainThread
public fun onSplashScreenExit(splashScreenViewProvider: SplashScreenViewProvider)
}
/**
* Condition evaluated to check if the splash screen should remain on screen
*
* The splash screen will stay visible until the condition isn't met anymore.
* The condition is evaluated before each request to draw the application, so it needs to be
* fast to avoid blocking the UI.
*/
public fun interface KeepOnScreenCondition {
/**
* Callback evaluated before every requests to draw the Activity. If it returns `true`, the
* splash screen will be kept visible to hide the Activity below.
*
* This callback is evaluated in the main thread.
*/
@MainThread
public fun shouldKeepOnScreen(): Boolean
}
private open class Impl(val activity: Activity) {
var finalThemeId: Int = 0
var backgroundResId: Int? = null
var backgroundColor: Int? = null
var icon: Drawable? = null
var hasBackground: Boolean = false
var splashScreenWaitPredicate = KeepOnScreenCondition { false }
private var animationListener: OnExitAnimationListener? = null
private var mSplashScreenViewProvider: SplashScreenViewProvider? = null
open fun install() {
val typedValue = TypedValue()
val currentTheme = activity.theme
if (currentTheme.resolveAttribute(
R.attr.windowSplashScreenBackground,
typedValue,
true
)
) {
backgroundResId = typedValue.resourceId
backgroundColor = typedValue.data
}
if (currentTheme.resolveAttribute(
R.attr.windowSplashScreenAnimatedIcon,
typedValue,
true
)
) {
icon = currentTheme.getDrawable(typedValue.resourceId)
}
if (currentTheme.resolveAttribute(R.attr.splashScreenIconSize, typedValue, true)) {
hasBackground =
typedValue.resourceId == R.dimen.splashscreen_icon_size_with_background
}
setPostSplashScreenTheme(currentTheme, typedValue)
}
protected fun setPostSplashScreenTheme(
currentTheme: Resources.Theme,
typedValue: TypedValue
) {
if (currentTheme.resolveAttribute(R.attr.postSplashScreenTheme, typedValue, true)) {
finalThemeId = typedValue.resourceId
if (finalThemeId != 0) {
activity.setTheme(finalThemeId)
}
}
}
open fun setKeepOnScreenCondition(keepOnScreenCondition: KeepOnScreenCondition) {
splashScreenWaitPredicate = keepOnScreenCondition
val contentView = activity.findViewById<View>(android.R.id.content)
val observer = contentView.viewTreeObserver
observer.addOnPreDrawListener(object : OnPreDrawListener {
override fun onPreDraw(): Boolean {
if (splashScreenWaitPredicate.shouldKeepOnScreen()) {
return false
}
contentView.viewTreeObserver.removeOnPreDrawListener(this)
mSplashScreenViewProvider?.let(::dispatchOnExitAnimation)
return true
}
})
}
open fun setOnExitAnimationListener(exitAnimationListener: OnExitAnimationListener) {
animationListener = exitAnimationListener
val splashScreenViewProvider = SplashScreenViewProvider(activity)
val finalBackgroundResId = backgroundResId
val finalBackgroundColor = backgroundColor
val splashScreenView = splashScreenViewProvider.view
if (finalBackgroundResId != null && finalBackgroundResId != Resources.ID_NULL) {
splashScreenView.setBackgroundResource(finalBackgroundResId)
} else if (finalBackgroundColor != null) {
splashScreenView.setBackgroundColor(finalBackgroundColor)
} else {
splashScreenView.background = activity.window.decorView.background
}
icon?.let { displaySplashScreenIcon(splashScreenView, it) }
splashScreenView.addOnLayoutChangeListener(
object : OnLayoutChangeListener {
override fun onLayoutChange(
view: View,
left: Int,
top: Int,
right: Int,
bottom: Int,
oldLeft: Int,
oldTop: Int,
oldRight: Int,
oldBottom: Int
) {
if (!view.isAttachedToWindow) {
return
}
view.removeOnLayoutChangeListener(this)
if (!splashScreenWaitPredicate.shouldKeepOnScreen()) {
dispatchOnExitAnimation(splashScreenViewProvider)
} else {
mSplashScreenViewProvider = splashScreenViewProvider
}
}
})
}
private fun displaySplashScreenIcon(splashScreenView: View, icon: Drawable) {
val iconView = splashScreenView.findViewById<ImageView>(R.id.splashscreen_icon_view)
iconView.apply {
val maskSize: Float
if (hasBackground) {
// If the splash screen has an icon background we need to mask both the
// background and foreground.
val iconBackgroundDrawable = context.getDrawable(R.drawable.icon_background)
val iconSize =
resources.getDimension(R.dimen.splashscreen_icon_size_with_background)
maskSize = iconSize * MASK_FACTOR
if (iconBackgroundDrawable != null) {
background = MaskedDrawable(iconBackgroundDrawable, maskSize)
}
} else {
val iconSize =
resources.getDimension(R.dimen.splashscreen_icon_size_no_background)
maskSize = iconSize * MASK_FACTOR
}
setImageDrawable(MaskedDrawable(icon, maskSize))
}
}
fun dispatchOnExitAnimation(splashScreenViewProvider: SplashScreenViewProvider) {
val finalListener = animationListener ?: return
animationListener = null
splashScreenViewProvider.view.postOnAnimation {
splashScreenViewProvider.view.bringToFront()
finalListener.onSplashScreenExit(splashScreenViewProvider)
}
}
}
@RequiresApi(Build.VERSION_CODES.S)
private class Impl31(activity: Activity) : Impl(activity) {
var preDrawListener: OnPreDrawListener? = null
var mDecorFitWindowInsets = true
val hierarchyListener = object : ViewGroup.OnHierarchyChangeListener {
override fun onChildViewAdded(parent: View?, child: View?) {
if (child is SplashScreenView) {
/*
* On API 31, the SplashScreenView sets window.setDecorFitsSystemWindows(false)
* when an OnExitAnimationListener is used. This also affects the application
* content that will be pushed up under the status bar even though it didn't
* requested it. And once the SplashScreenView is removed, the whole layout
* jumps back below the status bar. Fortunately, this happens only after the
* view is attached, so we have time to record the value of
* window.setDecorFitsSystemWindows() before the splash screen modifies it and
* reapply the correct value to the window.
*/
mDecorFitWindowInsets = computeDecorFitsWindow(child)
(activity.window.decorView as ViewGroup).setOnHierarchyChangeListener(null)
}
}
override fun onChildViewRemoved(parent: View?, child: View?) {
// no-op
}
}
fun computeDecorFitsWindow(child: SplashScreenView): Boolean {
val inWindowInsets = WindowInsets.Builder().build()
val outLocalInsets = Rect(
Int.MIN_VALUE, Int.MIN_VALUE, Int.MAX_VALUE,
Int.MAX_VALUE
)
// If setDecorFitWindowInsets is set to false, computeSystemWindowInsets
// will return the same instance of WindowInsets passed in its parameter and
// will set outLocalInsets to empty, so we check that both conditions are
// filled to extrapolate the value of setDecorFitWindowInsets
return !(inWindowInsets === child.rootView.computeSystemWindowInsets
(inWindowInsets, outLocalInsets) && outLocalInsets.isEmpty)
}
override fun install() {
setPostSplashScreenTheme(activity.theme, TypedValue())
(activity.window.decorView as ViewGroup).setOnHierarchyChangeListener(
hierarchyListener
)
}
override fun setKeepOnScreenCondition(keepOnScreenCondition: KeepOnScreenCondition) {
splashScreenWaitPredicate = keepOnScreenCondition
val contentView = activity.findViewById<View>(android.R.id.content)
val observer = contentView.viewTreeObserver
if (preDrawListener != null && observer.isAlive) {
observer.removeOnPreDrawListener(preDrawListener)
}
preDrawListener = object : OnPreDrawListener {
override fun onPreDraw(): Boolean {
if (splashScreenWaitPredicate.shouldKeepOnScreen()) {
return false
}
contentView.viewTreeObserver.removeOnPreDrawListener(this)
return true
}
}
observer.addOnPreDrawListener(preDrawListener)
}
override fun setOnExitAnimationListener(
exitAnimationListener: OnExitAnimationListener
) {
activity.splashScreen.setOnExitAnimationListener { splashScreenView ->
applyAppSystemUiTheme()
val splashScreenViewProvider = SplashScreenViewProvider(splashScreenView, activity)
exitAnimationListener.onSplashScreenExit(splashScreenViewProvider)
}
}
/**
* Apply the system ui related theme attribute defined in the application to override the
* ones set on the [SplashScreenView]
*
* On API 31, if an OnExitAnimationListener is set, the Window layout params are only
* applied only when the [SplashScreenView] is removed. This lead to some
* flickers.
*
* To fix this, we apply these attributes as soon as the [SplashScreenView]
* is visible.
*/
private fun applyAppSystemUiTheme() {
val tv = TypedValue()
val theme = activity.theme
val window = activity.window
if (theme.resolveAttribute(attr.statusBarColor, tv, true)) {
window.statusBarColor = tv.data
}
if (theme.resolveAttribute(attr.navigationBarColor, tv, true)) {
window.navigationBarColor = tv.data
}
if (theme.resolveAttribute(attr.windowDrawsSystemBarBackgrounds, tv, true)) {
if (tv.data != 0) {
window.addFlags(LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
} else {
window.clearFlags(LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
}
}
if (theme.resolveAttribute(attr.enforceNavigationBarContrast, tv, true)) {
window.isNavigationBarContrastEnforced = tv.data != 0
}
if (theme.resolveAttribute(attr.enforceStatusBarContrast, tv, true)) {
window.isStatusBarContrastEnforced = tv.data != 0
}
val decorView = window.decorView as ViewGroup
ThemeUtils.Api31.applyThemesSystemBarAppearance(theme, decorView, tv)
// Fix setDecorFitsSystemWindows being overridden by the SplashScreenView
decorView.setOnHierarchyChangeListener(null)
window.setDecorFitsSystemWindows(mDecorFitWindowInsets)
}
}
}
| apache-2.0 | d87483bb2c2b5e3c1a2866b99d958f92 | 41.622309 | 102 | 0.638522 | 5.47649 | false | false | false | false |
jkennethcarino/AnkiEditor | app/src/main/java/com/jkcarino/ankieditor/ui/editor/NoteTypeFieldsContainer.kt | 1 | 4173 | /*
* Copyright (C) 2018 Jhon Kenneth Carino
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jkcarino.ankieditor.ui.editor
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.appcompat.widget.PopupMenu
import com.jkcarino.ankieditor.R
import kotlinx.android.synthetic.main.item_note_type_field.view.*
class NoteTypeFieldsContainer @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayoutCompat(context, attrs, defStyleAttr) {
var onFieldOptionsClickListener: OnFieldOptionsClickListener? = null
val fieldsText: Array<String?>
get() {
val totalFields = childCount
val fields = arrayOfNulls<String>(totalFields)
for (i in 0 until totalFields) {
fields[i] = getChildAt(i).note_field_edittext.fieldText
}
return fields
}
fun addFields(fields: Array<String>) {
val inflater = LayoutInflater.from(context)
removeAllViews()
for (field in fields.indices) {
val view = inflater.inflate(R.layout.item_note_type_field, null)
// Set floating label
val fieldHint = view.note_field_til.apply { hint = fields[field] }
val fieldEditText = view.note_field_edittext.apply { tag = field }
view.note_field_options.setOnClickListener {
val index = fieldEditText.tag as Int
val text = fieldEditText.fieldText
PopupMenu(context, it).apply {
menuInflater.inflate(R.menu.menu_field_options, menu)
setOnMenuItemClickListener { item ->
val id = item.itemId
when (id) {
R.id.menu_cloze_deletion -> {
val fieldText = fieldEditText.text.toString()
val selectionStart = fieldEditText.selectionStart
val selectionEnd = fieldEditText.selectionEnd
onFieldOptionsClickListener?.onClozeDeletionClick(
index, fieldText, selectionStart, selectionEnd)
}
R.id.menu_advanced_editor -> {
onFieldOptionsClickListener?.onAdvancedEditorClick(
index, fieldHint.hint.toString(), text
)
}
}
true
}
}.show()
}
addView(view)
}
}
fun setFieldText(index: Int, text: String) {
if (childCount > 0) {
findViewWithTag<NoteTypeFieldEditText>(index).apply {
fieldText = text
requestFocus()
}
}
}
fun clearFields() {
(0 until childCount)
.map { getChildAt(it).note_field_edittext }
.forEach { it.text = null }
// Set the focus to the first field
getChildAt(0).note_field_edittext.requestFocus()
}
interface OnFieldOptionsClickListener {
fun onClozeDeletionClick(index: Int, text: String, selectionStart: Int, selectionEnd: Int)
fun onAdvancedEditorClick(index: Int, fieldName: String, text: String)
}
}
| gpl-3.0 | 66cf0a3396f57519d930d0ecc9440086 | 34.974138 | 98 | 0.583273 | 5.15822 | false | false | false | false |
Passw/Kotlin | hello.kt | 1 | 931 | package my.demo
// http://kotlinlang.org/docs/tutorials/command-line.html
fun main(args: Array<String>) {
if (args.size == 0) return
println("First argument: ${args[0]}")
println("Hello, World!")
System.out.println("Java, Hello Wrold!")
println(sum(3,5))
println(sum1(4,5))
printSum(5, 5)
localVariables()
println(max(3, 99))
println(max2(4, 89))
}
fun sum(a: Int, b: Int): Int {
return a + b
}
fun sum1(a: Int, b: Int) = a + b
fun printSum(a: Int, b: Int) {
println(a + b)
}
fun localVariables() {
val a: Int = 1
val b = 1 // `Int` type is inferred
val c: Int // Type required when no initializer is provided
c = 1 // definite assignment
var x = 5 // `Int` type is inferred
x +=1
println(x)
}
fun max(a: Int, b: Int): Int {
if (a > b)
return a
else
return b
}
fun max2(a: Int, b: Int) = if (a > b) a else b
| gpl-3.0 | fa6559222a60249e743e14aff5fe0449 | 18 | 64 | 0.562836 | 2.909375 | false | false | false | false |
JetBrains/kotlin-native | build-tools/src/main/kotlin/org/jetbrains/kotlin/RunJvmTask.kt | 2 | 5154 | /*
* Copyright 2010-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/LICENSE.txt file.
*/
package org.jetbrains.kotlin
import org.gradle.api.tasks.JavaExec
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.options.Option
import org.gradle.api.tasks.Input
import org.jetbrains.kotlin.benchmark.LogLevel
import org.jetbrains.kotlin.benchmark.Logger
import org.jetbrains.report.json.*
import java.io.ByteArrayOutputStream
import java.io.File
data class ExecParameters(val warmupCount: Int, val repeatCount: Int,
val filterArgs: List<String>, val filterRegexArgs: List<String>,
val verbose: Boolean, val outputFileName: String?)
open class RunJvmTask: JavaExec() {
@Input
@Option(option = "filter", description = "Benchmarks to run (comma-separated)")
var filter: String = ""
@Input
@Option(option = "filterRegex", description = "Benchmarks to run, described by regular expressions (comma-separated)")
var filterRegex: String = ""
@Input
@Option(option = "verbose", description = "Verbose mode of running benchmarks")
var verbose: Boolean = false
@Input
var warmupCount: Int = 0
@Input
var repeatCount: Int = 0
@Input
var repeatingType = BenchmarkRepeatingType.INTERNAL
@Input
var outputFileName: String? = null
private var predefinedArgs: List<String> = emptyList()
private fun executeTask(execParameters: ExecParameters): String {
// Firstly clean arguments.
setArgs(emptyList())
args(predefinedArgs)
args(execParameters.filterArgs)
args(execParameters.filterRegexArgs)
args("-w", execParameters.warmupCount)
args("-r", execParameters.repeatCount)
if (execParameters.verbose) {
args("-v")
}
execParameters.outputFileName?.let { args("-o", outputFileName) }
standardOutput = ByteArrayOutputStream()
super.exec()
return standardOutput.toString()
}
private fun getBenchmarksList(filterArgs: List<String>, filterRegexArgs: List<String>): List<String> {
// Firstly clean arguments.
setArgs(emptyList())
args("list")
standardOutput = ByteArrayOutputStream()
super.exec()
val benchmarks = standardOutput.toString().lines()
val regexes = filterRegexArgs.map { it.toRegex() }
return if (filterArgs.isNotEmpty() || regexes.isNotEmpty()) {
benchmarks.filter { benchmark -> benchmark in filterArgs || regexes.any { it.matches(benchmark) } }
} else benchmarks.filter { !it.isEmpty() }
}
private fun execSeparateBenchmarkRepeatedly(benchmark: String): List<String> {
// Logging with application should be done only in case it controls running benchmarks itself.
// Although it's a responsibility of gradle task.
val logger = if (verbose) Logger(LogLevel.DEBUG) else Logger()
logger.log("Warm up iterations for benchmark $benchmark\n")
for (i in 0.until(warmupCount)) {
executeTask(ExecParameters(0, 1, listOf("-f", benchmark),
emptyList(), false, null))
}
val result = mutableListOf<String>()
logger.log("Running benchmark $benchmark ")
for (i in 0.until(repeatCount)) {
logger.log(".", usePrefix = false)
val benchmarkReport = JsonTreeParser.parse(
executeTask(ExecParameters(0, 1, listOf("-f", benchmark),
emptyList(), false, null)
).removePrefix("[").removeSuffix("]")
).jsonObject
val modifiedBenchmarkReport = JsonObject(HashMap(benchmarkReport.content).apply {
put("repeat", JsonLiteral(i))
put("warmup", JsonLiteral(warmupCount))
})
result.add(modifiedBenchmarkReport.toString())
}
logger.log("\n", usePrefix = false)
return result
}
private fun execBenchmarksRepeatedly(filterArgs: List<String>, filterRegexArgs: List<String>) {
val benchmarksToRun = getBenchmarksList(filterArgs, filterRegexArgs)
val results = benchmarksToRun.flatMap { benchmark ->
execSeparateBenchmarkRepeatedly(benchmark)
}
File(outputFileName).printWriter().use { out ->
out.println("[${results.joinToString(",")}]")
}
}
@TaskAction
override fun exec() {
assert(outputFileName != null) { "Output file name should be always set" }
predefinedArgs = args ?: emptyList()
val filterArgs = filter.splitCommaSeparatedOption("-f")
val filterRegexArgs = filterRegex.splitCommaSeparatedOption("-fr")
when (repeatingType) {
BenchmarkRepeatingType.INTERNAL -> executeTask(
ExecParameters(warmupCount, repeatCount, filterArgs, filterRegexArgs, verbose, outputFileName)
)
BenchmarkRepeatingType.EXTERNAL -> execBenchmarksRepeatedly(filterArgs, filterRegexArgs)
}
}
} | apache-2.0 | a4245462d88abb63dd61123ed5524f9b | 40.24 | 122 | 0.648428 | 4.866856 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableInfo.kt | 1 | 13807 | // 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.callableBuilder
import com.intellij.psi.PsiElement
import com.intellij.util.ArrayUtil
import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode
import org.jetbrains.kotlin.descriptors.ClassDescriptorWithResolutionScopes
import org.jetbrains.kotlin.descriptors.DescriptorVisibility
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassInfo
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.util.getResolvableApproximations
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import java.util.*
/**
* Represents a concrete type or a set of types yet to be inferred from an expression.
*/
abstract class TypeInfo(val variance: Variance) {
object Empty : TypeInfo(Variance.INVARIANT) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = Collections.emptyList()
}
class ByExpression(val expression: KtExpression, variance: Variance) : TypeInfo(variance) {
override fun getPossibleNamesFromExpression(bindingContext: BindingContext): Array<String> {
return KotlinNameSuggester.suggestNamesByExpressionOnly(expression, bindingContext, { true }).toTypedArray()
}
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = expression.guessTypes(
context = builder.currentFileContext,
module = builder.currentFileModule,
pseudocode = try {
builder.pseudocode
} catch (stackException: EmptyStackException) {
val originalElement = builder.config.originalElement
val containingDeclarationForPseudocode = originalElement.containingDeclarationForPseudocode
// copy-pasted from org.jetbrains.kotlin.cfg.pseudocode.PseudocodeUtilsKt.getContainingPseudocode
val enclosingPseudocodeDeclaration = (containingDeclarationForPseudocode as? KtFunctionLiteral)?.let { functionLiteral ->
functionLiteral.parents.firstOrNull { it is KtDeclaration && it !is KtFunctionLiteral } as? KtDeclaration
} ?: containingDeclarationForPseudocode
throw KotlinExceptionWithAttachments(stackException.message, stackException)
.withPsiAttachment("original_expression.txt", originalElement)
.withPsiAttachment("containing_declaration.txt", containingDeclarationForPseudocode)
.withPsiAttachment("enclosing_declaration.txt", enclosingPseudocodeDeclaration)
}
).flatMap { it.getPossibleSupertypes(variance, builder) }
}
class ByTypeReference(val typeReference: KtTypeReference, variance: Variance) : TypeInfo(variance) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
builder.currentFileContext[BindingContext.TYPE, typeReference].getPossibleSupertypes(variance, builder)
}
class ByType(val theType: KotlinType, variance: Variance) : TypeInfo(variance) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
theType.getPossibleSupertypes(variance, builder)
}
class ByReceiverType(variance: Variance) : TypeInfo(variance) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
(builder.placement as CallablePlacement.WithReceiver).receiverTypeCandidate.theType.getPossibleSupertypes(variance, builder)
}
class ByExplicitCandidateTypes(val types: List<KotlinType>) : TypeInfo(Variance.INVARIANT) {
override fun getPossibleTypes(builder: CallableBuilder) = types
}
abstract class DelegatingTypeInfo(val delegate: TypeInfo) : TypeInfo(delegate.variance) {
override val substitutionsAllowed: Boolean = delegate.substitutionsAllowed
override fun getPossibleNamesFromExpression(bindingContext: BindingContext) =
delegate.getPossibleNamesFromExpression(bindingContext)
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = delegate.getPossibleTypes(builder)
}
class NoSubstitutions(delegate: TypeInfo) : DelegatingTypeInfo(delegate) {
override val substitutionsAllowed: Boolean = false
}
class StaticContextRequired(delegate: TypeInfo) : DelegatingTypeInfo(delegate) {
override val staticContextRequired: Boolean = true
}
class OfThis(delegate: TypeInfo) : DelegatingTypeInfo(delegate)
val isOfThis: Boolean
get() = when (this) {
is OfThis -> true
is DelegatingTypeInfo -> delegate.isOfThis
else -> false
}
open val substitutionsAllowed: Boolean = true
open val staticContextRequired: Boolean = false
open fun getPossibleNamesFromExpression(bindingContext: BindingContext): Array<String> = ArrayUtil.EMPTY_STRING_ARRAY
abstract fun getPossibleTypes(builder: CallableBuilder): List<KotlinType>
private fun getScopeForTypeApproximation(config: CallableBuilderConfiguration, placement: CallablePlacement?): LexicalScope? {
if (placement == null) return config.originalElement.getResolutionScope()
val containingElement = when (placement) {
is CallablePlacement.NoReceiver -> {
placement.containingElement
}
is CallablePlacement.WithReceiver -> {
val receiverClassDescriptor =
placement.receiverTypeCandidate.theType.constructor.declarationDescriptor
val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) }
if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile
}
}
return when (containingElement) {
is KtClassOrObject -> (containingElement.resolveToDescriptorIfAny() as? ClassDescriptorWithResolutionScopes)?.scopeForMemberDeclarationResolution
is KtBlockExpression -> (containingElement.statements.firstOrNull() ?: containingElement).getResolutionScope()
is KtElement -> containingElement.containingKtFile.getResolutionScope()
else -> null
}
}
protected fun KotlinType?.getPossibleSupertypes(variance: Variance, callableBuilder: CallableBuilder): List<KotlinType> {
if (this == null || ErrorUtils.containsErrorType(this)) {
return Collections.singletonList(callableBuilder.currentFileModule.builtIns.anyType)
}
val scope = getScopeForTypeApproximation(callableBuilder.config, callableBuilder.placement)
val approximations = getResolvableApproximations(scope, checkTypeParameters = false, allowIntersections = true)
return when (variance) {
Variance.IN_VARIANCE -> approximations.toList()
else -> listOf(approximations.firstOrNull() ?: this)
}
}
}
fun TypeInfo(expressionOfType: KtExpression, variance: Variance): TypeInfo = TypeInfo.ByExpression(expressionOfType, variance)
fun TypeInfo(typeReference: KtTypeReference, variance: Variance): TypeInfo = TypeInfo.ByTypeReference(typeReference, variance)
fun TypeInfo(theType: KotlinType, variance: Variance): TypeInfo = TypeInfo.ByType(theType, variance)
fun TypeInfo.noSubstitutions(): TypeInfo = (this as? TypeInfo.NoSubstitutions) ?: TypeInfo.NoSubstitutions(this)
fun TypeInfo.forceNotNull(): TypeInfo {
class ForcedNotNull(delegate: TypeInfo) : TypeInfo.DelegatingTypeInfo(delegate) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
super.getPossibleTypes(builder).map { it.makeNotNullable() }
}
return (this as? ForcedNotNull) ?: ForcedNotNull(this)
}
fun TypeInfo.ofThis() = TypeInfo.OfThis(this)
/**
* Encapsulates information about a function parameter that is going to be created.
*/
class ParameterInfo(
val typeInfo: TypeInfo,
val nameSuggestions: List<String>
) {
constructor(typeInfo: TypeInfo, preferredName: String? = null) : this(typeInfo, listOfNotNull(preferredName))
}
enum class CallableKind {
FUNCTION,
CLASS_WITH_PRIMARY_CONSTRUCTOR,
CONSTRUCTOR,
PROPERTY
}
abstract class CallableInfo(
val name: String,
val receiverTypeInfo: TypeInfo,
val returnTypeInfo: TypeInfo,
val possibleContainers: List<KtElement>,
val typeParameterInfos: List<TypeInfo>,
val isForCompanion: Boolean = false,
val modifierList: KtModifierList? = null
) {
abstract val kind: CallableKind
abstract val parameterInfos: List<ParameterInfo>
val isAbstract get() = modifierList?.hasModifier(KtTokens.ABSTRACT_KEYWORD) == true
abstract fun copy(
receiverTypeInfo: TypeInfo = this.receiverTypeInfo,
possibleContainers: List<KtElement> = this.possibleContainers,
modifierList: KtModifierList? = this.modifierList
): CallableInfo
}
class FunctionInfo(
name: String,
receiverTypeInfo: TypeInfo,
returnTypeInfo: TypeInfo,
possibleContainers: List<KtElement> = Collections.emptyList(),
override val parameterInfos: List<ParameterInfo> = Collections.emptyList(),
typeParameterInfos: List<TypeInfo> = Collections.emptyList(),
isForCompanion: Boolean = false,
modifierList: KtModifierList? = null,
val preferEmptyBody: Boolean = false
) : CallableInfo(name, receiverTypeInfo, returnTypeInfo, possibleContainers, typeParameterInfos, isForCompanion, modifierList) {
override val kind: CallableKind get() = CallableKind.FUNCTION
override fun copy(
receiverTypeInfo: TypeInfo,
possibleContainers: List<KtElement>,
modifierList: KtModifierList?
) = FunctionInfo(
name,
receiverTypeInfo,
returnTypeInfo,
possibleContainers,
parameterInfos,
typeParameterInfos,
isForCompanion,
modifierList
)
}
class ClassWithPrimaryConstructorInfo(
val classInfo: ClassInfo,
expectedTypeInfo: TypeInfo,
modifierList: KtModifierList? = null,
val primaryConstructorVisibility: DescriptorVisibility? = null
) : CallableInfo(
classInfo.name,
TypeInfo.Empty,
expectedTypeInfo.forceNotNull(),
Collections.emptyList(),
classInfo.typeArguments,
false,
modifierList = modifierList
) {
override val kind: CallableKind get() = CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR
override val parameterInfos: List<ParameterInfo> get() = classInfo.parameterInfos
override fun copy(
receiverTypeInfo: TypeInfo,
possibleContainers: List<KtElement>,
modifierList: KtModifierList?
) = throw UnsupportedOperationException()
}
class ConstructorInfo(
override val parameterInfos: List<ParameterInfo>,
val targetClass: PsiElement,
val isPrimary: Boolean = false,
modifierList: KtModifierList? = null,
val withBody: Boolean = false
) : CallableInfo("", TypeInfo.Empty, TypeInfo.Empty, Collections.emptyList(), Collections.emptyList(), false, modifierList = modifierList) {
override val kind: CallableKind get() = CallableKind.CONSTRUCTOR
override fun copy(
receiverTypeInfo: TypeInfo,
possibleContainers: List<KtElement>,
modifierList: KtModifierList?
) = throw UnsupportedOperationException()
}
class PropertyInfo(
name: String,
receiverTypeInfo: TypeInfo,
returnTypeInfo: TypeInfo,
val writable: Boolean,
possibleContainers: List<KtElement> = Collections.emptyList(),
typeParameterInfos: List<TypeInfo> = Collections.emptyList(),
val isLateinitPreferred: Boolean = false,
val isConst: Boolean = false,
isForCompanion: Boolean = false,
val annotations: List<KtAnnotationEntry> = emptyList(),
modifierList: KtModifierList? = null,
val initializer: KtExpression? = null
) : CallableInfo(name, receiverTypeInfo, returnTypeInfo, possibleContainers, typeParameterInfos, isForCompanion, modifierList) {
override val kind: CallableKind get() = CallableKind.PROPERTY
override val parameterInfos: List<ParameterInfo> get() = Collections.emptyList()
override fun copy(
receiverTypeInfo: TypeInfo,
possibleContainers: List<KtElement>,
modifierList: KtModifierList?
) = copyProperty(receiverTypeInfo, possibleContainers, modifierList)
fun copyProperty(
receiverTypeInfo: TypeInfo = this.receiverTypeInfo,
possibleContainers: List<KtElement> = this.possibleContainers,
modifierList: KtModifierList? = this.modifierList,
isLateinitPreferred: Boolean = this.isLateinitPreferred
) = PropertyInfo(
name,
receiverTypeInfo,
returnTypeInfo,
writable,
possibleContainers,
typeParameterInfos,
isConst,
isLateinitPreferred,
isForCompanion,
annotations,
modifierList,
initializer
)
}
| apache-2.0 | 650767c1b2058472e35251e70baa1f36 | 42.971338 | 158 | 0.734338 | 5.656288 | false | false | false | false |
NordicSemiconductor/Android-DFU-Library | lib_storage/src/main/java/no/nordicsemi/android/dfu/storage/ExternalFileDataSource.kt | 1 | 4029 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.dfu.storage
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.os.Environment
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ExternalFileDataSource @Inject internal constructor(
@ApplicationContext
private val context: Context,
private val parser: FileNameParser
) {
private val _fileResource = MutableStateFlow<FileResource?>(null)
val fileResource = _fileResource.asStateFlow()
private val downloadManger = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
private var downloadID: Long? = null
private val onDownloadCompleteReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent) {
val id: Long = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
if (downloadID == id) {
_fileResource.value = downloadManger.getUriForDownloadedFile(id)?.let {
FileDownloaded(it)
} ?: FileError
}
}
}
init {
context.registerReceiver(
onDownloadCompleteReceiver,
IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
)
}
fun download(url: String) {
if (isRunning()) {
return
}
_fileResource.value = LoadingFile
val request: DownloadManager.Request = DownloadManager.Request(Uri.parse(url))
request.setTitle(parser.parseName(url))
request.setDescription(context.getString(R.string.storage_notification_description))
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
@Suppress("DEPRECATION")
request.allowScanningByMediaScanner()
}
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, parser.parseName(url))
downloadID = downloadManger.enqueue(request)
}
private fun isRunning(): Boolean {
return fileResource.value is LoadingFile
}
}
| bsd-3-clause | e80d5af13c11509e2f3fcd33ac5fb5df | 37.371429 | 105 | 0.734674 | 4.949631 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/intention/impl/preview/IntentionPreviewPopupUpdateProcessor.kt | 2 | 9233 | // 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.codeInsight.intention.impl.preview
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.impl.preview.IntentionPreviewComponent.Companion.LOADING_PREVIEW
import com.intellij.codeInsight.intention.impl.preview.IntentionPreviewComponent.Companion.NO_PREVIEW
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo.Html
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.actionSystem.ShortcutSet
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.SoftWrapChangeListener
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiFile
import com.intellij.ui.ScreenUtil
import com.intellij.ui.popup.PopupPositionManager.Position.LEFT
import com.intellij.ui.popup.PopupPositionManager.Position.RIGHT
import com.intellij.ui.popup.PopupPositionManager.PositionAdjuster
import com.intellij.ui.popup.PopupUpdateProcessor
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.TestOnly
import java.awt.Dimension
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import javax.swing.JWindow
import kotlin.math.max
import kotlin.math.min
class IntentionPreviewPopupUpdateProcessor(private val project: Project,
private val originalFile: PsiFile,
private val originalEditor: Editor) : PopupUpdateProcessor(project) {
private var index: Int = LOADING_PREVIEW
private var show = false
private var originalPopup : JBPopup? = null
private val editorsToRelease = mutableListOf<EditorEx>()
private lateinit var popup: JBPopup
private lateinit var component: IntentionPreviewComponent
private var justActivated: Boolean = false
private val popupWindow: JWindow?
get() = UIUtil.getParentOfType(JWindow::class.java, popup.content)
override fun updatePopup(intentionAction: Any?) {
if (!show) return
if (!::popup.isInitialized || popup.isDisposed) {
val origPopup = originalPopup
if (origPopup == null || origPopup.isDisposed) return
component = IntentionPreviewComponent(origPopup)
component.multiPanel.select(LOADING_PREVIEW, true)
popup = JBPopupFactory.getInstance().createComponentPopupBuilder(component, null)
.setCancelCallback { cancel() }
.setCancelKeyEnabled(false)
.setShowBorder(false)
.addUserData(IntentionPreviewPopupKey())
.createPopup()
component.addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
var size = popup.size
val key = component.multiPanel.key
if (key != NO_PREVIEW) {
size = Dimension(size.width.coerceAtLeast(MIN_WIDTH), size.height)
}
popup.content.preferredSize = size
adjustPosition(originalPopup)
popup.size = size
}
})
adjustPosition(originalPopup)
}
val value = component.multiPanel.getValue(index, false)
if (value != null) {
select(index)
return
}
val action = intentionAction as IntentionAction
component.startLoading()
ReadAction.nonBlocking(
IntentionPreviewComputable(project, action, originalFile, originalEditor))
.expireWith(popup)
.coalesceBy(this)
.finishOnUiThread(ModalityState.defaultModalityState()) { renderPreview(it)}
.submit(AppExecutorUtil.getAppExecutorService())
}
private fun adjustPosition(originalPopup: JBPopup?) {
if (originalPopup != null && originalPopup.content.isShowing) {
PositionAdjuster(originalPopup.content).adjust(popup, RIGHT, LEFT)
}
}
private fun renderPreview(result: IntentionPreviewInfo) {
when (result) {
is IntentionPreviewDiffResult -> {
val editors = IntentionPreviewModel.createEditors(project, result)
if (editors.isEmpty()) {
selectNoPreview()
return
}
editorsToRelease.addAll(editors)
select(index, editors)
}
is Html -> {
select(index, html = result)
}
else -> {
selectNoPreview()
}
}
}
private fun selectNoPreview() {
if (justActivated) {
select(NO_PREVIEW)
}
else {
popupWindow?.isVisible = false
}
}
fun setup(popup: JBPopup, parentIndex: Int) {
index = parentIndex
originalPopup = popup
}
fun isShown() = show && popupWindow?.isVisible != false
fun hide() {
if (::popup.isInitialized && !popup.isDisposed) {
popup.cancel()
}
}
fun show() {
show = true
}
private fun cancel(): Boolean {
editorsToRelease.forEach { editor -> EditorFactory.getInstance().releaseEditor(editor) }
editorsToRelease.clear()
component.removeAll()
show = false
return true
}
private fun select(index: Int, editors: List<EditorEx> = emptyList(), @NlsSafe html: Html? = null) {
justActivated = false
popupWindow?.isVisible = true
component.stopLoading()
component.editors = editors
component.html = html
component.multiPanel.select(index, true)
val size = component.preferredSize
val location = popup.locationOnScreen
val screen = ScreenUtil.getScreenRectangle(location)
if (screen != null) {
var delta = screen.width + screen.x - location.x
val content = originalPopup?.content
val origLocation = if (content?.isShowing == true) content.locationOnScreen else null
// On the left side of the original popup: avoid overlap
if (origLocation != null && location.x < origLocation.x) {
delta = delta.coerceAtMost(origLocation.x - screen.x - PositionAdjuster.DEFAULT_GAP)
}
size.width = size.width.coerceAtMost(delta)
}
component.editors.forEach {
it.softWrapModel.addSoftWrapChangeListener(object : SoftWrapChangeListener {
override fun recalculationEnds() {
val height = (it as EditorImpl).offsetToXY(it.document.textLength).y + it.lineHeight + 6
it.component.preferredSize = Dimension(it.component.preferredSize.width, min(height, MAX_HEIGHT))
it.component.parent.invalidate()
popup.pack(true, true)
}
override fun softWrapsChanged() {}
})
it.component.preferredSize = Dimension(max(size.width, MIN_WIDTH), min(it.component.preferredSize.height, MAX_HEIGHT))
}
popup.pack(true, true)
}
/**
* Call when process is just activated via hotkey
*/
fun activate() {
justActivated = true
}
companion object {
internal const val MAX_HEIGHT = 300
internal const val MIN_WIDTH = 300
fun getShortcutText(): String = KeymapUtil.getPreferredShortcutText(getShortcutSet().shortcuts)
fun getShortcutSet(): ShortcutSet = KeymapUtil.getActiveKeymapShortcuts(IdeActions.ACTION_QUICK_JAVADOC)
@TestOnly
@JvmStatic
fun getPreviewText(project: Project,
action: IntentionAction,
originalFile: PsiFile,
originalEditor: Editor): String? {
return (getPreviewInfo(project, action, originalFile, originalEditor) as? IntentionPreviewDiffResult)?.psiFile?.text
}
/**
* Returns content of preview:
* if it's diff then new content is returned
* if it's HTML then text representation is returned
*/
@TestOnly
@JvmStatic
fun getPreviewContent(project: Project,
action: IntentionAction,
originalFile: PsiFile,
originalEditor: Editor): String {
return when(val info = getPreviewInfo(project, action, originalFile, originalEditor)) {
is IntentionPreviewDiffResult -> info.psiFile.text
is Html -> info.content().toString()
else -> ""
}
}
@TestOnly
@JvmStatic
fun getPreviewInfo(project: Project,
action: IntentionAction,
originalFile: PsiFile,
originalEditor: Editor): IntentionPreviewInfo =
ProgressManager.getInstance().runProcess<IntentionPreviewInfo>(
{ IntentionPreviewComputable(project, action, originalFile, originalEditor).generatePreview() },
EmptyProgressIndicator()) ?: IntentionPreviewInfo.EMPTY
}
internal class IntentionPreviewPopupKey
} | apache-2.0 | 85bf2121ad3bc2d65220f184d9799249 | 34.515385 | 140 | 0.700639 | 4.856917 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeMetaInfo/CodeMetaInfoRenderer.kt | 1 | 3998 | // 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.codeMetaInfo
import com.intellij.util.containers.Stack
import org.jetbrains.kotlin.idea.codeMetaInfo.models.CodeMetaInfo
import java.io.File
object CodeMetaInfoRenderer {
fun renderTagsToText(codeMetaInfos: List<CodeMetaInfo>, originalText: String): StringBuilder {
return StringBuilder().apply {
renderTagsToText(this, codeMetaInfos, originalText)
}
}
fun renderTagsToText(builder: StringBuilder, codeMetaInfos: List<CodeMetaInfo>, originalText: String) {
if (codeMetaInfos.isEmpty()) {
builder.append(originalText)
return
}
val sortedMetaInfos = getSortedCodeMetaInfos(codeMetaInfos).groupBy { it.start }
val opened = Stack<CodeMetaInfo>()
for ((i, c) in originalText.withIndex()) {
processMetaInfosStartedAtOffset(i, sortedMetaInfos, opened, builder)
builder.append(c)
}
val lastSymbolIsNewLine = builder.last() == '\n'
if (lastSymbolIsNewLine) {
builder.deleteCharAt(builder.length - 1)
}
processMetaInfosStartedAtOffset(originalText.length, sortedMetaInfos, opened, builder)
if (lastSymbolIsNewLine) {
builder.appendLine()
}
}
private fun processMetaInfosStartedAtOffset(
offset: Int,
sortedMetaInfos: Map<Int, List<CodeMetaInfo>>,
opened: Stack<CodeMetaInfo>,
builder: StringBuilder
) {
checkOpenedAndCloseStringIfNeeded(opened, offset, builder)
val matchedCodeMetaInfos = sortedMetaInfos[offset] ?: emptyList()
if (matchedCodeMetaInfos.isNotEmpty()) {
openStartTag(builder)
val iterator = matchedCodeMetaInfos.listIterator()
var current: CodeMetaInfo? = iterator.next()
while (current != null) {
val next: CodeMetaInfo? = if (iterator.hasNext()) iterator.next() else null
opened.push(current)
builder.append(current.asString())
when {
next == null ->
closeStartTag(builder)
next.end == current.end ->
builder.append(", ")
else ->
closeStartAndOpenNewTag(builder)
}
current = next
}
}
// Here we need to handle meta infos which has start == end and close them immediately
checkOpenedAndCloseStringIfNeeded(opened, offset, builder)
}
private val metaInfoComparator = (compareBy<CodeMetaInfo> { it.start } then compareByDescending { it.end }) then compareBy { it.tag }
private fun getSortedCodeMetaInfos(metaInfos: Collection<CodeMetaInfo>): List<CodeMetaInfo> {
return metaInfos.sortedWith(metaInfoComparator)
}
private fun closeString(result: StringBuilder) = result.append("<!>")
private fun openStartTag(result: StringBuilder) = result.append("<!")
private fun closeStartTag(result: StringBuilder) = result.append("!>")
private fun closeStartAndOpenNewTag(result: StringBuilder) = result.append("!><!")
private fun checkOpenedAndCloseStringIfNeeded(opened: Stack<CodeMetaInfo>, end: Int, result: StringBuilder) {
var prev: CodeMetaInfo? = null
while (!opened.isEmpty() && end == opened.peek().end) {
if (prev == null || prev.start != opened.peek().start)
closeString(result)
prev = opened.pop()
}
}
}
fun clearFileFromDiagnosticMarkup(file: File) {
val text = file.readText()
val cleanText = clearTextFromDiagnosticMarkup(text)
file.writeText(cleanText)
}
fun clearTextFromDiagnosticMarkup(text: String): String = text.replace(CodeMetaInfoParser.openingOrClosingRegex, "") | apache-2.0 | e3635f4a96a48d9b591cbdf9e043e3fd | 40.226804 | 158 | 0.643572 | 4.941904 | false | false | false | false |
GoogleContainerTools/google-container-tools-intellij | core/src/test/kotlin/com/google/container/tools/core/analytics/UsageTrackerManagerServiceTest.kt | 1 | 3529 | /*
* Copyright 2018 Google Inc. All Rights Reserved.
*
* 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.container.tools.core.analytics
import com.google.common.truth.Truth.assertThat
import com.google.container.tools.core.properties.PluginPropertiesFileReader
import com.google.container.tools.test.ContainerToolsRule
import com.google.container.tools.test.TestService
import com.intellij.ide.util.PropertiesComponent
import io.mockk.every
import io.mockk.impl.annotations.MockK
import org.junit.Before
import org.junit.Rule
import org.junit.Test
/**
* Tests for [UsageTrackerManagerService].
*/
class UsageTrackerManagerServiceTest {
@get:Rule
val containerToolsRule = ContainerToolsRule(this)
@TestService
@MockK
private lateinit var propertyReader: PluginPropertiesFileReader
@MockK
private lateinit var trackingPreferenceProperty: PropertiesComponent
private lateinit var usageTrackerManagerService: UsageTrackerManagerService
@Before
fun setUp() {
usageTrackerManagerService = UsageTrackerManagerService(trackingPreferenceProperty)
}
@Test
fun `usage tracking is not available and not enabled in unit test mode`() {
// Set the analytics ID to a proper value
val analyticsId = "UA-12345"
mockAnalyticsId(analyticsId)
assertThat(usageTrackerManagerService.isUsageTrackingAvailable()).isFalse()
assertThat(usageTrackerManagerService.isUsageTrackingEnabled()).isFalse()
}
@Test
fun `when user data tracking preference is stored true then tracking is opted in`() {
every {
trackingPreferenceProperty.getBoolean(
"GOOGLE_CLOUD_TOOLS_USAGE_TRACKER_OPT_IN",
false
)
} answers { true }
assertThat(usageTrackerManagerService.isTrackingOptedIn()).isTrue()
}
@Test
fun `when user data tracking preference is stored false then tracking is not opted in`() {
every {
trackingPreferenceProperty.getBoolean(
"GOOGLE_CLOUD_TOOLS_USAGE_TRACKER_OPT_IN",
false
)
} answers { false }
assertThat(usageTrackerManagerService.isTrackingOptedIn()).isFalse()
}
@Test
fun `get analytics ID when ID has been substituted returns analytics ID`() {
val analyticsId = "UA-12345"
mockAnalyticsId(analyticsId)
assertThat(usageTrackerManagerService.getAnalyticsId()).isEqualTo(analyticsId)
}
@Test
fun `get analytics ID when property placeholder has not been substituted returns null`() {
val analyticsIdPlaceholder = "\${analyticsId}"
every { propertyReader.getPropertyValue("analytics.id") } answers { analyticsIdPlaceholder }
assertThat(usageTrackerManagerService.getAnalyticsId()).isNull()
}
private fun mockAnalyticsId(analyticsId: String) {
every { propertyReader.getPropertyValue("analytics.id") } answers { analyticsId }
}
}
| apache-2.0 | 0dde4627de0c1d6a0b700ed1bbf1df39 | 32.932692 | 100 | 0.714083 | 5.012784 | false | true | false | false |
Yorxxx/played-next-kotlin | app/src/androidTest/java/com/piticlistudio/playednext/data/repository/datasource/room/genre/RoomGenreServiceTest.kt | 1 | 4214 | package com.piticlistudio.playednext.data.repository.datasource.room.genre
import android.arch.core.executor.testing.InstantTaskExecutorRule
import android.arch.persistence.room.Room
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import com.piticlistudio.playednext.data.AppDatabase
import com.piticlistudio.playednext.data.entity.room.RoomGameGenre
import com.piticlistudio.playednext.factory.DomainFactory
import junit.framework.Assert
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
internal class RoomGenreServiceTest {
@JvmField
@Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
private var database: AppDatabase? = null
@Before
fun setUp() {
database = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(), AppDatabase::class.java)
.allowMainThreadQueries()
.build()
}
@Test
fun insertShouldStoreData() {
val data = DomainFactory.makeRoomGenre()
val result = database?.genreRoom()?.insert(data)
Assert.assertNotNull(result)
Assert.assertEquals(data.id, result!!.toInt())
}
fun insertShouldIgnoreIfAlreadyStored() {
val data = DomainFactory.makeRoomGenre()
val id = database?.genreRoom()?.insert(data)
val id2 = database?.genreRoom()?.insert(data)
Assert.assertTrue(id!! > 0L)
Assert.assertEquals(0L, id2)
}
@Test
fun insertGameGenreShouldStoreData() {
val genre = DomainFactory.makeRoomGenre()
val game = DomainFactory.makeGameCache()
val data = RoomGameGenre(game.id, genre.id)
database?.gamesDao()?.insert(game)
database?.genreRoom()?.insert(genre)
val result = database?.genreRoom()?.insertGameGenre(data)
Assert.assertNotNull(result)
Assert.assertTrue(result!! > 0)
}
@Test
fun insertGameDeveloperShouldReplaceDataOnConflict() {
val genre = DomainFactory.makeRoomGenre()
val game = DomainFactory.makeGameCache()
val data = RoomGameGenre(game.id, genre.id)
database?.gamesDao()?.insert(game)
database?.genreRoom()?.insert(genre)
database?.genreRoom()?.insertGameGenre(data)
val result = database?.genreRoom()?.insertGameGenre(data)
Assert.assertNotNull(result)
Assert.assertTrue(result!! > 0)
}
@Test
fun findForGameShouldReturnData() {
val game = DomainFactory.makeGameCache()
val game2 = DomainFactory.makeGameCache()
val genre1 = DomainFactory.makeRoomGenre()
val genre2 = DomainFactory.makeRoomGenre()
val data = RoomGameGenre(game.id, genre1.id)
val data2 = RoomGameGenre(game.id, genre2.id)
val data3 = RoomGameGenre(game2.id, genre1.id)
database?.gamesDao()?.insert(game)
database?.gamesDao()?.insert(game2)
database?.genreRoom()?.insert(genre1)
database?.genreRoom()?.insert(genre2)
database?.genreRoom()?.insertGameGenre(data)
database?.genreRoom()?.insertGameGenre(data2)
database?.genreRoom()?.insertGameGenre(data3)
// Act
val observer = database?.genreRoom()?.findForGame(game.id)?.test()
Assert.assertNotNull(observer)
observer?.apply {
assertNoErrors()
assertValueCount(1)
assertNotComplete()
assertValue {
it.size == 2 && it.contains(genre1) && it.contains(genre2)
}
}
}
@Test
fun findForGameShouldReturnEmptyListWhenNoMatches() {
val game = DomainFactory.makeGameCache()
database?.gamesDao()?.insert(game)
// Act
// Act
val observer = database?.genreRoom()?.findForGame(game.id)?.test()
Assert.assertNotNull(observer)
observer?.apply {
assertNoErrors()
assertValueCount(1)
assertNotComplete()
assertValue { it.isEmpty() }
}
}
@After
fun tearDown() {
database?.close()
}
} | mit | 994185615f2ec2d603be5515e4ddd11c | 29.323741 | 110 | 0.655434 | 4.794084 | false | true | false | false |
badoualy/kotlogram | mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/tl/MTBadServerSalt.kt | 1 | 1174 | package com.github.badoualy.telegram.mtproto.tl
import com.github.badoualy.telegram.tl.StreamUtils.*
import com.github.badoualy.telegram.tl.TLContext
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
class MTBadServerSalt @JvmOverloads constructor(badMsgId: Long = 0, badMsqSeqno: Int = 0, errorCode: Int = 0, var newSalt: Long = 0) : MTBadMessage(badMsgId, badMsqSeqno, errorCode) {
override fun getConstructorId(): Int {
return CONSTRUCTOR_ID
}
@Throws(IOException::class)
override fun serializeBody(stream: OutputStream) {
writeLong(badMsgId, stream)
writeInt(badMsqSeqno, stream)
writeInt(errorCode, stream)
writeLong(newSalt, stream)
}
@Throws(IOException::class)
override fun deserializeBody(stream: InputStream, context: TLContext) {
badMsgId = readLong(stream)
badMsqSeqno = readInt(stream)
errorCode = readInt(stream)
newSalt = readLong(stream)
}
override fun toString(): String {
return "bad_server_salt#edab447b"
}
companion object {
@JvmField
val CONSTRUCTOR_ID = -307542917
}
}
| mit | fbcb621e6e3168de6924cc64fe64c459 | 29.102564 | 183 | 0.691652 | 3.952862 | false | false | false | false |
tekinarslan/RxJavaKotlinSample | app/src/main/java/com/tekinarslan/kotlinrxjavasample/adapter/RecyclerAdapter.kt | 1 | 1600 | package com.tekinarslan.kotlinrxjavasample.adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.tekinarslan.kotlinrxjavasample.R
import com.tekinarslan.kotlinrxjavasample.model.PhotosDataModel
import kotlinx.android.synthetic.main.item_recycler_view.view.*
import java.util.*
/**
* Created by selimtekinarslan on 6/29/2017.
*/
class RecyclerAdapter(var items: ArrayList<PhotosDataModel>) : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
override fun getItemCount(): Int {
return items.size
}
fun setItems(items: List<PhotosDataModel>) {
this.items = items as ArrayList<PhotosDataModel>
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.item_recycler_view, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
items[position].let {
holder?.title?.text = it.title
holder?.subtitle?.text = it.subTitle
Glide.with(holder?.image?.context)
.load(it.thumbnailUrl)
.placeholder(R.mipmap.ic_launcher)
.into(holder?.image)
}
}
class ViewHolder(rootView: View) : RecyclerView.ViewHolder(rootView) {
val card = rootView.card
val title = rootView.title
val subtitle = rootView.subtitle
val image = rootView.image
}
} | apache-2.0 | a02a341cba4857517d584255b09fee37 | 31.673469 | 115 | 0.691875 | 4.532578 | false | false | false | false |
ibinti/intellij-community | java/java-impl/src/com/intellij/psi/impl/JavaPlatformModuleSystem.kt | 3 | 4918 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl
import com.intellij.codeInsight.JavaModuleSystemEx
import com.intellij.codeInsight.JavaModuleSystemEx.ErrorWithFixes
import com.intellij.codeInsight.daemon.JavaErrorMessages
import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil
import com.intellij.codeInsight.daemon.impl.quickfix.AddRequiredModuleFix
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.vfs.jrt.JrtFileSystem
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightJavaModule
import com.intellij.psi.util.PsiUtil
class JavaPlatformModuleSystem : JavaModuleSystemEx {
override fun getName() = "Java Platform Module System"
override fun isAccessible(target: PsiPackage, place: PsiElement) = checkAccess(target, place, true) == null
override fun isAccessible(target: PsiClass, place: PsiElement) = checkAccess(target, place, true) == null
override fun checkAccess(target: PsiPackage, place: PsiElement) = checkAccess(target, place, false)
override fun checkAccess(target: PsiClass, place: PsiElement) = checkAccess(target, place, false)
private fun checkAccess(target: PsiClass, place: PsiElement, quick: Boolean): ErrorWithFixes? {
val useFile = place.containingFile?.originalFile
if (useFile != null && PsiUtil.isLanguageLevel9OrHigher(useFile)) {
val targetFile = target.containingFile
if (targetFile is PsiClassOwner) {
return checkAccess(targetFile, useFile, targetFile.packageName, quick)
}
}
return null
}
private fun checkAccess(target: PsiPackage, place: PsiElement, quick: Boolean): ErrorWithFixes? {
val useFile = place.containingFile?.originalFile
if (useFile != null && PsiUtil.isLanguageLevel9OrHigher(useFile)) {
val useVFile = useFile.virtualFile
if (useVFile != null) {
val index = ProjectFileIndex.getInstance(useFile.project)
val module = index.getModuleForFile(useVFile)
if (module != null) {
val test = index.isInTestSourceContent(useVFile)
val dirs = target.getDirectories(module.getModuleWithDependenciesAndLibrariesScope(test))
if (dirs.isEmpty()) {
return if (quick) ERR else ErrorWithFixes(JavaErrorMessages.message("package.not.found", target.qualifiedName))
}
val error = checkAccess(dirs[0], useFile, target.qualifiedName, quick)
return if (error == null ||
dirs.size > 1 && dirs.asSequence().drop(1).any { checkAccess(it, useFile, target.qualifiedName, true) == null }) null
else error
}
}
}
return null
}
private val ERR = ErrorWithFixes("-")
private fun checkAccess(target: PsiFileSystemItem, place: PsiFileSystemItem, packageName: String, quick: Boolean): ErrorWithFixes? {
val targetModule = JavaModuleGraphUtil.findDescriptorByElement(target)
val useModule = JavaModuleGraphUtil.findDescriptorByElement(place)
if (targetModule != null) {
if (targetModule.originalElement == useModule?.originalElement) {
return null
}
if (useModule == null && targetModule.containingFile?.virtualFile?.fileSystem !is JrtFileSystem) {
return null // a target is not on the mandatory module path
}
if (!(targetModule is LightJavaModule || JavaModuleGraphUtil.exports(targetModule, packageName, useModule))) {
return if (quick) ERR
else if (useModule == null) ErrorWithFixes(JavaErrorMessages.message("module.access.from.unnamed", packageName, targetModule.name))
else ErrorWithFixes(JavaErrorMessages.message("module.access.from.named", packageName, targetModule.name, useModule.name))
}
if (useModule == null) {
return null
}
if (!(targetModule.name == PsiJavaModule.JAVA_BASE || JavaModuleGraphUtil.reads(useModule, targetModule))) {
return if (quick) ERR else ErrorWithFixes(
JavaErrorMessages.message("module.access.does.not.read", packageName, targetModule.name, useModule.name),
listOf(AddRequiredModuleFix(useModule, targetModule.name)))
}
}
else if (useModule != null) {
return if (quick) ERR else ErrorWithFixes(JavaErrorMessages.message("module.access.to.unnamed", packageName, useModule.name))
}
return null
}
} | apache-2.0 | ab3b24a4152f4e172af4c61186e53085 | 44.971963 | 141 | 0.722245 | 4.751691 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/inspections/java/JavaProfilingCodeInspection.kt | 1 | 1755 | /*
* Copyright 2016 Blue Box Ware
*
* 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.gmail.blueboxware.libgdxplugin.inspections.java
import com.gmail.blueboxware.libgdxplugin.message
import com.gmail.blueboxware.libgdxplugin.utils.isProfilingCall
import com.gmail.blueboxware.libgdxplugin.utils.resolveCall
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiMethodCallExpression
class JavaProfilingCodeInspection : LibGDXJavaBaseInspection() {
override fun getStaticDescription() = message("profiling.code.html.description")
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : JavaElementVisitor() {
override fun visitMethodCallExpression(expression: PsiMethodCallExpression?) {
super.visitMethodCallExpression(expression)
if (expression == null) return
val (receiverClass, method) = expression.resolveCall() ?: return
val className = receiverClass.qualifiedName ?: return
if (isProfilingCall(className, method.name)) {
holder.registerProblem(expression, message("profiling.code.problem.descriptor"))
}
}
}
}
| apache-2.0 | 49baa0ee8e07fa68ed61ec2392694824 | 36.340426 | 108 | 0.744729 | 4.888579 | false | false | false | false |
tikivn/android-template | redux/src/main/java/vn/tiki/architecture/redux/Redux.kt | 1 | 1766 | package vn.tiki.architecture.redux
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.ObservableTransformer
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.processors.BehaviorProcessor
import io.reactivex.subjects.PublishSubject
interface Store<State> {
fun getState(): Flowable<State>
fun dispatch(action: Any)
fun destroy()
}
internal class StoreImpl<State>(initialState: State, epics: List<Epic<State>>, debug: Boolean) : Store<State> {
private val actions: PublishSubject<Any> = PublishSubject.create()
private val states: BehaviorProcessor<State> = BehaviorProcessor.createDefault(initialState)
private var disposables: CompositeDisposable = CompositeDisposable()
init {
val getState = { states.value }
val stateTransformer: ObservableTransformer<Any, State> = ObservableTransformer {
it.concatMap { action ->
Observable.concat(epics.map { epic -> epic.involve(Observable.just(action), getState) })
}
}
disposables.add(actions.compose(stateTransformer)
.subscribe(
states::onNext,
Throwable::printStackTrace))
if (debug) {
disposables.add(actions.map { "action = [$it]" }
.subscribe(::println))
disposables.add(states.map { "state = [$it]" }
.subscribe(::println))
}
}
override fun getState(): Flowable<State> {
return states
}
override fun dispatch(action: Any) {
actions.onNext(action)
}
override fun destroy() {
disposables.clear()
}
}
fun <State> createStore(initialState: State,
epics: List<Epic<State>>,
debug: Boolean = false): Store<State> {
return StoreImpl(initialState, epics, debug)
}
| apache-2.0 | 7a158c31d158f6bad6a32883b4127881 | 27.483871 | 111 | 0.686297 | 4.382134 | false | false | false | false |
vjache/klips | src/main/java/org/klips/engine/rete/builder/optimizer/Optimizer.kt | 1 | 4408 | package org.klips.engine.rete.builder.optimizer
import org.klips.engine.Binding
import org.klips.engine.rete.*
import org.klips.engine.rete.builder.StrategyOne
import org.klips.engine.util.Log
import java.util.*
class Optimizer(val engine: StrategyOne) {
fun optimize(nodes: Set<Node>): Set<Node> {
val roots = ArrayList(detectRoots(nodes))
val replaced = mutableSetOf<Node>()
fun step():Boolean {
val index = sortedMapOf<Signature, MutableSet<Tree>>()
roots.forEach {
nodeToTree(it).addToIndex(index)
}
findMaxMatch(index)?.let {
val (t1, t2, b) = it
replace(t1.reteNode, t2.reteNode, b)
roots.remove(t2.reteNode)
replaced.add(t2.reteNode)
return true
}
return false
}
while (step()){}
return replaced
}
// fun optimize1(nodes: Set<Node>): Set<Node> {
//
// val roots = detectRoots(nodes)
//
// val replaced = mutableSetOf<Node>()
//
// roots.forEach { root ->
//
// fun step():Boolean {
// nodeToTree(root).findMaxMatch()?.let {
// val (t1, t2, b) = it
// replace(t1.reteNode, t2.reteNode, b)
// replaced.add(t2.reteNode)
// return true
// }
// return false
// }
//
// while (step()){}
// }
//
// return replaced
// }
private fun nodeToTree(it: Node): Tree {
return when (it) {
is BetaNode -> Fork(it)
is AlphaNode -> Leafs(it)
is ProxyNode -> Rename(it)
else -> throw IllegalArgumentException()
}
}
private fun detectRoots(nodes: Set<Node>): List<Node> {
// Detect non root nodes
val nonRoots = mutableSetOf<Node>().apply {
nodes.forEach { node ->
if (node is BetaNode) {
add(node.left)
add(node.right)
} else add(node)
}
}
// Detect root nodes
val roots = nodes.filter { it !in nonRoots }
return roots
}
fun replace(with: Node, which: Node, binding: Binding) {
// 1. create proxy node ProxyNode
val pnode = engine.createProxyNode(with, binding)
// 2. attach proxy node to 'with'
val consumersRemove = mutableListOf<Consumer>()
which.consumers.forEach { consumer ->
when (consumer) {
is BetaNode -> {
// ASSERT
if (consumer.left != which && consumer.right != which)
throw IllegalArgumentException()
if (consumer.left == which) {
consumer.left = pnode
consumersRemove.add(consumer)
}
if (consumer.right == which) {
consumer.right = pnode
consumersRemove.add(consumer)
}
}
is ProxyNode ->
{
if (consumer.node == which) {
consumer.node = pnode
consumersRemove.add(consumer)
}
}
else ->
throw IllegalArgumentException()
}
}
// Clean consumers
consumersRemove.forEach { which.removeConsumer(it) }
}
fun Tree.addToIndex(index:MutableMap<Signature, MutableSet<Tree>>) {
deepTraverse {
index.getOrPut(signature){
mutableSetOf()
}.add(this)
false
}
}
fun findMaxMatch(index:Map<Signature, MutableSet<Tree>>): Triple<Tree, Tree, Binding>? {
index.values.filter { it.size > 1 }.reversed().forEach { group0 ->
val group = group0.toList()
for(i in 0..group.size-1)
for(j in i+1..group.size-1){
if (group[i].reteNode !== group[j].reteNode) {
group[i].bind(group[j])?.let {
return Triple(group[i], group[j], it)
}
}
}
}
return null
}
} | apache-2.0 | ef4a51d2ca1fa41d981cd5fa0d208e5c | 28.393333 | 92 | 0.469147 | 4.649789 | false | false | false | false |
AndroidDeveloperLB/AutoFitTextView | AutoFitTextViewSample/src/com/example/autofittextviewsample/Main2Activity.kt | 1 | 1692 | package com.example.autofittextviewsample
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import kotlinx.android.synthetic.main.activity_main2.*
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recyclerView.adapter = object : Adapter<ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return object : ViewHolder(LayoutInflater.from(this@Main2Activity).inflate(R.layout.item, parent, false)) {
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val sb = StringBuilder("item:")
for (i in 0..position)
sb.append(Integer.toString(position))
holder.textView.text = sb
}
override fun getItemCount(): Int {
return 50
}
}
}
private open class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal val textView: TextView
init {
textView = itemView.findViewById<View>(android.R.id.text1) as TextView
}
}
}
| apache-2.0 | 4d03a232abe4c3e3d221b2a2ae459820 | 35 | 123 | 0.677896 | 5.065868 | false | false | false | false |
rubensousa/RecyclerViewSnap | app/src/main/java/com/github/rubensousa/recyclerviewsnap/GridActivity.kt | 1 | 1098 | package com.github.rubensousa.recyclerviewsnap
import android.os.Bundle
import android.view.Gravity
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.github.rubensousa.gravitysnaphelper.GravitySnapHelper
import com.github.rubensousa.recyclerviewsnap.adapter.AppAdapter
import com.github.rubensousa.recyclerviewsnap.model.App
class GridActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_grid)
val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
val adapter = AppAdapter(R.layout.adapter_vertical)
val apps = arrayListOf<App>()
repeat(5) {
apps.addAll(MainActivity.getApps())
}
adapter.setItems(apps)
recyclerView.layoutManager = GridLayoutManager(this, 2, RecyclerView.VERTICAL, false)
recyclerView.setHasFixedSize(true)
recyclerView.adapter = adapter
}
}
| apache-2.0 | c7655d333a720b18c90e022a999e2592 | 33.3125 | 93 | 0.756831 | 4.815789 | false | false | false | false |
summerlly/Quiet | app/src/main/java/tech/summerly/quiet/data/netease/result/RecommendSongResultBean.kt | 1 | 12295 | package tech.summerly.quiet.data.netease.result
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
/**
* author : SUMMERLY
* e-mail : [email protected]
* time : 2017/8/24
* desc :
*/
data class RecommendSongResultBean(
@SerializedName("code")
@Expose
val code: Int,
@SerializedName("recommend")
@Expose
val recommend: List<Recommend>? = null
) {
data class Recommend(
@SerializedName("title")
@Expose
val name: String,
@SerializedName("id")
@Expose
val id: Long,
// @SerializedName("alias")
// @Expose
// val alias: List<String>? = null,
@SerializedName("artists")
@Expose
val artists: List<Artist>? = null,
@SerializedName("album")
@Expose
val album: Album,
@SerializedName("duration")
@Expose
val duration: Int,
@SerializedName("commentThreadId")
@Expose
val commentThreadId: String? = null,
@SerializedName("hMusic")
@Expose
val hMusic: MusicQuality? = null,
@SerializedName("mMusic")
@Expose
val mMusic: MusicQuality? = null,
@SerializedName("lMusic")
@Expose
val lMusic: MusicQuality? = null,
@SerializedName("bMusic")
@Expose
val bMusic: MusicQuality? = null,
@SerializedName("mvid")
@Expose
val mvid: Long? = null,
@SerializedName("reason")
@Expose
val reason: String? = null
// @SerializedName("position")
// @Expose
// val position: Long? = null,
// @SerializedName("status")
// @Expose
// val status: Long? = null,
// @SerializedName("fee")
// @Expose
// val fee: Long? = null,
// @SerializedName("copyrightId")
// @Expose
// val copyrightId: Long? = null,
// @SerializedName("disc")
// @Expose
// val disc: String? = null,
// @SerializedName("no")
// @Expose
// val no: Long? = null,
// @SerializedName("starred")
// @Expose
// val starred: Boolean? = null,
// @SerializedName("popularity")
// @Expose
// val popularity: Double? = null,
// @SerializedName("score")
// @Expose
// val score: Long? = null,
// @SerializedName("starredNum")
// @Expose
// val starredNum: Long? = null,
// @SerializedName("playedNum")
// @Expose
// val playedNum: Long? = null,
// @SerializedName("dayPlays")
// @Expose
// val dayPlays: Long? = null,
// @SerializedName("hearTime")
// @Expose
// val hearTime: Long? = null,
// @SerializedName("ringtone")
// @Expose
// val ringtone: Any? = null,
// @SerializedName("crbt")
// @Expose
// val crbt: Any? = null,
// @SerializedName("audition")
// @Expose
// val audition: Any? = null,
// @SerializedName("copyFrom")
// @Expose
// val copyFrom: String? = null,
// @SerializedName("rtUrl")
// @Expose
// val rtUrl: Any? = null,
// @SerializedName("ftype")
// @Expose
// val ftype: Long? = null,
// @SerializedName("rtUrls")
// @Expose
// val rtUrls: List<Any>? = null,
// @SerializedName("copyright")
// @Expose
// val copyright: Long? = null,
// @SerializedName("rtype")
// @Expose
// val rtype: Long? = null,
// @SerializedName("mp3Url")
// @Expose
// val mp3Url: Any? = null,
// @SerializedName("rurl")
// @Expose
// val rurl: Any? = null,
// @SerializedName("privilege")
// @Expose
// val privilege: Privilege? = null,
// @SerializedName("alg")
// @Expose
// val alg: String? = null
)
data class Album(
@SerializedName("title")
@Expose
val name: String,
@SerializedName("id")
@Expose
val id: Long,
@SerializedName("type")
@Expose
val type: String,
@SerializedName("size")
@Expose
val size: Long,
@SerializedName("picId")
@Expose
val picId: Long? = null,
@SerializedName("blurPicUrl")
@Expose
val blurPicUrl: String? = null,
// @SerializedName("companyId")
// @Expose
// val companyId: Long? = null,
// @SerializedName("pic")
// @Expose
// val pic: Long? = null,
@SerializedName("picUrl")
@Expose
val picUrl: String? = null,
@SerializedName("publishTime")
@Expose
val publishTime: Long? = null,
// @SerializedName("description")
// @Expose
// val description: String? = null,
// @SerializedName("tags")
// @Expose
// val tags: String? = null,
// @SerializedName("company")
// @Expose
// val company: Any? = null,
// @SerializedName("briefDesc")
// @Expose
// val briefDesc: String? = null,
// @SerializedName("artist")
// @Expose
// val artist: Artist_? = null,
// @SerializedName("songs")
// @Expose
// val songs: List<Any>? = null,
// @SerializedName("alias")
// @Expose
// val alias: List<Any>? = null,
// @SerializedName("status")
// @Expose
// val status: Long? = null,
// @SerializedName("copyrightId")
// @Expose
// val copyrightId: Long? = null,
// @SerializedName("commentThreadId")
// @Expose
// val commentThreadId: String? = null,
@SerializedName("artists")
@Expose
val artists: List<Artist__>? = null
// @SerializedName("picId_str")
// @Expose
// val picIdStr: String? = null
)
data class Artist(
@SerializedName("title")
@Expose
val name: String,
@SerializedName("id")
@Expose
val id: Long,
@SerializedName("picUrl")
@Expose
val picUrl: String? = null,
@SerializedName("img1v1Url")
@Expose
val img1v1Url: String? = null
// @SerializedName("picId")
// @Expose
// val picId: Long? = null,
// @SerializedName("img1v1Id")
// @Expose
// val img1v1Id: Long? = null,
// @SerializedName("briefDesc")
// @Expose
// val briefDesc: String? = null,
// @SerializedName("albumSize")
// @Expose
// val albumSize: Long? = null,
// @SerializedName("alias")
// @Expose
// val alias: List<Any>? = null
// @SerializedName("trans")
// @Expose
// val trans: String? = null,
// @SerializedName("musicSize")
// @Expose
// val musicSize: Long? = null
)
data class Artist__(
@SerializedName("title")
@Expose
val name: String? = null,
@SerializedName("id")
@Expose
val id: Long? = null,
// @SerializedName("picId")
// @Expose
// val picId: Long? = null,
// @SerializedName("img1v1Id")
// @Expose
// val img1v1Id: Long? = null,
// @SerializedName("briefDesc")
// @Expose
// val briefDesc: String? = null,
@SerializedName("picUrl")
@Expose
val picUrl: String? = null,
@SerializedName("img1v1Url")
@Expose
val img1v1Url: String? = null
// @SerializedName("albumSize")
// @Expose
// val albumSize: Long? = null,
// @SerializedName("alias")
// @Expose
// val alias: List<Any>? = null,
// @SerializedName("trans")
// @Expose
// val trans: String? = null,
// @SerializedName("musicSize")
// @Expose
// val musicSize: Long? = null
)
data class MusicQuality(
@SerializedName("id")
@Expose
val id: Long,
@SerializedName("size")
@Expose
val size: Long? = null,
@SerializedName("extension")
@Expose
val extension: String? = null,
@SerializedName("sr")
@Expose
val sr: Long? = null,
@SerializedName("bitrate")
@Expose
val bitrate: Long? = null,
@SerializedName("playTime")
@Expose
val playTime: Long? = null,
@SerializedName("volumeDelta")
@Expose
val volumeDelta: Double? = null,
@SerializedName("dfsId_str")
@Expose
val dfsIdStr: Any? = null
// @SerializedName("title")
// @Expose
// val title: String? = null,
// @SerializedName("dfsId")
// @Expose
// val dfsId: Long? = null,
)
// data class Artist_(
//
// @SerializedName("title")
// @Expose
// val title: String? = null,
// @SerializedName("id")
// @Expose
// val id: Long? = null,
// @SerializedName("picId")
// @Expose
// val picId: Long? = null,
// @SerializedName("img1v1Id")
// @Expose
// val img1v1Id: Long? = null,
// @SerializedName("briefDesc")
// @Expose
// val briefDesc: String? = null,
// @SerializedName("picUrl")
// @Expose
// val picUrl: String? = null,
// @SerializedName("img1v1Url")
// @Expose
// val img1v1Url: String? = null,
// @SerializedName("albumSize")
// @Expose
// val albumSize: Long? = null,
// @SerializedName("alias")
// @Expose
// val alias: List<Any>? = null,
// @SerializedName("trans")
// @Expose
// val trans: String? = null,
// @SerializedName("musicSize")
// @Expose
// val musicSize: Long? = null
//
// )
//data class Privilege (
//
// @SerializedName("id")
// @Expose
// val id: Long? = null,
// @SerializedName("fee")
// @Expose
// val fee: Long? = null,
// @SerializedName("payed")
// @Expose
// val payed: Long? = null,
// @SerializedName("st")
// @Expose
// val st: Long? = null,
// @SerializedName("pl")
// @Expose
// val pl: Long? = null,
// @SerializedName("dl")
// @Expose
// val dl: Long? = null,
// @SerializedName("sp")
// @Expose
// val sp: Long? = null,
// @SerializedName("cp")
// @Expose
// val cp: Long? = null,
// @SerializedName("subp")
// @Expose
// val subp: Long? = null,
// @SerializedName("cs")
// @Expose
// val cs: Boolean? = null,
// @SerializedName("maxbr")
// @Expose
// val maxbr: Long? = null,
// @SerializedName("fl")
// @Expose
// val fl: Long? = null,
// @SerializedName("toast")
// @Expose
// val toast: Boolean? = null,
// @SerializedName("flag")
// @Expose
// val flag: Long? = null,
//
//)
}
| gpl-2.0 | dd7e8bb3efb09ea51610badb8eb21262 | 28.343675 | 50 | 0.456771 | 4.232358 | false | false | false | false |
CPRTeam/CCIP-Android | app/src/main/java/app/opass/ccip/ui/WifiNetworkAdapter.kt | 1 | 1609 | package app.opass.ccip.ui
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.isGone
import androidx.recyclerview.widget.RecyclerView
import app.opass.ccip.R
import app.opass.ccip.model.WifiNetworkInfo
class WifiNetworkAdapter(
private val items: List<WifiNetworkInfo>,
private val onItemClick: (WifiNetworkInfo) -> Unit
) : RecyclerView.Adapter<WifiNetworkViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WifiNetworkViewHolder =
LayoutInflater.from(parent.context)
.inflate(R.layout.item_wifi_network, parent, false)
.let(::WifiNetworkViewHolder)
.apply {
itemView.setOnClickListener {
val pos = adapterPosition
if (pos != RecyclerView.NO_POSITION) onItemClick(items[pos])
}
}
override fun getItemCount() = items.size
override fun onBindViewHolder(holder: WifiNetworkViewHolder, position: Int) {
val item = items[position]
holder.name.text = item.ssid
val hasPassword = !item.password.isNullOrEmpty()
if (!hasPassword) {
holder.password.isGone = true
return
}
holder.password.text = item.password
holder.password.isGone = false
}
}
class WifiNetworkViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val name: TextView = view.findViewById(R.id.network_name)
val password: TextView = view.findViewById(R.id.network_password)
}
| gpl-3.0 | c560a5c48cf78e9c8bfa2e5dc59427ec | 33.234043 | 94 | 0.680547 | 4.597143 | false | false | false | false |
etesync/android | app/src/main/java/com/etesync/syncadapter/ui/etebase/ItemRevisionsListFragment.kt | 1 | 5721 | package com.etesync.syncadapter.ui.etebase
import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.fragment.app.ListFragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.commit
import androidx.fragment.app.viewModels
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.observe
import com.etebase.client.FetchOptions
import com.etesync.syncadapter.CachedCollection
import com.etesync.syncadapter.CachedItem
import com.etesync.syncadapter.R
import com.etesync.syncadapter.ui.etebase.ListEntriesFragment.Companion.setItemView
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import java.util.*
import java.util.concurrent.Future
class ItemRevisionsListFragment : ListFragment(), AdapterView.OnItemClickListener {
private val model: AccountViewModel by activityViewModels()
private val revisionsModel: RevisionsViewModel by viewModels()
private var state: Parcelable? = null
private lateinit var cachedCollection: CachedCollection
private lateinit var cachedItem: CachedItem
private var emptyTextView: TextView? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.journal_viewer_list, container, false)
//This is instead of setEmptyText() function because of Google bug
//See: https://code.google.com/p/android/issues/detail?id=21742
emptyTextView = view.findViewById<View>(android.R.id.empty) as TextView
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
var restored = false
revisionsModel.loadRevisions(model.value!!, cachedCollection, cachedItem)
revisionsModel.observe(this) {
val entries = it.sortedByDescending { item ->
item.meta.mtime ?: 0
}
val listAdapter = EntriesListAdapter(requireContext(), cachedCollection)
setListAdapter(listAdapter)
listAdapter.addAll(entries)
if(!restored && (state != null)) {
listView.onRestoreInstanceState(state)
restored = true
}
emptyTextView!!.text = getString(R.string.journal_entries_list_empty)
}
listView.onItemClickListener = this
}
override fun onPause() {
state = listView.onSaveInstanceState()
super.onPause()
}
override fun onDestroyView() {
super.onDestroyView()
revisionsModel.cancelLoad()
}
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val item = listAdapter?.getItem(position) as CachedItem
activity?.supportFragmentManager?.commit {
replace(R.id.fragment_container, CollectionItemFragment.newInstance(item))
addToBackStack(null)
}
}
internal inner class EntriesListAdapter(context: Context, val cachedCollection: CachedCollection) : ArrayAdapter<CachedItem>(context, R.layout.journal_viewer_list_item) {
override fun getView(position: Int, _v: View?, parent: ViewGroup): View {
var v = _v
if (v == null)
v = LayoutInflater.from(context).inflate(R.layout.journal_viewer_list_item, parent, false)!!
val item = getItem(position)!!
setItemView(v, cachedCollection.collectionType, item)
/* FIXME: handle entry error:
val entryError = data.select(EntryErrorEntity::class.java).where(EntryErrorEntity.ENTRY.eq(entryEntity)).limit(1).get().firstOrNull()
if (entryError != null) {
val errorIcon = v.findViewById<View>(R.id.error) as ImageView
errorIcon.visibility = View.VISIBLE
}
*/
return v
}
}
companion object {
fun newInstance(cachedCollection: CachedCollection, cachedItem: CachedItem): ItemRevisionsListFragment {
val ret = ItemRevisionsListFragment()
ret.cachedCollection = cachedCollection
ret.cachedItem = cachedItem
return ret
}
}
}
class RevisionsViewModel : ViewModel() {
private val revisions = MutableLiveData<List<CachedItem>>()
private var asyncTask: Future<Unit>? = null
fun loadRevisions(accountCollectionHolder: AccountHolder, cachedCollection: CachedCollection, cachedItem: CachedItem) {
asyncTask = doAsync {
val ret = LinkedList<CachedItem>()
val col = cachedCollection.col
val itemManager = accountCollectionHolder.colMgr.getItemManager(col)
var iterator: String? = null
var done = false
while (!done) {
val chunk = itemManager.itemRevisions(cachedItem.item, FetchOptions().iterator(iterator).limit(30))
iterator = chunk.iterator
done = chunk.isDone
ret.addAll(chunk.data.map { CachedItem(it, it.meta, it.contentString) })
}
uiThread {
revisions.value = ret
}
}
}
fun cancelLoad() {
asyncTask?.cancel(true)
}
fun observe(owner: LifecycleOwner, observer: (List<CachedItem>) -> Unit) =
revisions.observe(owner, observer)
} | gpl-3.0 | 6c149044bfb683180ca40ed0e28a80d5 | 34.987421 | 174 | 0.67698 | 5.014023 | false | false | false | false |
LorittaBot/Loritta | web/embed-editor/embed-editor/src/main/kotlin/net/perfectdreams/loritta/embededitor/editors/EmbedFieldEditor.kt | 1 | 6158 | package net.perfectdreams.loritta.embededitor.editors
import kotlinx.html.*
import kotlinx.html.dom.create
import kotlinx.html.js.onClickFunction
import net.perfectdreams.loritta.embededitor.EmbedEditor
import net.perfectdreams.loritta.embededitor.data.DiscordEmbed
import net.perfectdreams.loritta.embededitor.data.FieldRenderInfo
import net.perfectdreams.loritta.embededitor.generator.EmbedFieldsGenerator
import net.perfectdreams.loritta.embededitor.select
import net.perfectdreams.loritta.embededitor.utils.*
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.HTMLTextAreaElement
import kotlinx.browser.document
object EmbedFieldEditor : EditorBase {
val changeField: ELEMENT_CONFIGURATION = { m, discordMessage, currentElement, renderInfo ->
currentElement.classes += "clickable"
renderInfo as FieldRenderInfo
currentElement.onClickFunction = {
fieldPopup(
discordMessage.embed!!,
renderInfo.field,
false,
m
)
}
}
val addMoreFields: ELEMENT_CONFIGURATION = { m, discordMessage, currentElement, renderInfo ->
val embed = discordMessage.embed!!
if (DiscordEmbed.MAX_FIELD_OBJECTS > embed.fields.size) {
lovelyButton(
"fas fa-grip-lines",
"Adicionar Campo"
) {
fieldPopup(
embed,
DiscordEmbed.Field("owo", "uwu"),
true,
m
)
}
}
}
fun fieldPopup(embed: DiscordEmbed, field: DiscordEmbed.Field, isNew: Boolean, m: EmbedEditor) {
val modal = TingleModal(
TingleOptions(
footer = true
)
)
modal.setContent(
document.create.div {
div {
discordTextArea(m, field.name, "field-name", DiscordEmbed.MAX_FIELD_NAME_LENGTH)
}
div {
discordTextArea(m, field.value, "field-value", DiscordEmbed.MAX_FIELD_VALUE_LENGTH)
}
label {
+ "Inline? "
}
input(InputType.checkBox) {
name = "field-inline"
checked = field.inline
}
}
)
modal.closeMessageButton(
m
) {
m.activeMessage!!.copy(
embed = m.activeMessage!!.embed!!
.copy(
fields = m.activeMessage!!.embed!!.fields.toMutableList().apply {
remove(field)
}
)
)
}
modal.addLovelyFooterButton(
"fas fa-save",
"Salvar"
) {
m.generateMessageAndUpdateJson(
if (isNew) {
m.activeMessage!!.copy(
embed = m.activeMessage!!.embed!!
.copy(
fields = m.activeMessage!!.embed!!.fields.toMutableList().apply {
add(
DiscordEmbed.Field(
visibleModal.select<HTMLTextAreaElement>("[name='field-name']")
.value,
visibleModal.select<HTMLTextAreaElement>("[name='field-value']")
.value,
visibleModal.select<HTMLInputElement>("[name='field-inline']")
.checked
)
)
}
)
)
} else {
m.activeMessage!!.copy(
embed = m.activeMessage!!.embed!!
.copy(
fields = m.activeMessage!!.embed!!.fields.toMutableList().apply {
val indexOf = embed.fields.indexOf(field)
remove(field)
add(
indexOf,
DiscordEmbed.Field(
visibleModal.select<HTMLTextAreaElement>("[name='field-name']")
.value,
visibleModal.select<HTMLTextAreaElement>("[name='field-value']")
.value,
visibleModal.select<HTMLInputElement>("[name='field-inline']")
.checked
)
)
}
)
)
}
)
modal.close()
}
modal.open()
// visibleModal.select<HTMLTextAreaElement>(".text-input").autoResize()
}
} | agpl-3.0 | 172546a7e835765613a7065cf3e80962 | 42.373239 | 132 | 0.368301 | 7.437198 | false | false | false | false |
indy256/codelibrary | kotlin/QuickSort.kt | 1 | 828 | import java.util.Random
import kotlin.system.measureTimeMillis
fun quickSort(a: IntArray, rnd: Random = Random(), low: Int = 0, high: Int = a.size - 1) {
if (low >= high)
return
val separator = a[low + rnd.nextInt(high - low + 1)]
var i = low
var j = high
while (i <= j) {
while (a[i] < separator)
++i
while (a[j] > separator)
--j
if (i <= j) {
a[i] = a[j].also { a[j] = a[i] }
++i
--j
}
}
quickSort(a, rnd, low, j)
quickSort(a, rnd, i, high)
}
// test
fun main() {
val n = 10_000_000L
val rnd = Random()
val a = rnd.ints(n).toArray()
val b = a.sortedArray()
println(measureTimeMillis { quickSort(a, rnd) })
if (!a.contentEquals(b))
throw RuntimeException()
}
| unlicense | 3fd37043eefcfbdcb2bcee233643fe6a | 22 | 90 | 0.501208 | 3.22179 | false | false | false | false |
MikhailMe/serivce-app | ServingClient/app/src/main/java/servingclient/servingclient/GUI/CustomAdapter.kt | 1 | 2241 | package servingclient.servingclient.GUI
import android.widget.ArrayAdapter
import android.widget.TextView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.app.Activity
import android.graphics.Color
import android.util.Log
import android.view.View
import android.widget.ImageView
import servingclient.servingclient.R
class CustomAdapter(private val context: Activity, private val itemname: ArrayList<String>?, private val imgid: Array<Int>)
: ArrayAdapter<String>(context, R.layout.mylist, itemname) {
override fun getView(position: Int, view: View?, parent: ViewGroup): View {
val inflater = context.layoutInflater as LayoutInflater
val rowView = inflater.inflate(R.layout.mylist, null) as View
val txtTitle = rowView.findViewById(R.id.item) as TextView
val imageView = rowView.findViewById(R.id.icon) as ImageView
//imageView.setBackgroundColor(parent.solidColor)
txtTitle.text = itemname?.get(position)
txtTitle.setTextColor(Color.BLACK)
txtTitle.setTextSize(20.0f)
if (itemname != null)
imageView.setImageResource(when (true) {
itemname.get(position).contains("HOT_DOG") -> imgid[0]
itemname.get(position).contains("CHEESEBURGER") -> imgid[1]
itemname.get(position).contains("HAMBURGER") -> imgid[2]
itemname.get(position).contains("HOT_CORN") -> imgid[3]
itemname.get(position).contains("CHIPS") -> imgid[4]
itemname.get(position).contains("COLD_BEER") -> imgid[5]
itemname.get(position).contains("COCA_COLA") -> imgid[6]
itemname.get(position).contains("WATER") -> imgid[7]
itemname.get(position).contains("STEEL_WATER") -> imgid[8]
itemname.get(position).contains("TEA") -> imgid[9]
itemname.get(position).contains("COFFEE") -> imgid[10]
itemname.get(position).contains("JUICE") -> imgid[11]
itemname.get(position).contains("SCARF") -> imgid[12]
itemname.get(position).contains("BALL") -> imgid[13]
else -> imgid[14]
})
return rowView
}
} | gpl-3.0 | d9865f3c1dd4e1d235bfe7e542128cc3 | 41.301887 | 123 | 0.648371 | 4.204503 | false | false | false | false |
mcxiaoke/kotlin-koi | core/src/main/kotlin/com/mcxiaoke/koi/ext/Intent.kt | 1 | 2711 | package com.mcxiaoke.koi.ext
import android.app.Activity
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
/**
* User: mcxiaoke
* Date: 16/1/27
* Time: 11:26
*/
inline fun <reified T : Context> Context.newIntent(): Intent =
Intent(this, T::class.java)
inline fun <reified T : Context> Context.newIntent(flags: Int): Intent {
val intent = newIntent<T>()
intent.flags = flags
return intent
}
inline fun <reified T : Context> Context.newIntent(extras: Bundle): Intent =
newIntent<T>(0, extras)
inline fun <reified T : Context> Context.newIntent(flags: Int, extras: Bundle): Intent {
val intent = newIntent<T>(flags)
intent.putExtras(extras)
return intent
}
inline fun <reified T : Activity> Activity.startActivity(): Unit =
this.startActivity(newIntent<T>())
inline fun <reified T : Activity> Activity.startActivity(flags: Int): Unit =
this.startActivity(newIntent<T>(flags))
inline fun <reified T : Activity> Activity.startActivity(extras: Bundle): Unit =
this.startActivity(newIntent<T>(extras))
inline fun <reified T : Activity> Activity.startActivity(flags: Int, extras: Bundle): Unit =
this.startActivity(newIntent<T>(flags, extras))
inline fun <reified T : Activity> Activity.startActivityForResult(requestCode: Int): Unit =
this.startActivityForResult(newIntent<T>(), requestCode)
inline fun <reified T : Activity> Activity.startActivityForResult(requestCode: Int,
flags: Int): Unit =
this.startActivityForResult(newIntent<T>(flags), requestCode)
inline fun <reified T : Activity> Activity.startActivityForResult(
extras: Bundle, requestCode: Int): Unit =
this.startActivityForResult(newIntent<T>(extras), requestCode)
inline fun <reified T : Activity> Activity.startActivityForResult(
extras: Bundle, requestCode: Int, flags: Int): Unit =
this.startActivityForResult(newIntent<T>(flags, extras), requestCode)
inline fun <reified T : Service> Context.startService(): ComponentName =
this.startService(newIntent<T>())
inline fun <reified T : Service> Context.startService(flags: Int): ComponentName =
this.startService(newIntent<T>(flags))
inline fun <reified T : Service> Context.startService(extras: Bundle): ComponentName =
this.startService(newIntent<T>(extras))
inline fun <reified T : Service> Context.startService(extras: Bundle,
flags: Int): ComponentName
= this.startService(newIntent<T>(flags, extras))
| apache-2.0 | c30e9b067888f88fa893818e6422b72f | 36.136986 | 92 | 0.691258 | 4.358521 | false | false | false | false |
Shynixn/PetBlocks | petblocks-bukkit-plugin/petblocks-bukkit-nms-118R1/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_18_R1/CombinedPathfinder.kt | 1 | 1722 | package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_18_R1
import com.github.shynixn.petblocks.api.business.proxy.PathfinderProxy
import net.minecraft.world.entity.ai.goal.PathfinderGoal
/**
* This pathfinder is a solution to Paper causing normal pathfinders to sometimes get ignored.
*/
class CombinedPathfinder(val pathfinderProxy: Map<PathfinderProxy, Cache>) : PathfinderGoal() {
/**
* Override ShouldExecute.
*/
override fun a(): Boolean {
for (proxy in pathfinderProxy.keys) {
val cache = pathfinderProxy.getValue(proxy)
if (cache.isExecuting) {
val shouldContinue = proxy.shouldGoalContinueExecuting()
if (!shouldContinue) {
proxy.onStopExecuting()
cache.isExecuting = false
} else {
proxy.onExecute()
}
} else {
val shouldExecute = proxy.shouldGoalBeExecuted()
if (shouldExecute) {
proxy.onStartExecuting()
cache.isExecuting = true
proxy.onExecute()
}
}
}
return true
}
/**
* Override continue executing.
*/
override fun b(): Boolean {
return false
}
/**
* Override isInterrupting.
*/
override fun D_(): Boolean {
return true
}
/**
* Override startExecuting.
*/
override fun c() {
}
/**
* Override reset.
*/
override fun d() {
}
/**
* Override update.
*/
override fun e() {
}
class Cache {
var isExecuting = false
}
}
| apache-2.0 | f3474f1a8b8103ad5da88aafb39adf61 | 21.657895 | 95 | 0.533101 | 4.962536 | false | false | false | false |
spark/photon-tinker-android | meshui/src/main/java/io/particle/mesh/ui/setup/ManualCommissioningAddToNetworkFragment.kt | 1 | 3019 | package io.particle.mesh.ui.setup
import android.media.AudioManager
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.VideoView
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.navigation.fragment.findNavController
import com.squareup.phrase.Phrase
import io.particle.android.common.buildRawResourceUri
import io.particle.mesh.common.QATool
import io.particle.mesh.setup.flow.FlowRunnerUiListener
import io.particle.mesh.ui.BaseFlowFragment
import io.particle.mesh.ui.R
import kotlinx.android.synthetic.main.fragment_manual_commissioning_add_to_network.*
class ManualCommissioningAddToNetworkFragment : BaseFlowFragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(
R.layout.fragment_manual_commissioning_add_to_network,
container,
false
)
}
override fun onFragmentReady(activity: FragmentActivity, flowUiListener: FlowRunnerUiListener) {
super.onFragmentReady(activity, flowUiListener)
action_next.setOnClickListener {
// FIXME: this flow logic should live outside the UI
try {
findNavController().navigate(
R.id.action_manualCommissioningAddToNetworkFragment_to_scanCommissionerCodeFragment
)
} catch (ex: Exception) {
// Workaround to avoid this seemingly impossible crash: http://bit.ly/2kTpnIb
val error = IllegalStateException(
"Navigation error, Activity=${activity.javaClass}, isFinishing=${activity.isFinishing}",
ex
)
QATool.report(error)
[email protected]?.finish()
}
}
setup_header_text.text = Phrase.from(view, R.string.add_xenon_to_mesh_network)
.put("product_type", getUserFacingTypeName())
.format()
setUpVideoView(videoView)
}
private fun setUpVideoView(vidView: VideoView) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// stop pausing the user's music when showing the video!
vidView.setAudioFocusRequest(AudioManager.AUDIOFOCUS_NONE)
}
vidView.setVideoURI(activity!!.buildRawResourceUri(R.raw.commissioner_to_listening_mode))
lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
vidView.start()
}
override fun onStop(owner: LifecycleOwner) {
vidView.stopPlayback()
}
})
vidView.setOnPreparedListener { player -> player.isLooping = true }
}
}
| apache-2.0 | f5dbefc673e33aeefa8bbb2ca0830d1e | 34.517647 | 108 | 0.674395 | 4.94918 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/telemetry/FenixProductDetector.kt | 1 | 1585 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.telemetry
import android.content.Context
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import mozilla.components.support.utils.ext.getPackageInfoCompat
object FenixProductDetector {
enum class FenixVersion(val packageName: String) {
FIREFOX("org.mozilla.firefox"),
FIREFOX_NIGHTLY("org.mozilla.fenix"),
FIREFOX_BETA("org.mozilla.firefox_beta"),
}
fun getInstalledFenixVersions(context: Context): List<String> {
val fenixVersions = mutableListOf<String>()
for (product in FenixVersion.values()) {
if (packageIsInstalled(context, product.packageName)) {
fenixVersions.add(product.packageName)
}
}
return fenixVersions
}
fun isFenixDefaultBrowser(defaultBrowser: ActivityInfo?): Boolean {
if (defaultBrowser == null) return false
for (product in FenixVersion.values()) {
if (product.packageName == defaultBrowser.packageName) return true
}
return false
}
private fun packageIsInstalled(context: Context, packageName: String): Boolean {
try {
context.packageManager.getPackageInfoCompat(packageName, 0)
} catch (e: PackageManager.NameNotFoundException) {
return false
}
return true
}
}
| mpl-2.0 | 3ac8220aa3e78f77b6d55c0f39bf2703 | 31.346939 | 84 | 0.672555 | 4.541547 | false | false | false | false |
GyrosWorkshop/WukongAndroid | wukong/src/main/java/com/senorsen/wukong/network/MediaProviderClient.kt | 1 | 1393 | package com.senorsen.wukong.network
import android.util.Log
import com.google.common.net.HttpHeaders
import okhttp3.OkHttpClient
import okhttp3.Request
object MediaProviderClient {
private val TAG = javaClass.simpleName
private val client = OkHttpClient()
fun resolveRedirect(url: String): String {
if (!url.startsWith("http")) return url
val request = Request.Builder()
.head()
.header(HttpHeaders.USER_AGENT, "")
.url(url).build()
client.newCall(request).execute().use { response ->
when {
response.isSuccessful && response.code() == 200 -> {
Log.d(TAG, response.toString())
return response.request().url().toString()
}
else ->
throw HttpClient.InvalidResponseException(response)
}
}
}
fun getMedia(url: String): ByteArray {
val request = Request.Builder()
.header(HttpHeaders.USER_AGENT, "")
.url(url).build()
client.newCall(request).execute().use { response ->
when {
response.isSuccessful ->
return response.body()!!.bytes()
else ->
throw HttpClient.InvalidResponseException(response)
}
}
}
}
| agpl-3.0 | 9e9ad303b105ee5323088a57a4cdf8bd | 29.282609 | 71 | 0.539124 | 5.140221 | false | false | false | false |
android/camera-samples | CameraXVideo/utils/src/main/java/com/example/android/camera/utils/OrientationLiveData.kt | 6 | 3544 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.camera.utils
import android.content.Context
import android.hardware.camera2.CameraCharacteristics
import android.view.OrientationEventListener
import android.view.Surface
import androidx.lifecycle.LiveData
/**
* Calculates closest 90-degree orientation to compensate for the device
* rotation relative to sensor orientation, i.e., allows user to see camera
* frames with the expected orientation.
*/
class OrientationLiveData(
context: Context,
characteristics: CameraCharacteristics
): LiveData<Int>() {
private val listener = object : OrientationEventListener(context.applicationContext) {
override fun onOrientationChanged(orientation: Int) {
val rotation = when {
orientation <= 45 -> Surface.ROTATION_0
orientation <= 135 -> Surface.ROTATION_90
orientation <= 225 -> Surface.ROTATION_180
orientation <= 315 -> Surface.ROTATION_270
else -> Surface.ROTATION_0
}
val relative = computeRelativeRotation(characteristics, rotation)
if (relative != value) postValue(relative)
}
}
override fun onActive() {
super.onActive()
listener.enable()
}
override fun onInactive() {
super.onInactive()
listener.disable()
}
companion object {
/**
* Computes rotation required to transform from the camera sensor orientation to the
* device's current orientation in degrees.
*
* @param characteristics the [CameraCharacteristics] to query for the sensor orientation.
* @param surfaceRotation the current device orientation as a Surface constant
* @return the relative rotation from the camera sensor to the current device orientation.
*/
@JvmStatic
private fun computeRelativeRotation(
characteristics: CameraCharacteristics,
surfaceRotation: Int
): Int {
val sensorOrientationDegrees =
characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)!!
val deviceOrientationDegrees = when (surfaceRotation) {
Surface.ROTATION_0 -> 0
Surface.ROTATION_90 -> 90
Surface.ROTATION_180 -> 180
Surface.ROTATION_270 -> 270
else -> 0
}
// Reverse device orientation for front-facing cameras
val sign = if (characteristics.get(CameraCharacteristics.LENS_FACING) ==
CameraCharacteristics.LENS_FACING_FRONT) 1 else -1
// Calculate desired JPEG orientation relative to camera orientation to make
// the image upright relative to the device orientation
return (sensorOrientationDegrees - (deviceOrientationDegrees * sign) + 360) % 360
}
}
}
| apache-2.0 | f4aeb3db284fcc91e394f2480d3cae0a | 36.305263 | 98 | 0.655192 | 5.353474 | false | false | false | false |
Shashi-Bhushan/General | cp-trials/src/main/kotlin/in/shabhushan/cp_trials/PositionAverages.kt | 1 | 955 | package `in`.shabhushan.cp_trials
object PositionAverages {
fun posAverage(
s: String
) = s.split(", ").let { list ->
var common = 0
(0 until list.size - 1).forEach { row ->
(row + 1 until list.size).forEach { column ->
common += list[row].filterIndexed { index, element ->
element == list[column][index]
}.length
}
}
val total = (list.size.toDouble() * (list.size.toDouble() - 1.0)) / 2.0
common / (total * list.first().length) * 100
}
fun posAverage2(
s: String
) = s.split(", ").let { list ->
val total = list.first().length * (list.size.toDouble() * (list.size.toDouble() - 1.0)) / 2.0
list.mapIndexed { index, string ->
list.drop(index + 1).sumBy { secondString -> string.zip(secondString).count { it.first == it.second } }
}.sum() * 100.0 / total
}
}
| gpl-2.0 | d48ae012a1213950a9919720fc91d1a9 | 29.806452 | 115 | 0.510995 | 3.745098 | false | false | false | false |
google/horologist | network-awareness/src/main/java/com/google/android/horologist/networks/data/Status.kt | 1 | 1473 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.networks.data
import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi
import java.time.Instant
@ExperimentalHorologistNetworksApi
public sealed class Status(public val order: Int) {
@ExperimentalHorologistNetworksApi
public object Available : Status(order = 1) {
override fun toString(): String = "Available"
}
@ExperimentalHorologistNetworksApi
public class Losing(public val instant: Instant) : Status(order = 2) {
override fun toString(): String = "Losing"
}
@ExperimentalHorologistNetworksApi
public object Lost : Status(order = 3) {
override fun toString(): String = "Lost"
}
@ExperimentalHorologistNetworksApi
public object Unknown : Status(order = 4) {
override fun toString(): String = "Unknown"
}
}
| apache-2.0 | be4d30bf3d8b926997d7eaf00d704ec5 | 33.255814 | 79 | 0.727088 | 4.67619 | false | false | false | false |
fython/PackageTracker | mobile/src/main/kotlin/info/papdt/express/helper/ui/dialog/EditCategoryDialog.kt | 1 | 7114 | package info.papdt.express.helper.ui.dialog
import android.annotation.SuppressLint
import android.app.Activity.RESULT_OK
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import info.papdt.express.helper.*
import info.papdt.express.helper.R
import info.papdt.express.helper.dao.SRDatabase
import info.papdt.express.helper.event.EventIntents
import info.papdt.express.helper.model.Category
import info.papdt.express.helper.model.MaterialIcon
import info.papdt.express.helper.ui.ChooseIconActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import moe.feng.kotlinyan.common.*
class EditCategoryDialog : DialogFragment() {
companion object {
const val REASON_EDIT = 0
const val REASON_CREATE = 1
const val EXTRA_REASON = "reason"
const val REQUEST_CODE_CHOOSE_ICON = 20001
fun newCreateDialog(): EditCategoryDialog {
return EditCategoryDialog().apply {
arguments = Bundle().apply {
putInt(EXTRA_REASON, REASON_CREATE)
}
}
}
fun newEditDialog(oldData: Category): EditCategoryDialog {
return EditCategoryDialog().apply {
arguments = Bundle().apply {
putInt(EXTRA_REASON, REASON_EDIT)
putParcelable(EXTRA_OLD_DATA, oldData)
}
}
}
}
private var reason: Int = -1
private lateinit var oldData: Category
private lateinit var data: Category
private lateinit var titleEdit: EditText
private lateinit var iconView: TextView
private var positiveButton: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments!!.let {
reason = it.getInt(EXTRA_REASON, -1)
require(reason == REASON_CREATE || reason == REASON_EDIT)
if (reason == REASON_EDIT) {
oldData = it.getParcelable(EXTRA_OLD_DATA)!!
}
}
if (savedInstanceState == null) {
when (reason) {
REASON_EDIT -> {
data = Category(oldData)
}
REASON_CREATE -> {
data = Category(getString(R.string.category_default_title))
}
}
} else {
data = savedInstanceState.getParcelable(EXTRA_DATA)!!
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelable(EXTRA_DATA, data)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(context).apply {
titleRes = when (reason) {
REASON_CREATE -> R.string.edit_category_dialog_title_for_create
REASON_EDIT -> R.string.edit_category_dialog_title_for_edit
else -> throw IllegalArgumentException()
}
view = createContentView()
positiveButton(R.string.save) { _, _ ->
when (reason) {
REASON_CREATE -> {
sendLocalBroadcast(EventIntents.saveNewCategory(data))
}
REASON_EDIT -> {
sendLocalBroadcast(EventIntents.saveEditCategory(oldData, data))
}
}
}
cancelButton()
if (reason == REASON_EDIT) {
neutralButton(R.string.delete) { _, _ ->
sendLocalBroadcast(EventIntents.requestDeleteCategory(data))
}
}
}.create().apply {
setOnShowListener {
[email protected] = (it as AlertDialog).positiveButton
checkEnabledState()
}
}
}
@SuppressLint("InflateParams")
private fun createContentView(): View {
val view = LayoutInflater.from(context!!).inflate(R.layout.dialog_edit_category, null)
titleEdit = view.findViewById(R.id.category_title_edit)
iconView = view.findViewById(R.id.category_icon_view)
titleEdit.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) {
data.title = s?.toString()?.trim() ?: ""
checkEnabledState()
}
})
iconView.typeface = MaterialIcon.iconTypeface
updateViewValues()
titleEdit.setSelection(titleEdit.text.length)
val chooseBtn = view.findViewById<Button>(R.id.choose_btn)
chooseBtn.setOnClickListener {
if (!isDetached) {
val intent = Intent(it.context, ChooseIconActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
startActivityForResult(intent, REQUEST_CODE_CHOOSE_ICON)
}
}
return view
}
private fun updateViewValues() {
titleEdit.setText(data.title)
iconView.text = data.iconCode
}
private fun checkEnabledState() {
CoroutineScope(Dispatchers.Main).launch {
var shouldEnabled = !data.title.isEmpty()
if (shouldEnabled) {
when (reason) {
REASON_CREATE -> {
if (SRDatabase.categoryDao.get(data.title) != null) {
shouldEnabled = false
}
}
REASON_EDIT -> {
if (oldData.title != data.title
&& SRDatabase.categoryDao.get(data.title) != null) {
shouldEnabled = false
}
}
}
}
positiveButton?.isEnabled = shouldEnabled
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
when (requestCode) {
REQUEST_CODE_CHOOSE_ICON -> {
if (resultCode == RESULT_OK && intent != null) {
data.iconCode = intent[ChooseIconActivity.EXTRA_RESULT_ICON_CODE]!!.asString()
updateViewValues()
}
}
}
}
private fun sendLocalBroadcast(intent: Intent) {
context?.let { LocalBroadcastManager.getInstance(it).sendBroadcast(intent) }
}
} | gpl-3.0 | af6cd0f7151c48ce6c9a1981cb5bb252 | 33.043062 | 98 | 0.580264 | 5.162554 | false | false | false | false |
JavaEden/OrchidCore | plugins/OrchidGroovydoc/src/main/kotlin/com/eden/orchid/groovydoc/GroovydocCollection.kt | 1 | 1744 | package com.eden.orchid.groovydoc
import com.eden.orchid.api.generators.OrchidCollection
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.groovydoc.pages.GroovydocClassPage
import com.eden.orchid.groovydoc.pages.GroovydocPackagePage
import java.util.stream.Stream
@Description("A groovydoc Collection represents the pages for all the classes and packages in your Groovy project. A " +
"page is matched from a groovydoc Collection with an 'itemId' matching either the simple class name or the " +
"fully-qualified class or package name."
)
class GroovydocCollection(generator: GroovydocGenerator, collectionId: String, items: List<OrchidPage>)
: OrchidCollection<OrchidPage>(generator, collectionId, items) {
override fun find(id: String): Stream<OrchidPage> {
if(id.contains('.')) {
return items.stream()
.filter { page ->
if (page is GroovydocClassPage) {
page.classDoc.qualifiedName == id
}
else if (page is GroovydocPackagePage) {
page.packageDoc.name == id
}
else {
false
}
}
}
else {
return items.stream()
.filter { page ->
if (page is GroovydocClassPage) {
page.classDoc.name == id
}
else {
false
}
}
}
}
}
| mit | 2fcfb26225f00ad97a8c8b4183a23b40 | 37.755556 | 120 | 0.533257 | 5.484277 | false | false | false | false |
jsirianni/cis371 | In_Class_3_Kotlin/src/Server.kt | 1 | 1493 | import java.io.*
import java.net.*
/**
* A simple java server socket
* Listens on all IPs and port 8080
* @author jsirianni
*/
object SimpleServer {
/**
* Main method does the following:
* Sets global variables; fqdn, port, file, path
* Creates a client socket
* Calls downloadFile() method three times, downloading three different files
*/
@Throws(IOException::class)
@JvmStatic fun main(args: Array<String>) {
// Specify port to listen on
val port = 8080
// Create the socket and accept any incoming connection
val s = ServerSocket(port)
// Accept any incoming connection
val conn = s.accept()
// Create buffered reader and print stream to read and write to the client
val fromClient = BufferedReader(InputStreamReader(conn.getInputStream()))
val toClient = PrintStream(conn.getOutputStream())
// Read client message
var msg = ""
do {
msg = fromClient.readLine()
println(msg)
} while (!msg.isEmpty())
// Send generic response header to client
val resp = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 70\r\nConnection: close\r\n\"";
toClient.println(resp)
// Send html body
val body = "This is not the real content because this server is not yet complete.\r\n"
// Close the connection
conn.close()
} // End Main
} // end class | apache-2.0 | 7c69118e2ce04a6a6ff82501f14e9c99 | 27.188679 | 114 | 0.617549 | 4.378299 | false | false | false | false |
ishwarsawale/RSSReaderKotlinAndroid | SampleRss/app/src/main/java/rss/sample/com/samplerss/Adapter/FeedAdapter.kt | 1 | 2574 | package rss.sample.com.samplerss.Adapter
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import rss.sample.com.samplerss.Interface.ItemClickListener
import rss.sample.com.samplerss.Model.RootObject
import rss.sample.com.samplerss.R
@Suppress("DEPRECATION")
class FeedViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),View.OnClickListener,View.OnLongClickListener{
var txtTitle: TextView
var txtPubdate:TextView
var txtContent:TextView
private var itemClickListener : ItemClickListener?=null
init {
txtTitle = itemView.findViewById<TextView>(R.id.txtTitle)
txtPubdate = itemView.findViewById<TextView>(R.id.txtPubdate)
txtContent = itemView.findViewById<TextView>(R.id.txtContent)
itemView.setOnClickListener(this)
itemView.setOnLongClickListener(this)
}
fun setItemClickListener(itemClickListener: ItemClickListener){
this.itemClickListener = itemClickListener
}
override fun onClick(p0: View?) {
itemClickListener!!.onClick(p0,position,false)
}
override fun onLongClick(p0: View?): Boolean {
itemClickListener!!.onClick(p0,position,true)
return true
}
}
class FeedAdapter(private val rootObject: RootObject, private val mContext: Context) :RecyclerView.Adapter<FeedViewHolder>(){
private val inflater: LayoutInflater
init {
inflater = LayoutInflater.from(mContext)
}
override fun getItemCount(): Int {
return rootObject.items.size
}
override fun onCreateViewHolder(p0: ViewGroup?, p1: Int): FeedViewHolder {
val itemView = inflater.inflate(R.layout.row,p0,false)
return FeedViewHolder(itemView)
}
override fun onBindViewHolder(p0: FeedViewHolder?, p1: Int) {
p0?.txtTitle?.text = rootObject.items[p1].title
p0?.txtContent?.text = rootObject.items[p1].link
p0?.txtPubdate?.text = rootObject.items[p1].pubDate
p0?.setItemClickListener(ItemClickListener { view, position, isLongClick ->
if (!isLongClick){
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(rootObject.items[position].link))
browserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
mContext.startActivity(browserIntent)
}
})
}
}
| apache-2.0 | 9fc733a1bc56dbc216f07c2fc2db3c54 | 26.978261 | 126 | 0.710179 | 4.407534 | false | false | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/diff/StringDiffCallback.kt | 1 | 604 | package com.booboot.vndbandroid.diff
import androidx.recyclerview.widget.DiffUtil
class StringDiffCallback(private var oldItems: List<String>, private var newItems: List<String>) : DiffUtil.Callback() {
override fun getOldListSize() = oldItems.size
override fun getNewListSize() = newItems.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
oldItems[oldItemPosition] == newItems[newItemPosition]
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
oldItems[oldItemPosition] == newItems[newItemPosition]
} | gpl-3.0 | c4be63e9cd791dabdda9530ff467afa7 | 39.333333 | 120 | 0.761589 | 5.298246 | false | false | false | false |
MyDogTom/detekt | detekt-api/src/test/kotlin/io/gitlab/arturbosch/detekt/api/ExcludesSpec.kt | 1 | 2784 | package io.gitlab.arturbosch.detekt.api
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
class ExcludesSpec : Spek({
given("an excludes rule with a single exclude") {
val excludes = Excludes("test")
it("contains the `test` parameter") {
val parameter = "test"
assertThat(excludes.contains(parameter)).isTrue()
assertThat(excludes.none(parameter)).isFalse()
}
it("contains an extension of the `test` parameter") {
val parameter = "test.com"
assertThat(excludes.contains(parameter)).isTrue()
assertThat(excludes.none(parameter)).isFalse()
}
it("does not contain a different parameter") {
val parameter = "detekt"
assertThat(excludes.contains(parameter)).isFalse()
assertThat(excludes.none(parameter)).isTrue()
}
it("returns all matches") {
val parameter = "test.com"
val matches = excludes.matches(parameter)
assertThat(matches).hasSize(1)
assertThat(matches).contains("test")
}
}
given("an excludes rule with multiple excludes") {
val excludes = Excludes("here.there.io, test.com")
it("contains the `test` parameter") {
val parameter = "test.com"
assertThat(excludes.contains(parameter)).isTrue()
assertThat(excludes.none(parameter)).isFalse()
}
it("contains the `here.there.io` parameter") {
val parameter = "here.there.io"
assertThat(excludes.contains(parameter)).isTrue()
assertThat(excludes.none(parameter)).isFalse()
}
it("does not contain a parameter spanning over the excludes") {
val parameter = "io.test.com"
assertThat(excludes.contains(parameter)).isTrue()
assertThat(excludes.none(parameter)).isFalse()
}
it("does not contain a different") {
val parameter = "detekt"
assertThat(excludes.contains(parameter)).isFalse()
assertThat(excludes.none(parameter)).isTrue()
}
}
given("an excludes rule with lots of whitespace and an empty parameter") {
val excludes = Excludes(" test, , here.there ")
it("contains the `test` parameter") {
val parameter = "test"
assertThat(excludes.contains(parameter)).isTrue()
assertThat(excludes.none(parameter)).isFalse()
}
it("contains the `here.there` parameter") {
val parameter = "here.there"
assertThat(excludes.contains(parameter)).isTrue()
assertThat(excludes.none(parameter)).isFalse()
}
it("does not contain a different parameter") {
val parameter = "detekt"
assertThat(excludes.contains(parameter)).isFalse()
assertThat(excludes.none(parameter)).isTrue()
}
it("does not match empty strings") {
val parameter = " "
assertThat(excludes.contains(parameter)).isFalse()
assertThat(excludes.none(parameter)).isTrue()
}
}
})
| apache-2.0 | 8b44235b0ce0a1398fbd377fee71f931 | 28.617021 | 75 | 0.70546 | 3.658344 | false | true | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/filter/SortItem.kt | 2 | 2847 | package eu.kanade.tachiyomi.ui.catalogue.filter
import android.support.graphics.drawable.VectorDrawableCompat
import android.support.v4.content.ContextCompat
import android.view.View
import android.widget.CheckedTextView
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractSectionableItem
import eu.davidea.viewholders.FlexibleViewHolder
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.util.getResourceColor
class SortItem(val name: String, val group: SortGroup) : AbstractSectionableItem<SortItem.Holder, SortGroup>(group) {
override fun getLayoutRes(): Int {
return R.layout.navigation_view_checkedtext
}
override fun getItemViewType(): Int {
return 102
}
override fun createViewHolder(view: View, adapter: FlexibleAdapter<*>): Holder {
return Holder(view, adapter)
}
override fun bindViewHolder(adapter: FlexibleAdapter<*>, holder: Holder, position: Int, payloads: List<Any?>?) {
val view = holder.text
view.text = name
val filter = group.filter
val i = filter.values.indexOf(name)
fun getIcon() = when (filter.state) {
Filter.Sort.Selection(i, false) -> VectorDrawableCompat.create(view.resources, R.drawable.ic_arrow_down_white_32dp, null)
?.apply { setTint(view.context.getResourceColor(R.attr.colorAccent)) }
Filter.Sort.Selection(i, true) -> VectorDrawableCompat.create(view.resources, R.drawable.ic_arrow_up_white_32dp, null)
?.apply { setTint(view.context.getResourceColor(R.attr.colorAccent)) }
else -> ContextCompat.getDrawable(view.context, R.drawable.empty_drawable_32dp)
}
view.setCompoundDrawablesWithIntrinsicBounds(getIcon(), null, null, null)
holder.itemView.setOnClickListener {
val pre = filter.state?.index ?: i
if (pre != i) {
filter.state = Filter.Sort.Selection(i, false)
} else {
filter.state = Filter.Sort.Selection(i, filter.state?.ascending == false)
}
group.subItems.forEach { adapter.notifyItemChanged(adapter.getGlobalPositionOf(it)) }
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as SortItem
return name == other.name && group == other.group
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + group.hashCode()
return result
}
class Holder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter) {
val text: CheckedTextView = itemView.findViewById(R.id.nav_view_item)
}
} | apache-2.0 | 055f3eb7f64fcd4d19998ef73d0c4efb | 37.486486 | 133 | 0.674043 | 4.504747 | false | false | false | false |
TheFallOfRapture/Morph | src/main/kotlin/com/morph/engine/graphics/shaders/Uniforms.kt | 2 | 2393 | package com.morph.engine.graphics.shaders
import com.morph.engine.core.Camera
import com.morph.engine.graphics.Color
import com.morph.engine.graphics.components.RenderData
import com.morph.engine.graphics.components.light.Light
import com.morph.engine.math.Matrix4f
import com.morph.engine.math.Vector2f
import com.morph.engine.math.Vector3f
import com.morph.engine.math.Vector4f
import com.morph.engine.physics.components.Transform
import org.lwjgl.opengl.GL20.*
import java.util.*
abstract class Uniforms {
private var uniforms: HashMap<String, Int> = HashMap()
protected lateinit var shader: Shader<*>
fun init(shader: Shader<*>) {
this.shader = shader
}
abstract fun defineUniforms(shader: Int)
abstract fun setUniforms(t: Transform, data: RenderData, camera: Camera, screen: Matrix4f, lights: List<Light>)
abstract fun unbind(t: Transform, data: RenderData)
protected fun addUniform(name: String, shader: Int) {
val location = glGetUniformLocation(shader, name)
uniforms[name] = location
}
fun setUniform1i(name: String, value: Int) {
val location = uniforms[name]
location?.let { glUniform1i(it, value) }
}
fun setUniform1f(name: String, value: Float) {
val location = uniforms[name]
location?.let { glUniform1f(it, value) }
}
fun setUniform2f(name: String, value: Vector2f) {
val location = uniforms[name]
location?.let { glUniform2f(it, value.x, value.y) }
}
fun setUniform3f(name: String, value: Vector3f) {
val location = uniforms[name]
location?.let { glUniform3f(it, value.x, value.y, value.z) }
}
fun setUniform3f(name: String, value: Color) {
val location = uniforms[name]
location?.let { glUniform3f(it, value.red, value.green, value.blue) }
}
fun setUniform4f(name: String, value: Vector4f) {
val location = uniforms[name]
location?.let { glUniform4f(it, value.x, value.y, value.z, value.w) }
}
fun setUniform4f(name: String, value: Color) {
val location = uniforms[name]
location?.let { glUniform4f(it, value.red, value.green, value.blue, value.alpha) }
}
fun setUniformMatrix4fv(name: String, value: Matrix4f) {
val location = uniforms[name]
location?.let { glUniformMatrix4fv(it, true, value.toArray()) }
}
}
| mit | eb072013c31d88e6d9d39384f0d9b930 | 32.704225 | 115 | 0.678646 | 3.636778 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/hazelcast/serializers/MaterializeEntitySetProcessorStreamSerializer.kt | 1 | 4752 | /*
* Copyright (C) 2019. OpenLattice, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.hazelcast.serializers
import com.hazelcast.nio.ObjectDataInput
import com.hazelcast.nio.ObjectDataOutput
import com.kryptnostic.rhizome.hazelcast.serializers.UUIDStreamSerializerUtils
import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer
import com.openlattice.assembler.AssemblerConnectionManager
import com.openlattice.assembler.AssemblerConnectionManagerDependent
import com.openlattice.assembler.processors.MaterializeEntitySetProcessor
import com.openlattice.authorization.Principal
import com.openlattice.edm.type.PropertyType
import com.openlattice.hazelcast.StreamSerializerTypeIds
import org.springframework.stereotype.Component
/**
*
* @author Matthew Tamayo-Rios <[email protected]>
*/
@Component
class MaterializeEntitySetProcessorStreamSerializer
: SelfRegisteringStreamSerializer<MaterializeEntitySetProcessor>, AssemblerConnectionManagerDependent<Void?> {
companion object {
@JvmStatic
fun serializeAuthorizedPropertyTypesOfPrincipals(
out: ObjectDataOutput, authorizedPropertyTypesOfPrincipals: Map<Principal, Set<PropertyType>>
) {
out.writeInt(authorizedPropertyTypesOfPrincipals.size)
authorizedPropertyTypesOfPrincipals.forEach { (principal, authorizedPropertyTypes) ->
PrincipalStreamSerializer.serialize(out, principal)
out.writeInt(authorizedPropertyTypes.size)
authorizedPropertyTypes.forEach {
PropertyTypeStreamSerializer.serialize(out, it)
}
}
}
@JvmStatic
fun deserializeAuthorizedPropertyTypesOfPrincipals(input: ObjectDataInput): Map<Principal, Set<PropertyType>> {
val principalsSize = input.readInt()
return ((0 until principalsSize).map {
val principal = PrincipalStreamSerializer.deserialize(input)
val authorizedPropertySize = input.readInt()
val authorizedPropertyTypes = ((0 until authorizedPropertySize).map {
PropertyTypeStreamSerializer.deserialize(input)
}.toSet())
principal to authorizedPropertyTypes
}.toMap())
}
}
private lateinit var acm: AssemblerConnectionManager
override fun getTypeId(): Int {
return StreamSerializerTypeIds.MATERIALIZE_ENTITY_SETS_PROCESSOR.ordinal
}
override fun destroy() {
}
override fun getClazz(): Class<MaterializeEntitySetProcessor> {
return MaterializeEntitySetProcessor::class.java
}
override fun write(out: ObjectDataOutput, obj: MaterializeEntitySetProcessor) {
EntitySetStreamSerializer.serialize(out, obj.entitySet)
out.writeInt(obj.materializablePropertyTypes.size)
obj.materializablePropertyTypes.forEach { (propertyTypeId, propertyType) ->
UUIDStreamSerializerUtils.serialize(out, propertyTypeId)
PropertyTypeStreamSerializer.serialize(out, propertyType)
}
serializeAuthorizedPropertyTypesOfPrincipals(out, obj.authorizedPropertyTypesOfPrincipals)
}
override fun read(input: ObjectDataInput): MaterializeEntitySetProcessor {
val entitySet = EntitySetStreamSerializer.deserialize(input)
val materializablePropertySize = input.readInt()
val materializablePropertyTypes = ((0 until materializablePropertySize).map {
UUIDStreamSerializerUtils.deserialize(input) to PropertyTypeStreamSerializer.deserialize(input)
}.toMap())
val authorizedPropertyTypesOfPrincipals = deserializeAuthorizedPropertyTypesOfPrincipals(input)
return MaterializeEntitySetProcessor(
entitySet, materializablePropertyTypes, authorizedPropertyTypesOfPrincipals
).init(acm)
}
override fun init(acm: AssemblerConnectionManager): Void? {
this.acm = acm
return null
}
} | gpl-3.0 | df7bee2e3b025901de519881dad54cd8 | 38.608333 | 119 | 0.731481 | 5.802198 | false | false | false | false |
zaqwes8811/micro-apps | buffer/jvm-tricks/lang_cores/kotlin/src/testing/first.kt | 1 | 713 | package testing
/**
* Created by zaqwes on 3/29/15.
*/
//fun main(args : Array<String>) {
// println("Hello, world!")
//}
//fun main(args : Array<String>) {
// if (args.size == 0) {
// println("Please provide a name as a command-line argument")
// return
// }
// println("Hello, ${args[0]}!")
//}
/*fun main(args : Array<String>) {
for (name in args)
println("Hello, $name!")
}*/
fun main(args: Array<String>) {
val language = if (args.size == 0) "EN" else args[0]
println(when (language) {
"EN" -> "Hello!"
"FR" -> "Salut!"
"IT" -> "Ciao!"
"seyfer" -> "seed!"
else -> "Sorry, I can't greet you in $language yet"
})
} | mit | 63d50d404bb4cac1a7f8608d7419f8e4 | 21.3125 | 69 | 0.516129 | 3.060086 | false | false | false | false |
magnusja/libaums | httpserver/src/main/java/me/jahnen/libaums/server/http/server/AsyncHttpServer.kt | 2 | 2461 | package me.jahnen.libaums.server.http.server
import android.util.Log
import me.jahnen.libaums.core.fs.UsbFileInputStream
import me.jahnen.libaums.server.http.UsbFileProvider
import me.jahnen.libaums.server.http.exception.NotAFileException
import com.koushikdutta.async.AsyncServer
import com.koushikdutta.async.http.server.AsyncHttpServerRequest
import com.koushikdutta.async.http.server.AsyncHttpServerResponse
import com.koushikdutta.async.http.server.HttpServerRequestCallback
import java.io.FileNotFoundException
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
/**
* Created by magnusja on 16/12/16.
*/
class AsyncHttpServer(private val port: Int) : HttpServer, HttpServerRequestCallback {
override lateinit var usbFileProvider: UsbFileProvider
private val server = com.koushikdutta.async.http.server.AsyncHttpServer()
override var isAlive = false
override val hostname: String
get() = ""
override val listeningPort: Int
get() = port
init {
server.get("/.*", this)
}
@Throws(IOException::class)
override fun start() {
server.listen(port)
isAlive = true
}
@Throws(IOException::class)
override fun stop() {
server.stop()
// force the server to stop even if there are ongoing connections
AsyncServer.getDefault().stop()
isAlive = false
}
override fun onRequest(request: AsyncHttpServerRequest, response: AsyncHttpServerResponse) {
val uri: String
try {
uri = URLDecoder.decode(request.path, "utf-8")
} catch (e: UnsupportedEncodingException) {
Log.e(TAG, "could not decode URL", e)
response.code(404)
response.send(e.message)
return
}
Log.d(TAG, "Uri: $uri")
try {
val fileToServe = usbFileProvider.determineFileToServe(uri)
response.sendStream(UsbFileInputStream(fileToServe), fileToServe.length)
} catch (e: FileNotFoundException) {
response.code(404)
response.send(e.message)
} catch (e: NotAFileException) {
response.code(400)
response.send(e.message)
} catch (e: IOException) {
response.code(500)
response.send(e.message)
}
}
companion object {
private val TAG = AsyncHttpServer::class.java.simpleName
}
}
| apache-2.0 | 8178a1a534cae67a2a49042382df07b4 | 29.382716 | 96 | 0.668427 | 4.402504 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/widget/ForegroundImageView.kt | 1 | 5087 | /*
* Copyright 2014 DogmaLabs
*
* 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.boardgamegeek.ui.widget
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.graphics.drawable.NinePatchDrawable
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.content.withStyledAttributes
import com.boardgamegeek.R
class ForegroundImageView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {
private var foreground: Drawable? = null
private val rectPadding = Rect()
private var foregroundPadding = false
private var foregroundBoundsChanged = false
init {
context.withStyledAttributes(attrs, R.styleable.ForegroundImageView, defStyleAttr, defStyleRes) {
foregroundPadding = getBoolean(R.styleable.ForegroundImageView_foregroundInsidePadding, false)
// Apply foreground padding for nine patches automatically
if (!foregroundPadding) {
if ((background as? NinePatchDrawable)?.getPadding(rectPadding) == true) {
foregroundPadding = true
}
}
setForeground(getDrawable(R.styleable.ForegroundImageView_android_foreground))
}
}
/**
* Supply a Drawable that is to be rendered on top of all of the child views in the layout.
*
* @param drawable The Drawable to be drawn on top of the children.
*/
override fun setForeground(drawable: Drawable?) {
if (foreground !== drawable) {
foreground?.callback = null
unscheduleDrawable(foreground)
foreground = drawable
if (drawable != null) {
setWillNotDraw(false)
drawable.callback = this
if (drawable.isStateful) drawable.state = drawableState
} else {
setWillNotDraw(true)
}
requestLayout()
invalidate()
}
}
/**
* Returns the drawable used as the foreground of this layout. The foreground drawable,
* if non-null, is always drawn on top of the children.
*
* @return A Drawable or null if no foreground was set.
*/
override fun getForeground(): Drawable? {
return foreground
}
override fun drawableStateChanged() {
super.drawableStateChanged()
if (foreground?.isStateful == true) {
foreground?.state = drawableState
}
}
override fun verifyDrawable(who: Drawable): Boolean {
return super.verifyDrawable(who) || who === foreground
}
override fun jumpDrawablesToCurrentState() {
super.jumpDrawablesToCurrentState()
foreground?.jumpToCurrentState()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
foregroundBoundsChanged = true
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
if (foreground != null) {
val foreground = this.foreground as Drawable
if (foregroundBoundsChanged) {
foregroundBoundsChanged = false
val w = right - left
val h = bottom - top
if (foregroundPadding) {
foreground.setBounds(rectPadding.left, rectPadding.top, w - rectPadding.right, h - rectPadding.bottom)
} else {
foreground.setBounds(0, 0, w, h)
}
}
foreground.draw(canvas)
}
}
@SuppressLint("ClickableViewAccessibility")
@TargetApi(VERSION_CODES.LOLLIPOP)
override fun onTouchEvent(e: MotionEvent): Boolean {
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
if (e.actionMasked == MotionEvent.ACTION_DOWN) {
foreground?.setHotspot(e.x, e.y)
}
}
return super.onTouchEvent(e)
}
override fun drawableHotspotChanged(x: Float, y: Float) {
super.drawableHotspotChanged(x, y)
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
foreground?.setHotspot(x, y)
}
}
}
| gpl-3.0 | 21a1be3dd6acf4fa1f4b32a00977550c | 32.467105 | 122 | 0.641636 | 4.863289 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/mappers/UserMapper.kt | 1 | 672 | package com.boardgamegeek.mappers
import com.boardgamegeek.entities.BriefBuddyEntity
import com.boardgamegeek.entities.UserEntity
import com.boardgamegeek.io.model.Buddy
import com.boardgamegeek.io.model.User
import com.boardgamegeek.provider.BggContract
fun User.mapToEntity() = UserEntity(
internalId = BggContract.INVALID_ID.toLong(),
id = id.toIntOrNull() ?: BggContract.INVALID_ID,
userName = name,
firstName = firstName,
lastName = lastName,
avatarUrlRaw = avatarUrl,
)
fun Buddy.mapToEntity(timestamp: Long) = BriefBuddyEntity(
id = id.toIntOrNull() ?: BggContract.INVALID_ID,
userName = name,
updatedTimestamp = timestamp,
)
| gpl-3.0 | db5e0050912387cdd135fb3af3557bf9 | 29.545455 | 58 | 0.758929 | 4.148148 | false | false | false | false |
mercadopago/px-android | px-checkout/src/main/java/com/mercadopago/android/px/tracking/internal/views/ErrorViewTracker.kt | 1 | 757 | package com.mercadopago.android.px.tracking.internal.views
import com.mercadopago.android.px.model.exceptions.MercadoPagoError
import com.mercadopago.android.px.tracking.internal.TrackFactory
import com.mercadopago.android.px.tracking.internal.TrackWrapper
import com.mercadopago.android.px.tracking.internal.model.ApiErrorData
class ErrorViewTracker(errorMessage: String, mpError: MercadoPagoError) : TrackWrapper() {
private val data = mutableMapOf<String, Any>().also {
it["error_message"] = errorMessage
it["api_error"] = ApiErrorData(mpError).toMap()
}
override fun getTrack() = TrackFactory.withView(PATH).addData(data).build()
companion object {
private const val PATH = "$BASE_PATH/generic_error"
}
} | mit | c7405e0661a99c6436f2874bd7effc92 | 36.9 | 90 | 0.756935 | 4.159341 | false | false | false | false |
WindSekirun/RichUtilsKt | RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/service/RLocationService.kt | 1 | 11087 | package pyxis.uzuki.live.richutilskt.service
import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import android.os.Binder
import android.os.Bundle
import android.util.Log
import android.view.Surface
import android.view.WindowManager
import pyxis.uzuki.live.richutilskt.impl.F1
import pyxis.uzuki.live.richutilskt.utils.locationManager
import pyxis.uzuki.live.richutilskt.utils.sensorManager
import pyxis.uzuki.live.richutilskt.utils.windowManager
import java.io.IOException
import java.util.*
@SuppressLint("MissingPermission")
class RLocationService : Service() {
private val gpsLocationListener = LocationChangeListener()
private val networkLocationListener = LocationChangeListener()
private val sensorEventListener = SensorListener()
private val localBinder = LocalBinder()
private val TWO_MINUTES = 1000 * 60 * 2
private val MIN_BEARING_DIFF = 2.0f
private val FASTEST_INTERVAL_IN_MS = 1000L
private var bearing: Float = 0f
private var axisX: Int = 0
private var axisY: Int = 0
var currentBestLocation: Location? = null
private var locationCallback: LocationCallback? = null
override fun onBind(intent: Intent?) = localBinder
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
return START_STICKY
}
override fun onCreate() {
super.onCreate()
getLocation()
}
override fun onDestroy() {
super.onDestroy()
stopUpdates()
sensorManager.unregisterListener(sensorEventListener)
}
/**
* get location of user.
* this service using 3 methods for fetch location. (Mobile, GPS, Sensor)
*/
fun getLocation() {
val lastKnownGpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
val lastKnownNetworkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
var bestLastKnownLocation = currentBestLocation
if (lastKnownGpsLocation != null && isBetterLocation(lastKnownGpsLocation, bestLastKnownLocation)) {
bestLastKnownLocation = lastKnownGpsLocation
}
if (lastKnownNetworkLocation != null && isBetterLocation(lastKnownNetworkLocation, bestLastKnownLocation)) {
bestLastKnownLocation = lastKnownNetworkLocation
}
currentBestLocation = bestLastKnownLocation
if (locationManager.allProviders.contains(LocationManager.GPS_PROVIDER) && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, FASTEST_INTERVAL_IN_MS, 0.0f, gpsLocationListener)
}
if (locationManager.allProviders.contains(LocationManager.NETWORK_PROVIDER) && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, FASTEST_INTERVAL_IN_MS, 0.0f, networkLocationListener)
}
bestLastKnownLocation?.bearing = bearing
locationCallback?.handleNewLocation(currentBestLocation as Location)
val mSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
sensorManager.registerListener(sensorEventListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL * 5)
}
/**
* Set callback for location service.
* any location updates will invoke this callback (except new location data is not-best-location.)
*/
fun setLocationCallback(callback: (Location) -> Unit) {
locationCallback = object : LocationCallback, (Location) -> Unit {
override fun invoke(location: Location) {
callback.invoke(location)
}
override fun handleNewLocation(location: Location) {
callback.invoke(location)
}
}
}
/**
* Set callback for location service.
* any location updates will invoke this callback (except new location data is not-best-location.)
*/
fun setLocationCallback(callback: F1<Location>) {
locationCallback = object : LocationCallback, (Location) -> Unit {
override fun invoke(location: Location) {
callback.invoke(location)
}
override fun handleNewLocation(location: Location) {
callback.invoke(location)
}
}
}
/**
* stop location update service
*/
fun stopUpdates() {
locationManager.removeUpdates(gpsLocationListener)
locationManager.removeUpdates(networkLocationListener)
sensorManager.unregisterListener(sensorEventListener)
}
/**
* get Address from CurrentBestLocation
*
* @return List<Address> or null
*/
fun Context.getGeoCoderAddress(): List<Address>? {
val geoCoder = Geocoder(this, Locale.ENGLISH)
try {
return geoCoder.getFromLocation(currentBestLocation?.latitude ?: 0.0, currentBestLocation?.longitude ?: 0.0, 1)
} catch (e: IOException) {
Log.e(RLocationService::class.java.simpleName, "Impossible to connect to Geocoder", e)
}
return null
}
private fun Context.getFirstAddress(): Address? {
val addresses = getGeoCoderAddress()
if (addresses != null && addresses.isNotEmpty())
return addresses[0]
else
return null
}
/**
* get AddressLine
*
* @return addressLine of current Best Location
*/
fun Context.getAddressLine(): String = getFirstAddress()?.getAddressLine(0) ?: ""
/**
* get locality
*
* @return locality of current Best Location
*/
fun Context.getLocality(): String = getFirstAddress()?.locality ?: ""
/**
* get postal code
*
* @return postal code of current Best Location
*/
fun Context.getPostalCode(): String = getFirstAddress()?.postalCode ?: ""
/**
* get country name
*
* @return country name of current Best Location
*/
fun Context.getCountryName(): String = getFirstAddress()?.countryName ?: ""
private fun isBetterLocation(location: Location, currentBestLocation: Location?): Boolean {
if (currentBestLocation == null) {
// 이전에 저장한 것이 없다면 새로 사용
return true
}
val timeDelta = location.time - currentBestLocation.time
val isSignificantlyNewer = timeDelta > TWO_MINUTES // 시간차 2분 이상?
val isSignificantlyOlder = timeDelta < -TWO_MINUTES // 아니면 더 오래되었는지
val isNewer = timeDelta > 0 // 신규 위치정보 파악
// 만일 2분이상 차이난다면 새로운거 사용 (유저가 움직이기 때문)
if (isSignificantlyNewer) {
return true
} else if (isSignificantlyOlder) {
return false
}
// Check whether the new location fix is more or less accurate
val accuracyDelta = (location.accuracy - currentBestLocation.accuracy).toInt()
val isLessAccurate = accuracyDelta > 0 // 기존거가 더 정확함
val isMoreAccurate = accuracyDelta < 0 // 신규가 더 정확함
val isSignificantlyLessAccurate = accuracyDelta > 200 // 200이상 심각하게 차이남
val isFromSameProvider = isSameProvider(location.provider, currentBestLocation.provider) // 같은 프로바이더인지
if (isMoreAccurate) {// 더 정확하면?
return true
} else if (isNewer && !isLessAccurate) {// 새로운 데이터이고 신규가 정확하거나 같을때
return true
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {// 새로운 데이터이고 너무 차이나지 않고 같은 프로바이더인 경우
return true
}
return false
}
private fun isSameProvider(provider1: String?, provider2: String?): Boolean = if (provider1 == null) provider2 == null else provider1 == provider2
private inner class LocationChangeListener : android.location.LocationListener {
override fun onLocationChanged(location: Location?) {
if (location == null) {
return
}
if (isBetterLocation(location, currentBestLocation)) {
currentBestLocation = location
currentBestLocation?.bearing = bearing
locationCallback?.handleNewLocation(currentBestLocation as Location)
}
}
override fun onProviderDisabled(provider: String?) {}
override fun onProviderEnabled(provider: String?) {}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
}
private inner class SensorListener : SensorEventListener {
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
if (sensor?.type == Sensor.TYPE_ROTATION_VECTOR) {
Log.i(RLocationService::class.java.simpleName, "Rotation sensor accuracy changed to: " + accuracy)
}
}
override fun onSensorChanged(event: SensorEvent?) {
val rotationMatrix = FloatArray(16)
SensorManager.getRotationMatrixFromVector(rotationMatrix, event?.values)
val orientationValues = FloatArray(3)
readDisplayRotation()
SensorManager.remapCoordinateSystem(rotationMatrix, axisX, axisY, rotationMatrix)
SensorManager.getOrientation(rotationMatrix, orientationValues)
val azimuth = Math.toDegrees(orientationValues[0].toDouble())
val newBearing = azimuth
val abs = Math.abs(bearing.minus(newBearing).toFloat()) > MIN_BEARING_DIFF
if (abs) {
bearing = newBearing.toFloat()
currentBestLocation?.bearing = bearing
}
}
}
private fun readDisplayRotation() {
axisX = SensorManager.AXIS_X
axisY = SensorManager.AXIS_Y
when (windowManager.defaultDisplay.rotation) {
Surface.ROTATION_90 -> {
axisX = SensorManager.AXIS_Y
axisY = SensorManager.AXIS_MINUS_X
}
Surface.ROTATION_180 -> axisY = SensorManager.AXIS_MINUS_Y
Surface.ROTATION_270 -> {
axisX = SensorManager.AXIS_MINUS_Y
axisY = SensorManager.AXIS_X
}
}
}
inner class LocalBinder : Binder() {
val service: RLocationService
get() = this@RLocationService
}
interface LocationCallback {
fun handleNewLocation(location: Location)
}
} | apache-2.0 | a6d3eafd86beeb099a1a689bfe2176fb | 35.343434 | 157 | 0.662466 | 5.00139 | false | false | false | false |
RoverPlatform/rover-android | notifications/src/main/kotlin/io/rover/sdk/notifications/NotificationDispatcher.kt | 1 | 9033 | package io.rover.sdk.notifications
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.graphics.Bitmap
import android.os.Build
import androidx.annotation.DrawableRes
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import io.rover.core.R
import io.rover.sdk.core.assets.AssetService
import io.rover.sdk.core.data.NetworkResult
import io.rover.sdk.core.logging.log
import io.rover.sdk.core.streams.Publishers
import io.rover.sdk.core.streams.Scheduler
import io.rover.sdk.core.streams.doOnNext
import io.rover.sdk.core.streams.map
import io.rover.sdk.core.streams.onErrorReturn
import io.rover.sdk.core.streams.subscribe
import io.rover.sdk.core.streams.subscribeOn
import io.rover.sdk.core.streams.timeout
import io.rover.sdk.notifications.domain.NotificationAttachment
import io.rover.sdk.notifications.ui.concerns.NotificationsRepositoryInterface
import org.reactivestreams.Publisher
import java.util.concurrent.TimeUnit
/**
* Responsible for adding a [Notification] to the Android notification area as well as the Rover
* Notification Center.
*/
class NotificationDispatcher(
private val applicationContext: Context,
private val mainThreadScheduler: Scheduler,
// add this back after solving injection issues.
private val notificationsRepository: NotificationsRepositoryInterface,
private val notificationOpen: NotificationOpenInterface,
private val assetService: AssetService,
private val influenceTrackerService: InfluenceTrackerServiceInterface,
/**
* A small icon is necessary for Android push notifications. Pass a resid.
*
* Android design guidelines suggest that you use a multi-level drawable for your application
* icon, such that you can specify one of its levels that is most appropriate as a single-colour
* silhouette that can be used in the Android notification drawer.
*/
@param:DrawableRes
private val smallIconResId: Int,
/**
* The drawable level of [smallIconResId] that should be used for the icon silhouette used in
* the notification drawer.
*/
private val smallIconDrawableLevel: Int = 0,
/**
* This Channel Id will be used for any push notifications arrive without an included Channel
* Id.
*/
private val defaultChannelId: String? = null,
private val iconColor: Int? = null
) {
fun ingest(notificationFromAction: io.rover.sdk.notifications.domain.Notification) {
Publishers.defer {
processNotification(notificationFromAction)
}.subscribeOn(mainThreadScheduler).subscribe {} // TODO: do not use subscriber like this, it will leak
}
/**
* By default, if running on Oreo and later, and the [NotificationsAssembler.defaultChannelId] you
* gave does not exist, then we will lazily create it at notification reception time to
* avoid the
*
* We include a default implementation here, however, you should consider registering your own
* channel ID in your application initialization and passing it to the NotificationAssembler()
* constructor.
*/
@RequiresApi(Build.VERSION_CODES.O)
fun registerDefaultChannelId() {
log.w(
"Rover is registering a default channel ID for you. This isn't optimal; if you are targeting Android SDK >= 26 then you should create your Notification Channels.\n" +
"See https://developer.android.com/training/notify-user/channels.html"
)
// Create the NotificationChannel
val name = applicationContext.getString(R.string.default_notification_channel_name)
val description = applicationContext.getString(R.string.default_notification_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(defaultChannelId, name, importance)
mChannel.description = description
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = applicationContext.getSystemService(
Context.NOTIFICATION_SERVICE
) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
private fun processNotification(notification: io.rover.sdk.notifications.domain.Notification): Publisher<Unit> {
// notify the influenced opens tracker that a notification is being executed.
influenceTrackerService.notifyNotificationReceived(notification)
verifyChannelSetUp()
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder(applicationContext, notification.channelId ?: defaultChannelId ?: NotificationChannel.DEFAULT_CHANNEL_ID)
} else {
@Suppress("DEPRECATION") // Only in use to support legacy Android API.
NotificationCompat.Builder(applicationContext)
}
builder.setContentTitle(notification.title)
builder.setContentText(notification.body)
iconColor?.let {
builder.color = it
}
builder.setStyle(NotificationCompat.BigTextStyle())
builder.setSmallIcon(smallIconResId, smallIconDrawableLevel)
notificationsRepository.notificationArrivedByPush(notification)
builder.setContentIntent(
notificationOpen.pendingIntentForAndroidNotification(
notification
)
)
// Set large icon and Big Picture as needed by Rich Media values. Enforce a timeout
// so we don't fail to create the notification in the allotted 10s if network doesn't
// cooperate.
val attachmentBitmapPublisher: Publisher<NetworkResult<Bitmap>?> = when (notification.attachment) {
is NotificationAttachment.Image -> {
assetService.getImageByUrl(notification.attachment.url)
.timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.onErrorReturn { error ->
// log.w("Timed out fetching notification image. Will create image without the rich media.")
NetworkResult.Error<Bitmap>(error, false)
}
}
null -> Publishers.just(null)
else -> {
log.w("Notification attachments of type ${notification.attachment.typeName} not supported on Android.")
Publishers.just(null)
}
}
return attachmentBitmapPublisher
.doOnNext { attachmentBitmapResult ->
when (attachmentBitmapResult) {
is NetworkResult.Success<*> -> {
builder.setLargeIcon(attachmentBitmapResult.response as Bitmap)
builder.setStyle(
NotificationCompat.BigPictureStyle()
.bigPicture(attachmentBitmapResult.response as Bitmap)
)
}
is NetworkResult.Error -> {
log.w("Unable to retrieve notification image: ${notification.attachment?.url}, because: ${attachmentBitmapResult.throwable.message}")
log.w("Will create image without the rich media.")
}
null -> {
/* no-op, from errors handled previously in pipeline */
}
}
notificationManager.notify(
notification.id,
// "ROVR" in ascii. just to further avoid collision with any non-Rover notifications.
0x524F5652,
builder.build().apply {
this.flags = this.flags or Notification.FLAG_AUTO_CANCEL
}
)
}.map { Unit }
}
private val notificationManager: NotificationManagerCompat = NotificationManagerCompat.from(applicationContext)
@SuppressLint("NewApi")
private fun verifyChannelSetUp() {
val notificationManager = applicationContext.getSystemService(
Context.NOTIFICATION_SERVICE
) as NotificationManager
val existingChannel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.getNotificationChannel(defaultChannelId)
} else {
return
}
if (existingChannel == null) registerDefaultChannelId()
}
companion object {
/**
* Android gives push handlers 10 seconds to complete.
*
* If we can't get our image downloaded in the 10 seconds, instead of failing we want to
* timeout gracefully.
*/
private const val TIMEOUT_SECONDS = 8L
}
}
| apache-2.0 | 8427c3e370bc1970169db69a6690afe9 | 41.21028 | 179 | 0.668991 | 5.348135 | false | false | false | false |
prt2121/json2pojo | src/main/kotlin/com/prt2121/pojo/rx/JavaFxScheduler.kt | 1 | 2409 | package com.prt2121.pojo.rx
/**
* Created by pt2121 on 11/7/15.
*/
import javafx.animation.KeyFrame
import javafx.animation.Timeline
import javafx.application.Platform
import javafx.event.ActionEvent
import javafx.event.EventHandler
import javafx.util.Duration
import rx.Scheduler
import rx.Subscription
import rx.functions.Action0
import rx.subscriptions.BooleanSubscription
import rx.subscriptions.CompositeSubscription
import rx.subscriptions.Subscriptions
import java.util.concurrent.TimeUnit
import java.lang.Math.max
class JavaFxScheduler internal constructor() : Scheduler() {
override fun createWorker(): Worker {
return InnerJavaFxScheduler()
}
private class InnerJavaFxScheduler : Worker() {
private val innerSubscription = CompositeSubscription()
override fun unsubscribe() {
innerSubscription.unsubscribe()
}
override fun isUnsubscribed(): Boolean {
return innerSubscription.isUnsubscribed
}
override fun schedule(action: Action0, delayTime: Long, unit: TimeUnit): Subscription {
val s = BooleanSubscription.create()
val delay = unit.toMillis(max(delayTime, 0))
val timeline = Timeline(KeyFrame(Duration.millis(delay.toDouble()), object : EventHandler<ActionEvent> {
override fun handle(event: ActionEvent) {
if (innerSubscription.isUnsubscribed || s.isUnsubscribed) {
return
}
action.call()
innerSubscription.remove(s)
}
}))
timeline.cycleCount = 1
timeline.play()
innerSubscription.add(s)
return Subscriptions.create(object : Action0 {
override fun call() {
timeline.stop()
s.unsubscribe()
innerSubscription.remove(s)
}
})
}
override fun schedule(action: Action0): Subscription {
val s = BooleanSubscription.create()
Platform.runLater(object : Runnable {
override fun run() {
if (innerSubscription.isUnsubscribed || s.isUnsubscribed) {
return
}
action.call()
innerSubscription.remove(s)
}
})
innerSubscription.add(s)
return Subscriptions.create(object : Action0 {
override fun call() {
s.unsubscribe()
innerSubscription.remove(s)
}
})
}
}
companion object {
val instance = JavaFxScheduler()
}
} | apache-2.0 | a42c90bbdd7897016ac3d6050c8973c2 | 23.1 | 110 | 0.662931 | 4.827655 | false | false | false | false |
c4software/Android-Password-Store | app/src/main/java/com/zeapo/pwdstore/pwgen/RandomPasswordGenerator.kt | 1 | 3235 | /*
* Copyright © 2014-2019 The Android Password Store Authors. All Rights Reserved.
* SPDX-License-Identifier: GPL-2.0
*/
package com.zeapo.pwdstore.pwgen
internal object RandomPasswordGenerator {
/**
* Generates a completely random password.
*
* @param size length of password to generate
* @param pwFlags flag field where set bits indicate conditions the
* generated password must meet
* <table summary ="bits of flag field">
* <tr><td>Bit</td><td>Condition</td></tr>
* <tr><td>0</td><td>include at least one number</td></tr>
* <tr><td>1</td><td>include at least one uppercase letter</td></tr>
* <tr><td>2</td><td>include at least one symbol</td></tr>
* <tr><td>3</td><td>don't include ambiguous characters</td></tr>
* <tr><td>4</td><td>don't include vowels</td></tr>
* <tr><td>5</td><td>include at least one lowercase</td></tr>
</table> *
* @return the generated password
*/
fun rand(size: Int, pwFlags: Int): String {
var password: String
var cha: Char
var i: Int
var featureFlags: Int
var num: Int
var character: String
var bank = ""
if (pwFlags and PasswordGenerator.DIGITS > 0) {
bank += PasswordGenerator.DIGITS_STR
}
if (pwFlags and PasswordGenerator.UPPERS > 0) {
bank += PasswordGenerator.UPPERS_STR
}
if (pwFlags and PasswordGenerator.LOWERS > 0) {
bank += PasswordGenerator.LOWERS_STR
}
if (pwFlags and PasswordGenerator.SYMBOLS > 0) {
bank += PasswordGenerator.SYMBOLS_STR
}
do {
password = ""
featureFlags = pwFlags
i = 0
while (i < size) {
num = RandomNumberGenerator.number(bank.length)
cha = bank.toCharArray()[num]
character = cha.toString()
if (pwFlags and PasswordGenerator.AMBIGUOUS > 0 &&
PasswordGenerator.AMBIGUOUS_STR.contains(character)) {
continue
}
if (pwFlags and PasswordGenerator.NO_VOWELS > 0 && PasswordGenerator.VOWELS_STR.contains(character)) {
continue
}
password += character
i++
if (PasswordGenerator.DIGITS_STR.contains(character)) {
featureFlags = featureFlags and PasswordGenerator.DIGITS.inv()
}
if (PasswordGenerator.UPPERS_STR.contains(character)) {
featureFlags = featureFlags and PasswordGenerator.UPPERS.inv()
}
if (PasswordGenerator.SYMBOLS_STR.contains(character)) {
featureFlags = featureFlags and PasswordGenerator.SYMBOLS.inv()
}
if (PasswordGenerator.LOWERS_STR.contains(character)) {
featureFlags = featureFlags and PasswordGenerator.LOWERS.inv()
}
}
} while (featureFlags and (PasswordGenerator.UPPERS or PasswordGenerator.DIGITS or PasswordGenerator.SYMBOLS or PasswordGenerator.LOWERS) > 0)
return password
}
}
| gpl-3.0 | 09bac11fdfc4186cb60a25cb52f128a2 | 39.425 | 150 | 0.57081 | 4.762887 | false | false | false | false |
SuperAwesomeLTD/sa-mobile-sdk-android | superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/network/retrofit/OkHttpNetworkDataSource.kt | 1 | 1897 | package tv.superawesome.sdk.publisher.common.network.retrofit
import android.content.Context
import okhttp3.OkHttpClient
import okhttp3.Request
import okio.buffer
import okio.sink
import tv.superawesome.sdk.publisher.common.components.Logger
import tv.superawesome.sdk.publisher.common.datasources.NetworkDataSourceType
import tv.superawesome.sdk.publisher.common.models.UrlFileItem
import tv.superawesome.sdk.publisher.common.network.DataResult
import java.io.File
class OkHttpNetworkDataSource(
private val client: OkHttpClient,
private val applicationContext: Context,
private val logger: Logger,
) : NetworkDataSourceType {
override suspend fun getData(url: String): DataResult<String> {
logger.info("getData:url: $url")
val request = Request.Builder().url(url).build()
val response = client.newCall(request).execute()
return if (response.isSuccessful) {
DataResult.Success(response.body?.string() ?: "")
} else {
DataResult.Failure(Error("Could not GET data from $url"))
}
}
override suspend fun downloadFile(url: String): DataResult<String> {
logger.info("downloadFile")
val request = Request.Builder().url(url).build()
val response = client.newCall(request).execute()
val urlFileItem = UrlFileItem(url)
val downloadedFile = File(applicationContext.cacheDir, urlFileItem.fileName)
return try {
val sink = downloadedFile.sink().buffer()
sink.writeAll(response.body!!.source())
sink.close()
logger.success("File download successful with path: ${downloadedFile.absolutePath}")
DataResult.Success(downloadedFile.absolutePath)
} catch (e: Exception) {
logger.error("File download error", e)
DataResult.Failure(Error(e.localizedMessage))
}
}
} | lgpl-3.0 | 0e281cb72babd5178997320949df5b31 | 36.96 | 96 | 0.6932 | 4.615572 | false | false | false | false |
chrislo27/Baristron | src/chrislo27/discordbot/impl/baristron/BotBaristron.kt | 1 | 5382 | /*
* 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 chrislo27.discordbot.impl.baristron
import chrislo27.discordbot.Bot
import chrislo27.discordbot.Userdata
import chrislo27.discordbot.cmd.Command
import chrislo27.discordbot.cmd.CommandContext
import chrislo27.discordbot.cmd.CommandHandler
import chrislo27.discordbot.cmd.HelpData
import chrislo27.discordbot.cmd.impl.*
import chrislo27.discordbot.impl.baristron.cmds.TagCommand
import chrislo27.discordbot.impl.baristron.cmds.TestingCommand
import chrislo27.discordbot.impl.baristron.goat.GoatCommand
import chrislo27.discordbot.tick.TickManager
import chrislo27.discordbot.util.*
import sx.blah.discord.api.ClientBuilder
import sx.blah.discord.api.events.EventSubscriber
import sx.blah.discord.api.events.IListener
import sx.blah.discord.handle.impl.events.MessageReceivedEvent
import sx.blah.discord.handle.impl.events.ReadyEvent
import sx.blah.discord.handle.obj.IGuild
import sx.blah.discord.handle.obj.IUser
import sx.blah.discord.util.EmbedBuilder
import sx.blah.discord.util.MessageList
import java.util.*
class Baristron(builder: ClientBuilder) : Bot<Baristron>(builder) {
override val commandHandler: CommandHandler<Baristron> = CommandHandler(this)
init {
tickManager = TickManager(this)
MessageList.setEfficiency(client, MessageList.EfficiencyLevel.MEDIUM)
commandHandler.addCommands {
it.add(CommandsCommand(Permission.DUNGEON, "commands", "cmds"))
it.add(HelpCommand(Permission.DUNGEON, "help", "?"))
it.add(ChangeUsernameCommand(Permission.ADMIN, "changeusername"))
it.add(ChangeNicknameCommand(Permission.ADMIN, "changenickname"))
it.add(ChangeAvatarCommand(Permission.ADMIN, "changeavatar"))
it.add(object : ChangePrefixCommand<Baristron>(Permission.MODERATOR, "changeprefix") {
override fun savePrefix(context: CommandContext<Baristron>, prefix: String) {
Userdata.setString("baristron_prefix_${context.guild!!.id}", prefix)
}
})
it.add(object : Command<Baristron>(Permission.NORMAL, "info") {
override fun handle(context: CommandContext<Baristron>) {
sendMessage(builder(context.channel).withEmbed(EmbedBuilder().withTitle("About this bot").withColor(
Utils.random.nextInt(0xFFFFFF + 1)).withThumbnail(client.ourUser.avatarURL).withDesc(
"[Baristron](https://github.com/chrislo27/Baristron) is a multi-purpose bot by" +
" [chrislo27](https://github.com/chrislo27) written in " +
"Kotlin using the " +
"[Discord4J](https://github.com/austinv11/Discord4J) library." +
" It was originally written in Java, and thus this current version" +
" will not have 100% of the same features as the old version did.")
.appendField("Experimental!",
"This experimental version of Baristron is called Baristron Neo.",
false).build()))
}
override fun getHelp(): HelpData = HelpData("See info about this bot.",
linkedMapOf("" to "See info about this bot."))
})
it.add(TestingCommand(Permission.ADMIN, "test"))
it.add(TagCommand(Permission.NORMAL, "tag", "tags"))
it.add(GoatCommand(Permission.ADMIN, "goat"))
it.add(ServerLockdownCommand(Permission.NORMAL, "lockdownserver"))
}
client.dispatcher.registerListener(GuildUpdateListener())
client.dispatcher.registerListener(IListener { it: ReadyEvent ->
// client.dnd("testing the v6 waters")
})
}
@EventSubscriber
fun onMessage(event: MessageReceivedEvent) {
commandHandler.handleEvent(event)
}
override fun tickUpdate() {
}
override fun getPrefix(guild: IGuild?): String {
return Userdata.getString("baristron_prefix_" + guild?.id, "%%")!! // FIXME %% -> %
}
override fun getEmbeddedPrefix(guild: IGuild?): String? {
return Utils.repeat(getPrefix(guild), 3)
}
override fun getPermission(user: IUser, guild: IGuild?): Permission {
if (user == client.applicationOwner) return Permission.ADMIN
var p = Permission.valueOf(
Userdata.getString("permission_" + user.id, Permission.NORMAL.getName())!!.toUpperCase(Locale.ROOT))
if (p.getOrdinal() < Permission.MODERATOR.getOrdinal() && guild?.owner == user) {
p = Permission.MODERATOR
}
return p
}
override fun setPermission(user: IUser, perm: IPermission?) {
if (perm == null) {
Userdata.removeString("permission_" + user.id)
return
}
Userdata.setString("permission_" + user.id, perm.getName())
}
override fun onLogin() {
}
override fun onLogout() {
}
}
enum class Permission : IPermission {
DUNGEON,
NORMAL,
TRUSTED,
DISCORD4J,
MODLOG,
MODERATOR,
ADMIN;
override fun getName(): String {
return this.name
}
override fun getOrdinal(): Int {
return this.ordinal
}
}
| gpl-3.0 | 1aa11a2817171b80b5cc51a771f62715 | 32.6375 | 105 | 0.72631 | 3.776842 | false | false | false | false |
tasks/tasks | app/src/main/java/com/todoroo/andlib/sql/Criterion.kt | 1 | 1129 | package com.todoroo.andlib.sql
abstract class Criterion(val operator: Operator) {
protected abstract fun populate(): String
override fun toString() = "(${populate()})"
companion object {
@JvmStatic fun and(criterion: Criterion?, vararg criterions: Criterion?): Criterion {
return object : Criterion(Operator.and) {
override fun populate() = criterion.plus(criterions).joinToString(" AND ")
}
}
@JvmStatic fun or(criterion: Criterion?, vararg criterions: Criterion): Criterion {
return object : Criterion(Operator.or) {
override fun populate() = criterion.plus(criterions).joinToString(" OR ")
}
}
fun exists(query: Query): Criterion {
return object : Criterion(Operator.exists) {
override fun populate() = "EXISTS ($query)"
}
}
operator fun <T> T.plus(tail: Array<out T>): List<T> {
val list = ArrayList<T>(1 + tail.size)
list.add(this)
list.addAll(tail)
return list
}
}
} | gpl-3.0 | cdece9e71b31941b81892f8c1fdf9b43 | 29.540541 | 93 | 0.567759 | 4.723849 | false | false | false | false |
ofalvai/BPInfo | app/src/main/java/com/ofalvai/bpinfo/notifications/TokenUploadWorker.kt | 1 | 3287 | /*
* Copyright 2018 Olivér Falvai
*
* 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.ofalvai.bpinfo.notifications
import android.content.Context
import androidx.concurrent.futures.CallbackToFutureAdapter
import androidx.work.ListenableWorker
import androidx.work.WorkerFactory
import androidx.work.WorkerParameters
import com.android.volley.VolleyError
import com.google.common.util.concurrent.ListenableFuture
import com.ofalvai.bpinfo.api.subscription.SubscriptionClient
import com.ofalvai.bpinfo.util.Analytics
import timber.log.Timber
class TokenUploadWorker(
appContext: Context,
private val params: WorkerParameters,
private val subscriptionClient: SubscriptionClient,
private val analytics: Analytics
) : ListenableWorker(appContext, params) {
companion object {
const val TAG = "TokenUploadWorker"
const val KEY_NEW_TOKEN = "new_token"
const val KEY_OLD_TOKEN = "old_token"
}
class Factory(
private val subscriptionClient: SubscriptionClient,
private val analytics: Analytics
) : WorkerFactory() {
override fun createWorker(
appContext: Context,
workerClassName: String,
workerParameters: WorkerParameters
): ListenableWorker? {
return if (workerClassName == TokenUploadWorker::class.java.name) {
TokenUploadWorker(appContext, workerParameters, subscriptionClient, analytics)
} else {
null
}
}
}
override fun startWork(): ListenableFuture<Result> {
val newToken: String? = params.inputData.getString(KEY_NEW_TOKEN)
val oldToken: String? = params.inputData.getString(KEY_OLD_TOKEN)
return CallbackToFutureAdapter.getFuture { completer ->
if (newToken != null && oldToken != null) {
subscriptionClient.replaceToken(
oldToken,
newToken,
object : SubscriptionClient.TokenReplaceCallback {
override fun onTokenReplaceSuccess() {
Timber.d("New token successfully uploaded")
completer.set(Result.success())
}
override fun onTokenReplaceError(error: VolleyError) {
completer.set(Result.failure())
Timber.d(error, "New token upload unsuccessful")
analytics.logException(error)
}
})
} else {
Timber.w("Not uploading invalid tokens; old: %s, new: %s", oldToken, newToken)
completer.set(Result.failure())
}
}
}
}
| apache-2.0 | 9c4c4f56c3f8f9c202b7da72326036df | 36.340909 | 94 | 0.634814 | 5.078825 | false | false | false | false |
RedstonerServer/Parcels | src/main/kotlin/io/dico/parcels2/command/AbstractParcelCommands.kt | 1 | 2791 | package io.dico.parcels2.command
import io.dico.dicore.command.*
import io.dico.dicore.command.registration.reflect.ICommandInterceptor
import io.dico.dicore.command.registration.reflect.ICommandReceiver
import io.dico.parcels2.*
import io.dico.parcels2.PlayerProfile.Real
import io.dico.parcels2.PlayerProfile.Unresolved
import io.dico.parcels2.util.ext.hasPermAdminManage
import io.dico.parcels2.util.ext.parcelLimit
import org.bukkit.entity.Player
import org.bukkit.plugin.Plugin
import java.lang.reflect.Method
abstract class AbstractParcelCommands(val plugin: ParcelsPlugin) : ICommandInterceptor {
override fun getReceiver(context: ExecutionContext, target: Method, cmdName: String): ICommandReceiver {
return getParcelCommandReceiver(plugin.parcelProvider, context, target, cmdName)
}
override fun getCoroutineContext(context: ExecutionContext?, target: Method?, cmdName: String?): Any {
return plugin.coroutineContext
}
protected fun checkConnected(action: String) {
if (!plugin.storage.isConnected) err("Parcels cannot $action right now because of a database error")
}
protected suspend fun checkParcelLimit(player: Player, world: ParcelWorld) {
if (player.hasPermAdminManage) return
val numOwnedParcels = plugin.storage.getOwnedParcels(PlayerProfile(player)).await()
.filter { it.worldId.equals(world.id) }.size
val limit = player.parcelLimit
if (numOwnedParcels >= limit) {
err("You have enough plots for now")
}
}
protected suspend fun toPrivilegeKey(profile: PlayerProfile): PrivilegeKey = when (profile) {
is Real -> profile
is Unresolved -> profile.tryResolveSuspendedly(plugin.storage)
?: throw CommandException()
else -> throw CommandException()
}
protected fun areYouSureMessage(context: ExecutionContext): String {
val command = (context.route + context.original).joinToString(" ") + " -sure"
return "Are you sure? You cannot undo this action!\n" +
"Run \"/$command\" if you want to go through with this."
}
protected fun Job.reportProgressUpdates(context: ExecutionContext, action: String): Job =
onProgressUpdate(1000, 1000) { progress, elapsedTime ->
val alt = context.getFormat(EMessageType.NUMBER)
val main = context.getFormat(EMessageType.INFORMATIVE)
context.sendMessage(
EMessageType.INFORMATIVE, false, "$action progress: $alt%.02f$main%%, $alt%.2f${main}s elapsed"
.format(progress * 100, elapsedTime / 1000.0)
)
}
}
fun err(message: String): Nothing = throw CommandException(message) | gpl-2.0 | 0eb6321d8289863f4a8ebe31ca403f93 | 41.640625 | 111 | 0.689 | 4.409163 | false | false | false | false |
nextcloud/android | app/src/androidTest/java/com/owncloud/android/datamodel/FileDataStorageManagerContentResolverIT.kt | 1 | 2320 | /*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.datamodel
import org.junit.Assert
import org.junit.Test
class FileDataStorageManagerContentResolverIT : FileDataStorageManagerIT() {
companion object {
private const val MANY_FILES_AMOUNT = 5000
}
override fun before() {
sut = FileDataStorageManager(user, targetContext.contentResolver)
super.before()
}
/**
* only on FileDataStorageManager
*/
@Test
fun testFolderWithManyFiles() {
// create folder
val folderA = OCFile("/folderA/")
folderA.setFolder().parentId = sut.getFileByDecryptedRemotePath("/")!!.fileId
sut.saveFile(folderA)
Assert.assertTrue(sut.fileExists("/folderA/"))
Assert.assertEquals(0, sut.getFolderContent(folderA, false).size)
val folderAId = sut.getFileByDecryptedRemotePath("/folderA/")!!.fileId
// create files
val newFiles = (1..MANY_FILES_AMOUNT).map {
val file = OCFile("/folderA/file$it")
file.parentId = folderAId
sut.saveFile(file)
val storedFile = sut.getFileByDecryptedRemotePath("/folderA/file$it")
Assert.assertNotNull(storedFile)
storedFile
}
// save files in folder
sut.saveFolder(
folderA,
newFiles,
ArrayList()
)
// check file count is correct
Assert.assertEquals(MANY_FILES_AMOUNT, sut.getFolderContent(folderA, false).size)
}
}
| gpl-2.0 | a3929918f516f9e2c91ec7b7d94b2f05 | 32.142857 | 89 | 0.667672 | 4.649299 | false | false | false | false |
programingjd/server | src/test/kotlin/info/jdavid/asynk/server/EchoTests.kt | 1 | 3704 | package info.jdavid.asynk.server
import info.jdavid.asynk.core.asyncConnect
import info.jdavid.asynk.core.asyncRead
import info.jdavid.asynk.core.asyncWrite
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.channels.toList
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.StandardSocketOptions
import java.nio.ByteBuffer
import java.nio.channels.AsynchronousSocketChannel
import kotlin.coroutines.coroutineContext
class EchoTests {
@Test
fun echo() {
Server(object: Handler<Unit> {
override suspend fun context(others: Collection<*>?) = Unit
override suspend fun connect(remoteAddress: InetSocketAddress) = true
override suspend fun handle(socket: AsynchronousSocketChannel, remoteAddress: InetSocketAddress,
buffer: ByteBuffer, context: Unit) {
while (withTimeout(5000L) { socket.asyncRead(buffer) } > -1) {
(buffer.flip() as ByteBuffer).apply {
while (remaining() > 0) this.also { withTimeout(5000L) { socket.asyncWrite(it) } }
}
buffer.flip()
}
}
}).use {
//Thread.sleep(20000L)
runBlocking {
awaitAll(
async {
AsynchronousSocketChannel.open().use {
it.setOption(StandardSocketOptions.TCP_NODELAY, true)
it.setOption(StandardSocketOptions.SO_REUSEADDR, true)
it.asyncConnect(InetSocketAddress(InetAddress.getLoopbackAddress(), 8080))
ByteBuffer.wrap("abc\r\ndef\r\n".toByteArray()).apply {
while (remaining() > 0) it.asyncWrite(this)
}
delay(100)
ByteBuffer.wrap("ghi\r\njkl\r\nmno".toByteArray()).apply {
while (remaining() > 0) it.asyncWrite(this)
}
it.shutdownOutput()
val buffer = ByteBuffer.allocate(128)
assertEquals(23, aRead(it, buffer))
assertEquals("abc\r\ndef\r\nghi\r\njkl\r\nmno",
String(ByteArray(23).apply { (buffer.flip() as ByteBuffer).get(this) }))
}
},
async {
AsynchronousSocketChannel.open().use {
it.setOption(StandardSocketOptions.TCP_NODELAY, true)
it.setOption(StandardSocketOptions.SO_REUSEADDR, true)
it.asyncConnect(InetSocketAddress(InetAddress.getLoopbackAddress(), 8080))
ByteBuffer.wrap("123\r\n".toByteArray()).apply {
while (remaining() > 0) it.asyncWrite(this)
}
delay(50)
ByteBuffer.wrap("456\r\n789".toByteArray()).apply {
while (remaining() > 0) it.asyncWrite(this)
}
it.shutdownOutput()
val buffer = ByteBuffer.allocate(128)
assertEquals(13, aRead(it, buffer))
assertEquals("123\r\n456\r\n789",
String(ByteArray(13).apply { (buffer.flip() as ByteBuffer).get(this) }))
}
}
)
}
}
}
@Suppress("EXPERIMENTAL_API_USAGE")
private suspend fun aRead(socket: AsynchronousSocketChannel, buffer: ByteBuffer) =
CoroutineScope(coroutineContext).produce {
while (true) {
val n = socket.asyncRead(buffer)
if (n > 0) send(n) else break
}
close()
}.toList().sum()
}
| apache-2.0 | 08c1369dc69094fc097dcd2dc5f68a3a | 37.583333 | 102 | 0.617981 | 4.567201 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/main/java/be/florien/anyflow/injection/ApplicationModule.kt | 1 | 4910 | package be.florien.anyflow.injection
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.media.AudioManager
import android.os.Build
import android.os.Environment
import androidx.lifecycle.LiveData
import be.florien.anyflow.AnyFlowApp
import be.florien.anyflow.data.DataRepository
import be.florien.anyflow.data.local.LibraryDatabase
import be.florien.anyflow.data.server.AmpacheConnection
import be.florien.anyflow.data.user.AuthPersistence
import be.florien.anyflow.data.user.AuthPersistenceKeystore
import be.florien.anyflow.feature.alarms.AlarmActivity
import be.florien.anyflow.feature.alarms.AlarmsSynchronizer
import be.florien.anyflow.player.PlayerService
import com.facebook.stetho.okhttp3.StethoInterceptor
import com.google.android.exoplayer2.database.ExoDatabaseProvider
import com.google.android.exoplayer2.offline.DownloadManager
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource
import com.google.android.exoplayer2.upstream.cache.Cache
import com.google.android.exoplayer2.upstream.cache.NoOpCacheEvictor
import com.google.android.exoplayer2.upstream.cache.SimpleCache
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import java.util.concurrent.Executor
import javax.inject.Named
import javax.inject.Singleton
/**
* Provide elements used through all the application state
*/
@Module
class ApplicationModule {
companion object {
private const val PREFERENCE_NAME = "anyflow_preferences"
}
@Singleton
@Provides
fun providePreferences(context: Context): SharedPreferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE)
@Singleton
@Provides
fun provideOkHttp(): OkHttpClient = OkHttpClient.Builder().addNetworkInterceptor(StethoInterceptor()).build()
@Singleton
@Provides
fun provideAuthPersistence(preferences: SharedPreferences, context: Context): AuthPersistence = AuthPersistenceKeystore(preferences, context)
@Singleton
@Provides
fun provideAmpacheConnection(authPersistence: AuthPersistence, context: Context, sharedPreferences: SharedPreferences): AmpacheConnection =
AmpacheConnection(authPersistence, (context.applicationContext as AnyFlowApp), sharedPreferences)
@Provides
fun provideAmpacheConnectionStatus(connection: AmpacheConnection): LiveData<AmpacheConnection.ConnectionStatus> = connection.connectionStatusUpdater
@Singleton
@Provides
fun provideLibrary(context: Context): LibraryDatabase = LibraryDatabase.getInstance(context)
@Singleton
@Provides
fun provideCacheDataBaseProvider(context: Context): ExoDatabaseProvider = ExoDatabaseProvider(context)
@Singleton
@Provides
fun provideCache(context: Context, dbProvider: ExoDatabaseProvider): Cache = SimpleCache(
context.getExternalFilesDir(Environment.DIRECTORY_MUSIC) ?: context.noBackupFilesDir,
NoOpCacheEvictor(),
dbProvider)
@Singleton
@Provides
fun provideDownloadManager(context: Context, databaseProvider: ExoDatabaseProvider, cache: Cache): DownloadManager {
val dataSourceFactory = DefaultHttpDataSource.Factory()
val downloadExecutor = Executor { obj: Runnable -> obj.run() }
return DownloadManager(
context,
databaseProvider,
cache,
dataSourceFactory,
downloadExecutor)
}
@Provides
fun provideAlarmManager(context: Context): AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
@Provides
@Named("player")
fun providePlayerPendingIntent(context: Context): PendingIntent {
val intent = Intent(context, PlayerService::class.java)
intent.action = "ALARM"
if (Build.VERSION.SDK_INT >= 26) {
return PendingIntent.getForegroundService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
@Provides
@Named("alarm")
fun provideAlarmPendingIntent(context: Context): PendingIntent {
val intent = Intent(context, AlarmActivity::class.java)
return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
}
@Provides
fun provideAlarmsSynchronizer(alarmManager: AlarmManager, dataRepository: DataRepository, @Named("player") playerIntent: PendingIntent, @Named("alarm") alarmIntent: PendingIntent): AlarmsSynchronizer = AlarmsSynchronizer(alarmManager, dataRepository, alarmIntent, playerIntent)
@Provides
fun provideAudioManager(context: Context) = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
} | gpl-3.0 | 6fc6e4a413d36642c62e0c39f702b262 | 39.925 | 281 | 0.773931 | 5.056643 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise | imitate/src/main/java/com/engineer/imitate/KotlinRootActivity.kt | 1 | 14590 | package com.engineer.imitate
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.annotation.SuppressLint
import android.content.Intent
import android.content.res.Configuration
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.PopupMenu
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.engineer.imitate.model.FragmentItem
import com.engineer.imitate.ui.activity.ReverseGifActivity
import com.engineer.imitate.ui.widget.opensource.text.ActionMenu
import com.engineer.imitate.util.*
import com.example.cpp_native.app.NativeRoot
import com.gyf.immersionbar.ImmersionBar
import com.list.rados.fast_list.FastListAdapter
import com.list.rados.fast_list.bind
import com.skydoves.transformationlayout.onTransformationStartContainer
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_kotlin_root.*
import kotlinx.android.synthetic.main.content_kotlin_root.*
import kotlinx.android.synthetic.main.view_item.view.*
import org.apache.commons.io.FileUtils
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.concurrent.TimeUnit
@Route(path = Routes.INDEX)
@SuppressLint("LogNotTimber")
class KotlinRootActivity : AppCompatActivity() {
private val TAG = KotlinRootActivity::class.java.simpleName
private val ORIGINAL_URL = "file:///android_asset/index.html"
private lateinit var hybridHelper: HybridHelper
private var currentFragment: Fragment? = null
private lateinit var mLinearManager: LinearLayoutManager
private lateinit var mGridLayoutManager: GridLayoutManager
private lateinit var mLayoutManager: RecyclerView.LayoutManager
private var adapter: FastListAdapter<FragmentItem>? = null
override fun onCreate(savedInstanceState: Bundle?) {
onTransformationStartContainer()
super.onCreate(savedInstanceState)
ImmersionBar.with(this)
.fitsSystemWindows(true)
.statusBarColor(R.color.colorPrimary).init()
setContentView(R.layout.activity_kotlin_root)
setSupportActionBar(toolbar)
loadView()
jsonTest()
// autoStartPage()
NativeRoot.init()
NativeRoot.test()
val patchViewModel = ViewModelProvider(this)[PatchViewModel::class.java]
patchViewModel.copyFile()
}
private fun autoStartPage() {
val fragment: Fragment =
ARouter.getInstance().build("/anim/fresco").navigation(this) as Fragment
currentFragment = fragment
content.visibility = View.VISIBLE
index.visibility = View.GONE
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.content, fragment).commit()
}
private fun loadView() {
mLinearManager = LinearLayoutManager(this)
mGridLayoutManager = GridLayoutManager(this, 2)
mLayoutManager = mLinearManager
// if (isNetworkConnected()) {
// loadWebView()
// } else {
// }
loadRecyclerView()
// loadWebView()
gif.setOnClickListener {
// startActivity(Intent(this, ReverseGifActivity::class.java))
val bundle = transformationLayout.withView(transformationLayout, "myTransitionName")
val intent = Intent(this, ReverseGifActivity::class.java)
intent.putExtra("TransformationParams", transformationLayout.getParcelableParams())
startActivity(intent, bundle)
}
}
// <editor-fold defaultstate="collapsed" desc="拷贝一些文件到特定目录,不是每个手机都需要">
/**
* 拷贝一些文件到特定目录,不是每个手机都需要
*/
private fun personalCopy() {
val path = filesDir.absolutePath + "/gif/"
val fileDir = File(path)
val files = fileDir.listFiles()
files?.apply {
if (fileDir.exists()) {
val destDir = Environment.getExternalStorageDirectory()
for (file in this) {
Log.e(TAG, ": " + file.absolutePath)
Observable.just("")
.subscribeOn(Schedulers.io())
.subscribe {
FileUtils.copyFileToDirectory(file, destDir)
}
}
}
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="init fragments">
private fun initList(): MutableList<FragmentItem> {
return mutableListOf(
FragmentItem("/anim/entrance", "entrance"),
FragmentItem("/anim/dependency_injection", "dependency_injection"),
FragmentItem("/anim/rx_play", "rx_play"),
FragmentItem("/anim/motion_layout", "motion_layout"),
FragmentItem("/anim/github", "github features"),
FragmentItem("/anim/pure_3d_share", "3D shape"),
FragmentItem("/anim/circleLoading", "circle-loading"),
FragmentItem("/anim/coroutines", "coroutines"),
FragmentItem("/anim/recycler_view", "RecyclerView"),
FragmentItem("/anim/slide", "slide"),
FragmentItem("/anim/drawable_example", "drawable_example"),
FragmentItem("/anim/elevation", "elevation"),
FragmentItem("/anim/fresco", "fresco"),
FragmentItem("/anim/constraint", "constraint animation"),
FragmentItem("/anim/scroller", "scroller"),
FragmentItem("/anim/vh_fragment", "vh_fragment"),
FragmentItem("/anim/parallax", "parallax")
)
}
// </editor-fold>
private fun loadRecyclerView() {
hybrid.animate().alpha(0f).setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
super.onAnimationEnd(animation)
hybrid.visibility = View.GONE
recyclerView.visibility = View.VISIBLE
}
}).start()
val list = initList()
adapter = recyclerView.bind(list, R.layout.view_item) { item: FragmentItem, _: Int ->
desc.text = item.name
path.text = item.path
path.setOnClickListener {
AnimDelegate.apply(context, path, gif, shell_root)
}
more_menu.setOnClickListener {
showMenu(more_menu)
}
shell.setOnClickListener {
gif.hide()
val fragment: Fragment =
ARouter.getInstance().build(item.path).navigation(context) as Fragment
currentFragment = fragment
content.visibility = View.VISIBLE
index.visibility = View.GONE
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.content, fragment).commit()
updateState()
}
}.layoutManager(mLayoutManager)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
Log.e(TAG, "dy==$dy")
Log.e(TAG, "是否可以 scroll up==${recyclerView.canScrollVertically(-1)}")
Log.e(TAG, "是否可以 scroll down==${recyclerView.canScrollVertically(1)}")
}
})
}
}
private fun showMenu(view: View) {
val popupMenu = PopupMenu(this, view, Gravity.END)
popupMenu.menuInflater.inflate(R.menu.index_setting_menu, popupMenu.menu)
popupMenu.show()
}
@SuppressLint("SetJavaScriptEnabled")
private fun loadWebView() {
hybrid.animate().alpha(1f).setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
super.onAnimationEnd(animation)
hybrid.visibility = View.VISIBLE
recyclerView.visibility = View.GONE
}
}).start()
hybrid.settings.javaScriptEnabled = true
hybrid.settings.allowFileAccess = true
hybridHelper = HybridHelper(this)
hybridHelper.setOnItemClickListener(SimpleClickListener())
hybrid.addJavascriptInterface(hybridHelper, "hybrid")
hybrid.loadUrl(ORIGINAL_URL)
}
private inner class SimpleClickListener : HybridHelper.OnItemClickListener {
override fun reload() {
runOnUiThread {
loadRecyclerView()
}
}
@SuppressLint("RestrictedApi")
override fun onClick(fragment: Fragment, title: String) {
runOnUiThread {
if (!TextUtils.isEmpty(title)) {
setTitle(title)
}
content.visibility = View.VISIBLE
index.visibility = View.GONE
gif.hide()
currentFragment = fragment
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.content, fragment).commit()
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_kotlin_root, menu)
return true
}
private fun isNightMode(): Boolean {
val flag = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
return flag == Configuration.UI_MODE_NIGHT_YES
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
val item = menu?.findItem(R.id.theme_switch)
if (isNightMode()) {
item?.setIcon(R.drawable.ic_brightness_low_white_24dp)
item?.setTitle("日间模式")
} else {
item?.setIcon(R.drawable.ic_brightness_high_white_24dp)
item?.title = "夜间模式"
}
val change = menu?.findItem(R.id.action_change)
change?.isVisible = (recyclerView.visibility == View.VISIBLE)
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
if (content.visibility == View.VISIBLE) {
releaseFragment()
} else {
finish()
}
} else if (item.itemId == R.id.action_refresh) {
if (recyclerView.visibility == View.VISIBLE) {
loadWebView()
} else {
loadRecyclerView()
}
return true
} else if (item.itemId == R.id.action_change) {
if (recyclerView.visibility == View.VISIBLE) {
if (recyclerView.layoutManager == mLinearManager) {
mLayoutManager = mGridLayoutManager
} else {
mLayoutManager = mLinearManager
}
adapter?.layoutManager(mLayoutManager)?.notifyDataSetChanged()
return true
}
} else if (item.itemId == R.id.theme_switch) {
if (isNightMode()) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
SpUtil(this).saveBool(SpUtil.KEY_THEME_NIGHT_ON, false)
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
SpUtil(this).saveBool(SpUtil.KEY_THEME_NIGHT_ON, true)
}
// recreate()
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
if (content.visibility == View.VISIBLE) {
releaseFragment()
} else {
super.onBackPressed()
}
}
private fun releaseFragment() {
content.visibility = View.GONE
index.visibility = View.VISIBLE
gif.show()
Log.e(TAG, "fragments size = " + supportFragmentManager.fragments.size)
currentFragment?.let {
if (supportFragmentManager.fragments.size > 0) {
supportFragmentManager.beginTransaction()
.remove(it)
.commitAllowingStateLoss()
currentFragment = null
updateState()
}
}
}
private fun updateState() {
Observable.just(1)
.delay(1, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.doOnNext {
Log.e(TAG, "updateState: ======================================================\n")
Log.e(TAG, "fragments size = " + supportFragmentManager.fragments.size)
supportFragmentManager.fragments.forEach {
Log.e(
TAG,
"fragment [ ${it.javaClass.name} ] in activity [ ${it.activity?.javaClass?.simpleName} ]"
)
}
Log.e(TAG, "updateState: ======================================================\n")
}
.subscribe()
}
private fun jsonTest() {
val uri = "https://www.zhihu.com/search?q=%E5%88%A9%E7%89%A9%E6%B5%A6&type=content"
val parseUri = Uri.parse(uri)
Log.e(TAG, "type : " + parseUri::class.java.canonicalName)
Log.e(TAG, "query: ${parseUri.query}")
Log.e(TAG, "isOpaque: ${parseUri.isOpaque}")
val jsonArray = JSONArray()
for (i in 0..3) {
val jsonObj = JSONObject()
jsonObj.put("name", "name_$i")
jsonArray.put(jsonObj)
}
Log.e(TAG, "result ==$jsonArray")
}
override fun onDestroy() {
super.onDestroy()
hybrid.removeJavascriptInterface("hybrid")
}
}
| apache-2.0 | 5102f58804dfa776bfd5c86535343d51 | 36.112821 | 113 | 0.607918 | 4.91644 | false | false | false | false |
mockk/mockk | modules/mockk-agent/src/jvmMain/kotlin/io/mockk/proxy/jvm/transformation/InliningClassTransformer.kt | 1 | 6012 | package io.mockk.proxy.jvm.transformation
import io.mockk.proxy.MockKAgentLogger
import io.mockk.proxy.MockKInvocationHandler
import io.mockk.proxy.common.transformation.ClassTransformationSpecMap
import io.mockk.proxy.jvm.advice.ProxyAdviceId
import io.mockk.proxy.jvm.advice.jvm.JvmMockKConstructorProxyAdvice
import io.mockk.proxy.jvm.advice.jvm.JvmMockKHashMapStaticProxyAdvice
import io.mockk.proxy.jvm.advice.jvm.JvmMockKProxyAdvice
import io.mockk.proxy.jvm.advice.jvm.JvmMockKStaticProxyAdvice
import io.mockk.proxy.jvm.advice.jvm.MockHandlerMap
import io.mockk.proxy.jvm.dispatcher.JvmMockKDispatcher
import net.bytebuddy.ByteBuddy
import net.bytebuddy.asm.Advice
import net.bytebuddy.asm.AsmVisitorWrapper
import net.bytebuddy.description.ModifierReviewable.OfByteCodeElement
import net.bytebuddy.description.method.MethodDescription
import net.bytebuddy.dynamic.ClassFileLocator.Simple.of
import net.bytebuddy.matcher.ElementMatchers.*
import java.io.File
import java.lang.instrument.ClassFileTransformer
import java.security.ProtectionDomain
import java.util.concurrent.atomic.AtomicLong
internal class InliningClassTransformer(
private val log: MockKAgentLogger,
private val specMap: ClassTransformationSpecMap,
private val handlers: MockHandlerMap,
private val staticHandlers: MockHandlerMap,
private val constructorHandlers: MockHandlerMap,
private val byteBuddy: ByteBuddy
) : ClassFileTransformer {
private val restrictedMethods = setOf(
"java.lang.System.getSecurityManager"
)
private lateinit var advice: JvmMockKProxyAdvice
private lateinit var staticAdvice: JvmMockKStaticProxyAdvice
private lateinit var staticHashMapAdvice: JvmMockKHashMapStaticProxyAdvice
private lateinit var constructorAdvice: JvmMockKConstructorProxyAdvice
init {
class AdviceBuilder {
fun build() {
advice = JvmMockKProxyAdvice(handlers)
staticAdvice = JvmMockKStaticProxyAdvice(staticHandlers)
staticHashMapAdvice = JvmMockKHashMapStaticProxyAdvice(staticHandlers)
constructorAdvice = JvmMockKConstructorProxyAdvice(constructorHandlers)
JvmMockKDispatcher.set(advice.id, advice)
JvmMockKDispatcher.set(staticAdvice.id, staticAdvice)
JvmMockKDispatcher.set(staticHashMapAdvice.id, staticHashMapAdvice)
JvmMockKDispatcher.set(constructorAdvice.id, constructorAdvice)
}
}
AdviceBuilder().build()
}
override fun transform(
loader: ClassLoader?,
className: String,
classBeingRedefined: Class<*>,
protectionDomain: ProtectionDomain?,
classfileBuffer: ByteArray?
): ByteArray? {
val spec = specMap[classBeingRedefined]
?: return classfileBuffer
try {
val builder = byteBuddy.redefine(classBeingRedefined, of(classBeingRedefined.name, classfileBuffer))
.visit(FixParameterNamesVisitor(classBeingRedefined))
val type = builder
.run { if (spec.shouldDoSimpleIntercept) visit(simpleAdvice()) else this }
.run { if (spec.shouldDoStaticIntercept) visit(staticAdvice(className)) else this }
.run { if (spec.shouldDoConstructorIntercept) visit(constructorAdvice()) else this }
.make()
try {
val property = System.getProperty("io.mockk.classdump.path")
if (property != null) {
val nextIndex = classDumpIndex.incrementAndGet().toString()
val storePath = File(File(property, "inline"), nextIndex)
type.saveIn(storePath)
}
} catch (ex: Exception) {
log.trace(ex, "Failed to save file to a dump");
}
return type.bytes
} catch (e: Throwable) {
log.warn(e, "Failed to transform class $className")
return null
}
}
private fun simpleAdvice() =
Advice.withCustomMapping()
.bind<ProxyAdviceId>(ProxyAdviceId::class.java, advice.id)
.to(JvmMockKProxyAdvice::class.java)
.on(
isMethod<MethodDescription>()
.and(not<OfByteCodeElement>(isStatic<OfByteCodeElement>()))
.and(not<MethodDescription>(isDefaultFinalizer<MethodDescription>()))
)
private fun staticAdvice(className: String) =
Advice.withCustomMapping()
.bind<ProxyAdviceId>(ProxyAdviceId::class.java, staticProxyAdviceId(className))
.to(staticProxyAdvice(className))
.on(
isStatic<OfByteCodeElement>()
.and(not<MethodDescription>(isTypeInitializer<MethodDescription>()))
.and(not<MethodDescription>(isConstructor<MethodDescription>()))
.and(not<MethodDescription>(this::matchRestrictedMethods))
)
private fun matchRestrictedMethods(desc: MethodDescription) =
desc.declaringType.typeName + "." + desc.name in restrictedMethods
private fun constructorAdvice(): AsmVisitorWrapper.ForDeclaredMethods? {
return Advice.withCustomMapping()
.bind<ProxyAdviceId>(ProxyAdviceId::class.java, constructorAdvice.id)
.to(JvmMockKConstructorProxyAdvice::class.java)
.on(isConstructor())
}
// workaround #35
private fun staticProxyAdviceId(className: String) =
when (className) {
"java/util/HashMap" -> staticHashMapAdvice.id
else -> staticAdvice.id
}
// workaround #35
private fun staticProxyAdvice(className: String) =
when (className) {
"java/util/HashMap" -> JvmMockKHashMapStaticProxyAdvice::class.java
else -> JvmMockKStaticProxyAdvice::class.java
}
companion object {
val classDumpIndex = AtomicLong();
}
} | apache-2.0 | 9219fc0fc433c390a149770365adeb9a | 39.355705 | 112 | 0.676813 | 5.232376 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/controllers/main/CertificateListAdapter.kt | 1 | 4282 | package de.xikolo.controllers.main
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.ButterKnife
import de.xikolo.App
import de.xikolo.R
import de.xikolo.controllers.helper.DownloadViewHelper
import de.xikolo.models.Course
import de.xikolo.models.DownloadAsset
import de.xikolo.models.dao.EnrollmentDao
class CertificateListAdapter(private val fragment: CertificateListFragment, private val callback: OnCertificateCardClickListener) : RecyclerView.Adapter<CertificateListAdapter.CertificateViewHolder>() {
companion object {
val TAG: String = CertificateListAdapter::class.java.simpleName
}
private val courseList: MutableList<Course> = mutableListOf()
fun update(courseList: List<Course>) {
this.courseList.clear()
this.courseList.addAll(courseList)
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return courseList.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CertificateViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_certificate_list, parent, false)
return CertificateViewHolder(view)
}
override fun onBindViewHolder(holder: CertificateViewHolder, position: Int) {
val course = courseList[position]
holder.textTitle.text = course.title
holder.textTitle.setOnClickListener { _ -> callback.onCourseClicked(course.id) }
holder.container.removeAllViews()
fragment.activity?.let { activity ->
EnrollmentDao.Unmanaged.findForCourse(course.id)?.let { enrollment ->
if (course.certificates.confirmationOfParticipation.available) {
val dvh = DownloadViewHelper(
activity,
DownloadAsset.Certificate.ConfirmationOfParticipation(
enrollment.certificates.confirmationOfParticipationUrl,
course
),
App.instance.getString(R.string.course_confirmation_of_participation),
null,
App.instance.getString(R.string.course_certificate_not_achieved)
)
holder.container.addView(dvh.view)
}
if (course.certificates.recordOfAchievement.available) {
val dvh = DownloadViewHelper(
activity,
DownloadAsset.Certificate.RecordOfAchievement(
enrollment.certificates.recordOfAchievementUrl,
course
),
App.instance.getString(R.string.course_record_of_achievement),
null,
App.instance.getString(R.string.course_certificate_not_achieved)
)
holder.container.addView(dvh.view)
}
if (course.certificates.qualifiedCertificate.available) {
val dvh = DownloadViewHelper(
activity,
DownloadAsset.Certificate.QualifiedCertificate(
enrollment.certificates.qualifiedCertificateUrl,
course
),
App.instance.getString(R.string.course_qualified_certificate),
null,
App.instance.getString(R.string.course_certificate_not_achieved)
)
holder.container.addView(dvh.view)
}
}
}
}
interface OnCertificateCardClickListener {
fun onCourseClicked(courseId: String)
}
class CertificateViewHolder(view: View) : RecyclerView.ViewHolder(view) {
@BindView(R.id.textTitle)
lateinit var textTitle: TextView
@BindView(R.id.container)
lateinit var container: LinearLayout
init {
ButterKnife.bind(this, view)
}
}
}
| bsd-3-clause | de205031490854963b3cf7dc68dcdcd2 | 35.288136 | 202 | 0.606959 | 5.604712 | false | false | false | false |
adgvcxz/ViewModel | app/src/main/kotlin/com/adgvcxz/viewmodel/sample/SimpleRecyclerViewModel.kt | 1 | 3469 | package com.adgvcxz.viewmodel.sample
import android.view.View
import com.adgvcxz.IModel
import com.adgvcxz.IMutation
import com.adgvcxz.add
import com.adgvcxz.bindModel
import com.adgvcxz.recyclerviewmodel.*
import com.adgvcxz.viewmodel.sample.databinding.ItemTextViewBinding
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.item_loading.view.*
import java.util.*
import java.util.concurrent.TimeUnit
/**
* zhaowei
* Created by zhaowei on 2017/6/6.
*/
var initId = 0
class SimpleRecyclerViewModel : RecyclerViewModel() {
override var initModel: RecyclerModel =
RecyclerModel(null, hasLoadingItem = true, isAnim = true)
override fun request(refresh: Boolean): Observable<IMutation> {
return if (refresh) {
Observable.timer(3, TimeUnit.SECONDS)
.map { (0 until 10).map { TextItemViewModel() } }
.flatMap {
if (!refresh && currentModel().items.size > 30) {
Observable.concat(
Observable.just(UpdateData(it)),
Observable.just(RemoveLoadingItem)
)
} else {
Observable.just(UpdateData(it))
}
}
} else {
Observable.timer(100, TimeUnit.MILLISECONDS).map { LoadFailure }
}
}
}
class TextItemView : ItemBindingView<ItemTextViewBinding, TextItemViewModel> {
override val layoutId: Int = R.layout.item_text_view
override fun generateViewBinding(view: View): ItemTextViewBinding {
return ItemTextViewBinding.bind(view)
}
override fun bind(
binding: ItemTextViewBinding,
viewModel: TextItemViewModel,
position: Int,
disposable: CompositeDisposable
) {
viewModel.bindModel(disposable) {
add({ content }, { binding.textView.text = this })
}
}
}
class TextItemViewModel : RecyclerItemViewModel<TextItemViewModel.Model>() {
override var initModel: Model = Model()
class ValueChangeMutation(val value: String) : IMutation
override fun transformMutation(mutation: Observable<IMutation>): Observable<IMutation> {
val value = RxBus.instance.toObservable(ValueChangeEvent::class.java)
.filter { it.id == currentModel().id }
.map { ValueChangeMutation(it.value) }
return Observable.merge(value, mutation)
}
override fun scan(model: Model, mutation: IMutation): Model {
when (mutation) {
is ValueChangeMutation -> model.content = mutation.value
}
return model
}
class Model : IModel {
var content: String = UUID.randomUUID().toString() + "==== $initId"
var id = initId++
}
}
class LoadingItemView : IDefaultView<LoadingItemViewModel> {
override val layoutId: Int = R.layout.item_loading
override fun bind(viewHolder: ItemViewHolder, viewModel: LoadingItemViewModel, position: Int) {
with(viewHolder.itemView) {
viewModel.bindModel(viewHolder.disposables) {
add({ state != LoadingItemViewModel.Failure }, {
loading.visibility = if (this) View.VISIBLE else View.GONE
failed.visibility = if (this) View.GONE else View.VISIBLE
})
}
}
}
} | apache-2.0 | ac4771e391e240d49e416dfab2109ab0 | 31.429907 | 99 | 0.630441 | 4.700542 | false | false | false | false |
kiruto/kotlin-android-mahjong | app/src/main/java/dev/yuriel/kotmvp/layout/LayoutElement.kt | 1 | 3448 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[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 dev.yuriel.kotmvp.layout
import android.graphics.YuvImage
import com.badlogic.gdx.scenes.scene2d.Actor
import dev.yuriel.kotmvp.LayoutWrongException
import java.util.*
/**
* Created by yuriel on 8/10/16.
*/
abstract class LayoutElement {
companion object {
val children = mutableMapOf<String, LayoutElement>()
var unit: Number = 1
}
abstract val id: String
protected val attributes = hashMapOf<String, String>()
open val attr = LayoutPosition(0F, 0F, 0F, 0F)
open var actor: Actor? = null
set(value) {
field = value
if (attr.size.width == 0F && attr.size.height == 0F) {
attr.size.width = value?.width?: 0F
attr.size.height = value?.height?: 0F
}
}
var top: Number? = null
get() = attr.top()
private set
var right: Number? = null
get() = attr.right()
private set
var bottom: Number? = null
get() = attr.bottom()
private set
var left: Number? = null
get() = attr.left()
private set
var width: Number? = null
get() = attr.size.width
set(value) {
field = value?.toFloat()?: 0L * unit.toFloat()
setW(value?: field?: 0)
}
var height: Number? = null
get() = attr.size.height
set(value) {
field = value?.toFloat()?: 0L * unit.toFloat()
setH(value?: field?: 0)
}
fun actor(init: Actor.() -> Unit) {
actor?.init()
}
private fun setW(width: Number) {
attr.size.width = width.toFloat() * unit.toFloat()
}
private fun setH(height: Number) {
attr.size.height = height.toFloat() * unit.toFloat()
}
protected operator fun get(name: String): LayoutElement? = children[name]
protected fun <T: LayoutElement> layout(layout: T, init: T.() -> Unit): T {
if (children.containsKey(layout.id)) {
throw LayoutWrongException()
}
layout.init()
children.put(layout.id, layout)
layout.actor?.setPosition(layout.attr.ghostOrigin.first!!, layout.attr.ghostOrigin.second!!)
layout.actor?.setSize(layout.attr.size.width, layout.attr.size.height)
return layout
}
} | mit | 0bdf2f5a0ed5cd5354309d044e531068 | 32.813725 | 100 | 0.636601 | 4.085308 | false | false | false | false |
rhdunn/marklogic-intellij-plugin | src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/api/EvalRequestBuilder.kt | 1 | 1743 | /*
* Copyright (C) 2017-2018 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.marklogic.api
import java.util.HashMap
abstract class EvalRequestBuilder protected constructor() {
var contentDatabase: String? = null
var transactionID: String? = null
private var xquery: String? = null
@Suppress("PropertyName")
var XQuery: String?
get() = xquery
set(xquery) {
this.xquery = xquery
this.javascript = null // There can only be one!
}
private var javascript: String? = null
var javaScript: String?
get() = javascript
set(javascript) {
this.xquery = null // There can only be one!
this.javascript = javascript
}
private val vars = HashMap<QName, Item>()
val variableNames get(): Set<QName> =
vars.keys
fun addVariables(variables: Map<QName, Item>) {
for ((key, value) in variables) {
vars.put(key, value)
}
}
fun addVariable(name: QName, value: Item) {
vars[name] = value
}
fun getVariable(name: QName): Item {
return vars[name]!!
}
abstract fun build(): Request
}
| apache-2.0 | a586ba27b0649d5f2f8fc93436177a96 | 28.05 | 75 | 0.644291 | 4.240876 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-CSS-JS/src/main/kotlin/o/katydid/css/styles/builders/KatydidOverflowStyleBuilder.kt | 1 | 2088 | //
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package o.katydid.css.styles.builders
import o.katydid.css.styles.KatydidStyle
import o.katydid.css.types.EOverflow
import o.katydid.css.types.EOverflowWrap
import o.katydid.css.types.EResize
//---------------------------------------------------------------------------------------------------------------------
/**
* Builder class for setting overflow properties of a given [style] from a nested block.
*/
@KatydidStyleBuilderDsl
class KatydidOverflowStyleBuilder(
private val style: KatydidStyle
) {
fun x(value: EOverflow) =
style.overflowX(value)
fun y(value: EOverflow) =
style.overflowY(value)
fun wrap(value: EOverflowWrap) =
style.overflowWrap(value)
}
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.overflow(build: KatydidOverflowStyleBuilder.() -> Unit) =
KatydidOverflowStyleBuilder(this).build()
fun KatydidStyle.overflow(x: EOverflow, y: EOverflow = x) =
setXyProperty("overflow", x, y)
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.overflowX(value: EOverflow) =
setProperty("overflow-x", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.overflowY(value: EOverflow) =
setProperty("overflow-y", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.overflowWrap(value: EOverflowWrap) =
setProperty("overflow-wrap", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.resize(value: EResize) =
setProperty("resize", "$value")
//---------------------------------------------------------------------------------------------------------------------
| apache-2.0 | 8fa2f04d647ebef51f6f56e9ce9ef2d7 | 32.142857 | 119 | 0.431034 | 5.931818 | false | false | false | false |
jpeddicord/speedofsound | src/net/codechunk/speedofsound/util/SliderPreference.kt | 1 | 4102 | package net.codechunk.speedofsound.util
import android.content.Context
import android.content.res.TypedArray
import android.preference.DialogPreference
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.TextView
import net.codechunk.speedofsound.R
/**
* A preference that is displayed as a seek bar.
*/
open class SliderPreference(context: Context, attrs: AttributeSet) : DialogPreference(context, attrs), OnSeekBarChangeListener {
/**
* Seek bar widget to control preference value.
*/
protected var seekBar: SeekBar? = null
/**
* Text view displaying the value of the seek bar.
*/
private var valueDisplay: TextView? = null
/**
* Dialog view.
*/
protected var view: View? = null
/**
* Minimum value.
*/
protected val minValue: Int
/**
* Maximum value.
*/
protected val maxValue: Int
/**
* Units of this preference.
*/
protected var units: String? = null
/**
* Current value.
*/
protected var value: Int = 0
init {
this.minValue = attrs.getAttributeIntValue(LOCAL_NS, "minValue", 0)
this.maxValue = attrs.getAttributeIntValue(LOCAL_NS, "maxValue", 0)
this.units = attrs.getAttributeValue(LOCAL_NS, "units")
}
/**
* Set the initial value.
* Needed to properly load the default value.
*/
override fun onSetInitialValue(restorePersistedValue: Boolean, defaultValue: Any?) {
if (restorePersistedValue) {
// Restore existing state
this.value = this.getPersistedInt(-1)
} else {
// Set default state from the XML attribute
this.value = defaultValue as Int
persistInt(this.value)
}
}
/**
* Support loading a default value.
*/
override fun onGetDefaultValue(a: TypedArray, index: Int): Any {
return a.getInteger(index, -1)
}
/**
* Set up the preference display.
*/
override fun onCreateDialogView(): View {
// reload the persisted value since onSetInitialValue is only performed once
// for the activity, not each time the preference is opened
this.value = getPersistedInt(-1)
// load the layout
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
this.view = inflater.inflate(R.layout.slider_preference_dialog, null)
// setup the slider
this.seekBar = this.view!!.findViewById<View>(R.id.slider_preference_seekbar) as SeekBar
this.seekBar!!.max = this.maxValue - this.minValue
this.seekBar!!.progress = this.value - this.minValue
this.seekBar!!.setOnSeekBarChangeListener(this)
this.valueDisplay = this.view!!.findViewById<View>(R.id.slider_preference_value) as TextView
this.updateDisplay()
return this.view!!
}
/**
* Save on dialog close.
*/
override fun onDialogClosed(positiveResult: Boolean) {
super.onDialogClosed(positiveResult)
if (!positiveResult) {
return
}
if (shouldPersist()) {
this.persistInt(this.value)
}
this.notifyChanged()
}
protected fun updateDisplay() {
var text = this.value.toString()
if (this.units != null) {
text += this.units
}
this.valueDisplay!!.text = text
}
/**
* Updated the displayed value on change.
*/
override fun onProgressChanged(seekBar: SeekBar, value: Int, fromTouch: Boolean) {
this.value = value + this.minValue
this.updateDisplay()
}
override fun onStartTrackingTouch(sb: SeekBar) {}
override fun onStopTrackingTouch(sb: SeekBar) {}
companion object {
/**
* Our custom namespace for this preference.
*/
protected const val LOCAL_NS = "http://schemas.android.com/apk/res-auto"
}
}
| gpl-2.0 | aea6b19eed549ea3af4d699f2bb98e56 | 26.165563 | 128 | 0.632374 | 4.598655 | false | false | false | false |
mctoyama/PixelClient | src/main/kotlin/org/pixelndice/table/pixelclient/connection/main/State02WaitingProtocolVersion.kt | 1 | 1513 | package org.pixelndice.table.pixelclient.connection.main
import org.apache.logging.log4j.LogManager
import org.pixelndice.table.pixelclient.ApplicationBus
import org.pixelndice.table.pixelclient.PixelResourceBundle
import org.pixelndice.table.pixelprotocol.Protobuf
import java.text.MessageFormat
private val logger = LogManager.getLogger(State02WaitingProtocolVersion::class.java)
class State02WaitingProtocolVersion : State {
override fun process(ctx: Context) {
val packet = ctx.packet
if (packet != null) {
if (packet.payloadCase == Protobuf.Packet.PayloadCase.VERSIONOK) {
logger.info("Procol check version ok")
ctx.state = State03SendingAuthRequest()
ctx.process()
} else if( packet.payloadCase == Protobuf.Packet.PayloadCase.VERSIONERROR){
logger.fatal("Wrong version, update your client!")
ApplicationBus.post(ApplicationBus.SystemFailure())
} else {
val message = "Expecting VERSIONOK / VERSIONERROR, instead received: $packet. IP: ${ctx.channel.address}"
logger.fatal(message)
val resp = Protobuf.Packet.newBuilder()
val rend = Protobuf.EndWithError.newBuilder()
rend.reason = message
resp.setEndWithError(rend)
ctx.packet = resp.build()
ApplicationBus.post(ApplicationBus.SystemFailure())
}
}
}
}
| bsd-2-clause | 082d1674b0cf06627a8cec426953c3e5 | 30.520833 | 121 | 0.644415 | 4.928339 | false | false | false | false |
oldergod/red | app/src/main/java/com/benoitquenaudon/tvfoot/red/util/CircleTransform.kt | 1 | 1125 | package com.benoitquenaudon.tvfoot.red.util
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Paint.ANTI_ALIAS_FLAG
import android.graphics.Paint.DITHER_FLAG
import android.graphics.Paint.FILTER_BITMAP_FLAG
import android.graphics.Shader.TileMode.CLAMP
import androidx.core.graphics.createBitmap
import com.squareup.picasso.Transformation
object CircleTransform : Transformation {
override fun transform(source: Bitmap): Bitmap {
val size = minOf(source.width, source.height)
val x = (source.width - size) / 2
val y = (source.height - size) / 2
val squared = Bitmap.createBitmap(source, x, y, size, size)
val result = createBitmap(size, size)
val canvas = Canvas(result)
val paint = Paint(FILTER_BITMAP_FLAG or DITHER_FLAG or ANTI_ALIAS_FLAG)
paint.shader = BitmapShader(squared, CLAMP, CLAMP)
val r = size / 2f
canvas.drawCircle(r, r, r, paint)
if (source != result) {
source.recycle()
}
return result
}
override fun key(): String = javaClass.name
} | apache-2.0 | 9363b64c5fa55b7cfcac8551b5dfbdd6 | 28.631579 | 75 | 0.736889 | 3.865979 | false | false | false | false |
mswift42/apg | Wo4/app/src/main/java/mswift42/com/github/wo4/StopWatchFragment.kt | 1 | 3316 | package mswift42.com.github.wo4
import android.os.Bundle
import android.os.Handler
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import kotlinx.android.synthetic.main.fragment_stop_watch.*
/**
* A simple [Fragment] subclass.
*/
class StopWatchFragment : Fragment(), View.OnClickListener {
private var seconds = 0;
private var running = false;
private var wasRunning = false;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
seconds = savedInstanceState.getInt("seconds")
running = savedInstanceState.getBoolean("running")
wasRunning = savedInstanceState.getBoolean("wasRunning")
if (wasRunning) {
running = true
}
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val layout = inflater!!.inflate(R.layout.fragment_stop_watch, container,false)
runTimer(layout)
val startButton = layout.findViewById(R.id.start_button) as Button
startButton.setOnClickListener(this)
val stopButton = layout.findViewById(R.id.stop_button) as Button
stopButton.setOnClickListener(this)
val resetButton = layout.findViewById(R.id.reset_button) as Button
resetButton.setOnClickListener(this)
return layout
}
override fun onClick(view: View) {
when (view.getId()) {
R.id.start_button -> onClickStart(view)
R.id.stop_button -> onClickStop(view)
R.id.reset_button -> onClickReset(view)
}
}
override public fun onPause() {
super.onPause()
wasRunning = running
running = false
}
override public fun onResume() {
super.onResume();
if (wasRunning) {
running = true
}
}
override public fun onSaveInstanceState(savedInstanceState: Bundle?) {
savedInstanceState?.putInt("seconds", seconds)
savedInstanceState?.putBoolean("running", running)
savedInstanceState?.putBoolean("wasRunning", wasRunning)
}
fun onClickStart(view: View) {
running = true
}
fun onClickStop(view: View) {
running = false
}
fun onClickReset(view: View) {
running = false
seconds = 0
}
private fun runTimer(view: View): Unit {
val timeView = view.findViewById(R.id.time_view) as TextView
val handler = Handler()
val settimer = object : Runnable {
override fun run() {
val hours = seconds / 3600
val minutes = (seconds % 3600) / 60
val sec = seconds % 60
val time = String.format("%d:%02d:%02d", hours, minutes, sec)
timeView.text = time
if (running) {
seconds++
}
handler.postDelayed(this, 1000)
}
}
handler.post(settimer)
}
}// Required empty public constructor
| gpl-3.0 | 3a6b87554fda9c60a87aa7a6418792b3 | 31.509804 | 86 | 0.61158 | 4.784993 | false | false | false | false |
kiruto/debug-bottle | components/src/main/kotlin/com/exyui/android/debugbottle/components/fragments/__DisplayCrashBlockFragment.kt | 1 | 11594 | package com.exyui.android.debugbottle.components.fragments
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.annotation.IdRes
import android.text.TextUtils
import android.util.Log
import android.view.*
import android.widget.*
import com.exyui.android.debugbottle.components.R
import com.exyui.android.debugbottle.components.crash.CrashBlock
import com.exyui.android.debugbottle.components.crash.CrashBlockDetailAdapter
import com.exyui.android.debugbottle.components.crash.CrashReportFileMgr
import java.util.*
import java.util.concurrent.Executor
import java.util.concurrent.Executors
/**
* Created by yuriel on 9/13/16.
*/
class __DisplayCrashBlockFragment: __ContentFragment() {
private var rootView: ViewGroup? = null
private val mBlockEntries: MutableList<CrashBlock> by lazy { ArrayList<CrashBlock>() }
private var mBlockStartTime: String? = null
private val mListView by lazy { findViewById(R.id.__dt_canary_display_leak_list) as ListView }
private val mFailureView by lazy { findViewById(R.id.__dt_canary_display_leak_failure) as TextView }
private val mActionButton by lazy { findViewById(R.id.__dt_canary_action) as Button }
private val mMaxStoredBlockCount by lazy { resources.getInteger(R.integer.__block_canary_max_stored_count) }
companion object {
private val TAG = "__DisplayBlockActivity"
private val SHOW_BLOCK_EXTRA = "show_latest"
val SHOW_BLOCK_EXTRA_KEY = "BlockStartTime"
// @JvmOverloads fun createPendingIntent(context: Context, blockStartTime: String? = null): PendingIntent {
// val intent = Intent(context, DisplayHttpBlockActivity::class.java)
// intent.putExtra(SHOW_BLOCK_EXTRA, blockStartTime)
// intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
// return PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)
// }
internal fun classSimpleName(className: String): String {
val separator = className.lastIndexOf('.')
return if (separator == -1) {
className
} else {
className.substring(separator + 1)
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
if (savedInstanceState != null) {
mBlockStartTime = savedInstanceState.getString(SHOW_BLOCK_EXTRA_KEY)
} else {
val intent = context?.intent
if (intent?.hasExtra(SHOW_BLOCK_EXTRA) == true) {
mBlockStartTime = intent.getStringExtra(SHOW_BLOCK_EXTRA)
}
}
val rootView = inflater.inflate(R.layout.__dt_canary_display_leak_light, container, false)
this.rootView = rootView as ViewGroup
setHasOptionsMenu(true)
updateUi()
return rootView
}
// No, it's not deprecated. Android lies.
// override fun onRetainNonConfigurationInstance(): Any {
// return mBlockEntries as Any
// }
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(SHOW_BLOCK_EXTRA_KEY, mBlockStartTime)
}
override fun onResume() {
super.onResume()
LoadBlocks.load(this)
}
override fun onDestroy() {
super.onDestroy()
LoadBlocks.forgetActivity()
}
override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
val block = getBlock(mBlockStartTime)
if (block != null) {
menu.add(R.string.__block_canary_share_leak).setOnMenuItemClickListener {
shareBlock(block)
true
}
menu.add(R.string.__block_canary_share_stack_dump).setOnMenuItemClickListener {
shareHeapDump(block)
true
}
//return true
}
//return false
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
mBlockStartTime = null
updateUi()
}
return true
}
override fun onBackPressed(): Boolean {
return if (mBlockStartTime != null) {
mBlockStartTime = null
updateUi()
true
} else {
super.onBackPressed()
}
}
private fun shareBlock(block: CrashBlock) {
val leakInfo = block.toString()
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_TEXT, leakInfo)
startActivity(Intent.createChooser(intent, getString(R.string.__block_canary_share_with)))
}
private fun shareHeapDump(block: CrashBlock) {
val heapDumpFile = block.file
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
heapDumpFile?.setReadable(true, false)
}
val intent = Intent(Intent.ACTION_SEND)
intent.type = "application/octet-stream"
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(heapDumpFile))
startActivity(Intent.createChooser(intent, getString(R.string.__block_canary_share_with)))
}
private fun updateUi() {
val block = getBlock(mBlockStartTime)
if (block == null) {
mBlockStartTime = null
}
// Reset to defaults
mListView.visibility = View.VISIBLE
mFailureView.visibility = View.GONE
if (block != null) {
renderBlockDetail(block)
} else {
renderBlockList()
}
}
private fun renderBlockList() {
val listAdapter = mListView.adapter
if (listAdapter is BlockListAdapter) {
listAdapter.notifyDataSetChanged()
} else {
val adapter = BlockListAdapter()
mListView.adapter = adapter
mListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
mBlockStartTime = mBlockEntries[position].time
updateUi()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
context?.invalidateOptionsMenu()
//val actionBar = actionBar
//actionBar?.setDisplayHomeAsUpEnabled(false)
}
//title = "Http Listener"
mActionButton.setText(R.string.__block_canary_delete_all)
mActionButton.setOnClickListener {
CrashReportFileMgr.deleteLogFiles()
mBlockEntries.clear()
updateUi()
}
}
mActionButton.visibility = if (mBlockEntries.isEmpty()) View.GONE else View.VISIBLE
}
private fun renderBlockDetail(block: CrashBlock?) {
val listAdapter = mListView.adapter
val adapter: CrashBlockDetailAdapter
if (listAdapter is CrashBlockDetailAdapter) {
adapter = listAdapter
} else {
adapter = CrashBlockDetailAdapter()
mListView.adapter = adapter
mListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
adapter.toggleRow(position)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
context?.invalidateOptionsMenu()
//val actionBar = actionBar
//actionBar?.setDisplayHomeAsUpEnabled(true)
}
mActionButton.visibility = View.VISIBLE
mActionButton.setText(R.string.__block_canary_delete)
mActionButton.setOnClickListener {
if (block != null) {
block.file?.delete()
mBlockStartTime = null
mBlockEntries.remove(block)
updateUi()
}
}
}
adapter.update(block)
//title = "${block?.method}: ${block?.url}"
}
private fun getBlock(startTime: String?): CrashBlock? {
if (TextUtils.isEmpty(startTime)) {
return null
}
return mBlockEntries.firstOrNull { it.time == startTime }
}
private fun findViewById(@IdRes id: Int): View? = rootView?.findViewById(id)
internal inner class BlockListAdapter : BaseAdapter() {
override fun getCount(): Int = mBlockEntries.size
override fun getItem(position: Int): CrashBlock = mBlockEntries[position]
override fun getItemId(position: Int): Long = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var view = convertView
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.__dt_canary_block_row, parent, false)
}
val titleView = view!!.findViewById(R.id.__dt_canary_row_text) as TextView
@Suppress("UNUSED_VARIABLE")
val timeView = view.findViewById(R.id.__dt_canary_row_time) as TextView
val block = getItem(position)
val index: String = if (position == 0 && mBlockEntries.size == mMaxStoredBlockCount) {
"MAX. "
} else {
"${mBlockEntries.size - position}. "
}
val title = "$index${block.message}"
titleView.text = title
//timeView.text = block.time
return view
}
}
internal class LoadBlocks(private var fragmentOrNull: __DisplayCrashBlockFragment?) : Runnable {
private val mainHandler: Handler = Handler(Looper.getMainLooper())
override fun run() {
val blocks = ArrayList<CrashBlock>()
val files = CrashReportFileMgr.logFiles
if (files != null) {
for (blockFile in files) {
try {
blocks.add(CrashBlock.newInstance(blockFile))
} catch (e: Exception) {
// Likely a format change in the blockFile
blockFile.delete()
Log.e(TAG, "Could not read block log file, deleted :" + blockFile, e)
}
}
Collections.sort(blocks) { lhs, rhs ->
rhs.file?.lastModified()?.compareTo((lhs.file?.lastModified())?: 0L)?: 0
}
}
mainHandler.post {
inFlight.remove(this@LoadBlocks)
if (fragmentOrNull != null) {
fragmentOrNull!!.mBlockEntries.clear()
fragmentOrNull!!.mBlockEntries.addAll(blocks)
//Log.d("BlockCanary", "load block entries: " + blocks.size());
fragmentOrNull!!.updateUi()
}
}
}
companion object {
val inFlight: MutableList<LoadBlocks> = ArrayList()
private val backgroundExecutor: Executor = Executors.newSingleThreadExecutor()
fun load(activity: __DisplayCrashBlockFragment) {
val loadBlocks = LoadBlocks(activity)
inFlight.add(loadBlocks)
backgroundExecutor.execute(loadBlocks)
}
fun forgetActivity() {
for (loadBlocks in inFlight) {
loadBlocks.fragmentOrNull = null
}
inFlight.clear()
}
}
}
} | apache-2.0 | f98b13674e0a8c20644097e553c79da7 | 35.577287 | 115 | 0.594877 | 5.021221 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/docker/build/DockerIgnoreParser.kt | 1 | 2832 | /*
Copyright 2017-2020 Charles Korn.
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 batect.docker.build
import batect.docker.DockerException
import java.nio.file.Files
import java.nio.file.Path
class DockerIgnoreParser {
// Based on https://github.com/docker/cli/blob/master/cli/command/image/build/dockerignore.go and
// https://github.com/docker/engine/blob/master/builder/dockerignore/dockerignore.go
fun parse(path: Path): DockerImageBuildIgnoreList {
if (Files.notExists(path)) {
return DockerImageBuildIgnoreList(emptyList())
}
val lines = Files.readAllLines(path)
val entries = lines
.filterNot { it.startsWith('#') }
.map { it.trim() }
.filterNot { it.isEmpty() }
.filterNot { it == "." }
.map {
if (it == "!") {
throw DockerException("The .dockerignore pattern '$it' is invalid.")
}
if (it.startsWith('!')) {
Pair(it.substring(1).trimStart(), true)
} else {
Pair(it, false)
}
}.map { (pattern, inverted) ->
DockerImageBuildIgnoreEntry(cleanPattern(pattern), inverted)
}
return DockerImageBuildIgnoreList(entries)
}
// This needs to match the behaviour of Golang's filepath.Clean()
private fun cleanPattern(pattern: String): String {
val normalisedPattern = pattern
.split("/")
.filterNot { it == "" }
.filterNot { it == "." }
.fold(emptyList<String>()) { soFar, nextSegment ->
if (nextSegment != "..") {
soFar + nextSegment
} else if (soFar.isEmpty()) {
if (pattern.startsWith("/")) {
emptyList()
} else {
listOf(nextSegment)
}
} else if (soFar.last() == "..") {
soFar + nextSegment
} else {
soFar.dropLast(1)
}
}
.joinToString("/")
if (normalisedPattern.isEmpty()) {
return "."
}
return normalisedPattern
}
}
| apache-2.0 | 04af0ce36569185f9ba01934380c144a | 32.714286 | 101 | 0.543785 | 4.933798 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/docker/DockerHostNameResolver.kt | 1 | 2659 | /*
Copyright 2017-2020 Charles Korn.
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 batect.docker
import batect.docker.client.DockerSystemInfoClient
import batect.docker.client.DockerVersionInfoRetrievalResult
import batect.os.OperatingSystem
import batect.os.SystemInfo
import batect.utils.Version
import batect.utils.VersionComparisonMode
class DockerHostNameResolver(
private val systemInfo: SystemInfo,
private val dockerSystemInfoClient: DockerSystemInfoClient
) {
private val dockerVersionInfoRetrievalResult by lazy { dockerSystemInfoClient.getDockerVersionInfo() }
fun resolveNameOfDockerHost(): DockerHostNameResolutionResult = when (systemInfo.operatingSystem) {
OperatingSystem.Mac -> getDockerHostName("mac")
OperatingSystem.Windows -> getDockerHostName("win")
OperatingSystem.Linux, OperatingSystem.Other -> DockerHostNameResolutionResult.NotSupported
}
private fun getDockerHostName(operatingSystemPart: String): DockerHostNameResolutionResult {
val version = (dockerVersionInfoRetrievalResult as? DockerVersionInfoRetrievalResult.Succeeded)?.info?.version
return when {
version == null -> DockerHostNameResolutionResult.NotSupported
version.isGreaterThanOrEqualToDockerVersion(Version(18, 3, 0)) -> DockerHostNameResolutionResult.Resolved("host.docker.internal")
version.isGreaterThanOrEqualToDockerVersion(Version(17, 12, 0)) -> DockerHostNameResolutionResult.Resolved("docker.for.$operatingSystemPart.host.internal")
version.isGreaterThanOrEqualToDockerVersion(Version(17, 6, 0)) -> DockerHostNameResolutionResult.Resolved("docker.for.$operatingSystemPart.localhost")
else -> DockerHostNameResolutionResult.NotSupported
}
}
private fun Version.isGreaterThanOrEqualToDockerVersion(dockerVersion: Version): Boolean = this.compareTo(dockerVersion, VersionComparisonMode.DockerStyle) >= 0
}
sealed class DockerHostNameResolutionResult {
object NotSupported : DockerHostNameResolutionResult()
data class Resolved(val hostName: String) : DockerHostNameResolutionResult()
}
| apache-2.0 | 127d623ecf7d2b412ab407da746a0e4e | 46.482143 | 167 | 0.780369 | 5.471193 | false | false | false | false |
androidx/androidx | constraintlayout/constraintlayout-compose/src/androidMain/kotlin/androidx/constraintlayout/compose/ConstraintLayoutBaseScope.kt | 3 | 43511 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.constraintlayout.compose
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.core.widgets.ConstraintWidget
/**
* Common scope for [ConstraintLayoutScope] and [ConstraintSetScope], the content being shared
* between the inline DSL API and the ConstraintSet-based API.
*/
abstract class ConstraintLayoutBaseScope {
protected val tasks = mutableListOf<(State) -> Unit>()
fun applyTo(state: State): Unit = tasks.forEach { it(state) }
open fun reset() {
tasks.clear()
helperId = HelpersStartId
helpersHashCode = 0
}
@PublishedApi
internal var helpersHashCode: Int = 0
private fun updateHelpersHashCode(value: Int) {
helpersHashCode = (helpersHashCode * 1009 + value) % 1000000007
}
private val HelpersStartId = 1000
private var helperId = HelpersStartId
private fun createHelperId() = helperId++
/**
* Represents a vertical anchor (e.g. start/end of a layout, guideline) that layouts
* can link to in their `Modifier.constrainAs` or `constrain` blocks.
*
* @param reference The [LayoutReference] that this anchor belongs to.
*/
@Stable
data class VerticalAnchor internal constructor(
internal val id: Any,
internal val index: Int,
val reference: LayoutReference
)
/**
* Represents a horizontal anchor (e.g. top/bottom of a layout, guideline) that layouts
* can link to in their `Modifier.constrainAs` or `constrain` blocks.
*
* @param reference The [LayoutReference] that this anchor belongs to.
*/
@Stable
data class HorizontalAnchor internal constructor(
internal val id: Any,
internal val index: Int,
val reference: LayoutReference
)
/**
* Represents a horizontal anchor corresponding to the [FirstBaseline] of a layout that other
* layouts can link to in their `Modifier.constrainAs` or `constrain` blocks.
*
* @param reference The [LayoutReference] that this anchor belongs to.
*/
// TODO(popam): investigate if this can be just a HorizontalAnchor
@Stable
data class BaselineAnchor internal constructor(
internal val id: Any,
val reference: LayoutReference
)
/**
* Specifies additional constraints associated to the horizontal chain identified with [ref].
*/
fun constrain(
ref: HorizontalChainReference,
constrainBlock: HorizontalChainScope.() -> Unit
): HorizontalChainScope = HorizontalChainScope(ref.id).apply {
constrainBlock()
[email protected](this.tasks)
}
/**
* Specifies additional constraints associated to the vertical chain identified with [ref].
*/
fun constrain(
ref: VerticalChainReference,
constrainBlock: VerticalChainScope.() -> Unit
): VerticalChainScope = VerticalChainScope(ref.id).apply {
constrainBlock()
[email protected](this.tasks)
}
/**
* Specifies the constraints associated to the layout identified with [ref].
*/
fun constrain(
ref: ConstrainedLayoutReference,
constrainBlock: ConstrainScope.() -> Unit
): ConstrainScope = ConstrainScope(ref.id).apply {
constrainBlock()
[email protected](this.tasks)
}
/**
* Creates a guideline at a specific offset from the start of the [ConstraintLayout].
*/
fun createGuidelineFromStart(offset: Dp): VerticalAnchor {
val id = createHelperId()
tasks.add { state ->
state.verticalGuideline(id).apply {
if (state.layoutDirection == LayoutDirection.Ltr) start(offset) else end(offset)
}
}
updateHelpersHashCode(1)
updateHelpersHashCode(offset.hashCode())
return VerticalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* Creates a guideline at a specific offset from the left of the [ConstraintLayout].
*/
fun createGuidelineFromAbsoluteLeft(offset: Dp): VerticalAnchor {
val id = createHelperId()
tasks.add { state -> state.verticalGuideline(id).apply { start(offset) } }
updateHelpersHashCode(2)
updateHelpersHashCode(offset.hashCode())
return VerticalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* Creates a guideline at a specific offset from the start of the [ConstraintLayout].
* A [fraction] of 0f will correspond to the start of the [ConstraintLayout], while 1f will
* correspond to the end.
*/
fun createGuidelineFromStart(fraction: Float): VerticalAnchor {
val id = createHelperId()
tasks.add { state ->
state.verticalGuideline(id).apply {
if (state.layoutDirection == LayoutDirection.Ltr) {
percent(fraction)
} else {
percent(1f - fraction)
}
}
}
updateHelpersHashCode(3)
updateHelpersHashCode(fraction.hashCode())
return VerticalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* Creates a guideline at a width fraction from the left of the [ConstraintLayout].
* A [fraction] of 0f will correspond to the left of the [ConstraintLayout], while 1f will
* correspond to the right.
*/
// TODO(popam, b/157781990): this is not really percenide
fun createGuidelineFromAbsoluteLeft(fraction: Float): VerticalAnchor {
val id = createHelperId()
tasks.add { state -> state.verticalGuideline(id).apply { percent(fraction) } }
updateHelpersHashCode(4)
updateHelpersHashCode(fraction.hashCode())
return VerticalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* Creates a guideline at a specific offset from the end of the [ConstraintLayout].
*/
fun createGuidelineFromEnd(offset: Dp): VerticalAnchor {
val id = createHelperId()
tasks.add { state ->
state.verticalGuideline(id).apply {
if (state.layoutDirection == LayoutDirection.Ltr) end(offset) else start(offset)
}
}
updateHelpersHashCode(5)
updateHelpersHashCode(offset.hashCode())
return VerticalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* Creates a guideline at a specific offset from the right of the [ConstraintLayout].
*/
fun createGuidelineFromAbsoluteRight(offset: Dp): VerticalAnchor {
val id = createHelperId()
tasks.add { state -> state.verticalGuideline(id).apply { end(offset) } }
updateHelpersHashCode(6)
updateHelpersHashCode(offset.hashCode())
return VerticalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* Creates a guideline at a width fraction from the end of the [ConstraintLayout].
* A [fraction] of 0f will correspond to the end of the [ConstraintLayout], while 1f will
* correspond to the start.
*/
fun createGuidelineFromEnd(fraction: Float): VerticalAnchor {
return createGuidelineFromStart(1f - fraction)
}
/**
* Creates a guideline at a width fraction from the right of the [ConstraintLayout].
* A [fraction] of 0f will correspond to the right of the [ConstraintLayout], while 1f will
* correspond to the left.
*/
fun createGuidelineFromAbsoluteRight(fraction: Float): VerticalAnchor {
return createGuidelineFromAbsoluteLeft(1f - fraction)
}
/**
* Creates a guideline at a specific offset from the top of the [ConstraintLayout].
*/
fun createGuidelineFromTop(offset: Dp): HorizontalAnchor {
val id = createHelperId()
tasks.add { state -> state.horizontalGuideline(id).apply { start(offset) } }
updateHelpersHashCode(7)
updateHelpersHashCode(offset.hashCode())
return HorizontalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* Creates a guideline at a height percenide from the top of the [ConstraintLayout].
* A [fraction] of 0f will correspond to the top of the [ConstraintLayout], while 1f will
* correspond to the bottom.
*/
fun createGuidelineFromTop(fraction: Float): HorizontalAnchor {
val id = createHelperId()
tasks.add { state -> state.horizontalGuideline(id).apply { percent(fraction) } }
updateHelpersHashCode(8)
updateHelpersHashCode(fraction.hashCode())
return HorizontalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* Creates a guideline at a specific offset from the bottom of the [ConstraintLayout].
*/
fun createGuidelineFromBottom(offset: Dp): HorizontalAnchor {
val id = createHelperId()
tasks.add { state -> state.horizontalGuideline(id).apply { end(offset) } }
updateHelpersHashCode(9)
updateHelpersHashCode(offset.hashCode())
return HorizontalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* Creates a guideline at a height percenide from the bottom of the [ConstraintLayout].
* A [fraction] of 0f will correspond to the bottom of the [ConstraintLayout], while 1f will
* correspond to the top.
*/
fun createGuidelineFromBottom(fraction: Float): HorizontalAnchor {
return createGuidelineFromTop(1f - fraction)
}
/**
* Creates and returns a start barrier, containing the specified elements.
*/
fun createStartBarrier(
vararg elements: LayoutReference,
margin: Dp = 0.dp
): VerticalAnchor {
val id = createHelperId()
tasks.add { state ->
val direction = if (state.layoutDirection == LayoutDirection.Ltr) {
SolverDirection.LEFT
} else {
SolverDirection.RIGHT
}
state.barrier(id, direction).apply {
add(*(elements.map { it.id }.toTypedArray()))
}.margin(state.convertDimension(margin))
}
updateHelpersHashCode(10)
elements.forEach { updateHelpersHashCode(it.hashCode()) }
updateHelpersHashCode(margin.hashCode())
return VerticalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* Creates and returns a left barrier, containing the specified elements.
*/
fun createAbsoluteLeftBarrier(
vararg elements: LayoutReference,
margin: Dp = 0.dp
): VerticalAnchor {
val id = createHelperId()
tasks.add { state ->
state.barrier(id, SolverDirection.LEFT).apply {
add(*(elements.map { it.id }.toTypedArray()))
}.margin(state.convertDimension(margin))
}
updateHelpersHashCode(11)
elements.forEach { updateHelpersHashCode(it.hashCode()) }
updateHelpersHashCode(margin.hashCode())
return VerticalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* Creates and returns a top barrier, containing the specified elements.
*/
fun createTopBarrier(
vararg elements: LayoutReference,
margin: Dp = 0.dp
): HorizontalAnchor {
val id = createHelperId()
tasks.add { state ->
state.barrier(id, SolverDirection.TOP).apply {
add(*(elements.map { it.id }.toTypedArray()))
}.margin(state.convertDimension(margin))
}
updateHelpersHashCode(12)
elements.forEach { updateHelpersHashCode(it.hashCode()) }
updateHelpersHashCode(margin.hashCode())
return HorizontalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* Creates and returns an end barrier, containing the specified elements.
*/
fun createEndBarrier(
vararg elements: LayoutReference,
margin: Dp = 0.dp
): VerticalAnchor {
val id = createHelperId()
tasks.add { state ->
val direction = if (state.layoutDirection == LayoutDirection.Ltr) {
SolverDirection.RIGHT
} else {
SolverDirection.LEFT
}
state.barrier(id, direction).apply {
add(*(elements.map { it.id }.toTypedArray()))
}.margin(state.convertDimension(margin))
}
updateHelpersHashCode(13)
elements.forEach { updateHelpersHashCode(it.hashCode()) }
updateHelpersHashCode(margin.hashCode())
return VerticalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* Creates and returns a right barrier, containing the specified elements.
*/
fun createAbsoluteRightBarrier(
vararg elements: LayoutReference,
margin: Dp = 0.dp
): VerticalAnchor {
val id = createHelperId()
tasks.add { state ->
state.barrier(id, SolverDirection.RIGHT).apply {
add(*(elements.map { it.id }.toTypedArray()))
}.margin(state.convertDimension(margin))
}
updateHelpersHashCode(14)
elements.forEach { updateHelpersHashCode(it.hashCode()) }
updateHelpersHashCode(margin.hashCode())
return VerticalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* Creates and returns a bottom barrier, containing the specified elements.
*/
fun createBottomBarrier(
vararg elements: LayoutReference,
margin: Dp = 0.dp
): HorizontalAnchor {
val id = createHelperId()
tasks.add { state ->
state.barrier(id, SolverDirection.BOTTOM).apply {
add(*(elements.map { it.id }.toTypedArray()))
}.margin(state.convertDimension(margin))
}
updateHelpersHashCode(15)
elements.forEach { updateHelpersHashCode(it.hashCode()) }
updateHelpersHashCode(margin.hashCode())
return HorizontalAnchor(id, 0, LayoutReferenceImpl(id))
}
/**
* This creates a flow helper
* Flow helpers allows a long sequence of Composable widgets to wrap onto
* multiple rows or columns.
* [flowVertically] if set to true aranges the Composables from top to bottom.
* Normally they are arranged from left to right.
* [verticalGap] defines the gap between views in the y axis
* [horizontalGap] defines the gap between views in the x axis
* [maxElement] defines the maximum element on a row before it if the
* [padding] sets padding around the content
* [wrapMode] sets the way reach maxElements is handled
* Flow.WRAP_NONE (default) -- no wrap behavior,
* Flow.WRAP_CHAIN - create additional chains
* [verticalAlign] set the way elements are aligned vertically. Center is default
* [horizontalAlign] set the way elements are aligned horizontally. Center is default
* [horizontalFlowBias] set the way elements are aligned vertically Center is default
* [verticalFlowBias] sets the top bottom bias of the vertical chain
* [verticalStyle] sets the style of a vertical chain (Spread,Packed, or SpreadInside)
* [horizontalStyle] set the style of the horizontal chain (Spread, Packed, or SpreadInside)
*/
fun createFlow(
vararg elements: LayoutReference?,
flowVertically: Boolean = false,
verticalGap: Dp = 0.dp,
horizontalGap: Dp = 0.dp,
maxElement: Int = 0,
padding: Dp = 0.dp,
wrapMode: Wrap = Wrap.None,
verticalAlign: VerticalAlign = VerticalAlign.Center,
horizontalAlign: HorizontalAlign = HorizontalAlign.Center,
horizontalFlowBias: Float = 0.0f,
verticalFlowBias: Float = 0.0f,
verticalStyle: FlowStyle = FlowStyle.Packed,
horizontalStyle: FlowStyle = FlowStyle.Packed,
): ConstrainedLayoutReference {
val id = createHelperId()
tasks.add { state ->
state.getFlow(id, flowVertically).apply {
add(*(elements.map { it?.id }.toTypedArray()))
horizontalChainStyle = horizontalStyle.style
setVerticalChainStyle(verticalStyle.style)
verticalBias(verticalFlowBias)
horizontalBias(horizontalFlowBias)
setHorizontalAlign(horizontalAlign.mode)
setVerticalAlign(verticalAlign.mode)
setWrapMode(wrapMode.mode)
paddingLeft = state.convertDimension(padding)
paddingTop = state.convertDimension(padding)
paddingRight = state.convertDimension(padding)
paddingBottom = state.convertDimension(padding)
maxElementsWrap = maxElement
setHorizontalGap(state.convertDimension(horizontalGap))
setVerticalGap(state.convertDimension(verticalGap))
}
}
updateHelpersHashCode(16)
elements.forEach { updateHelpersHashCode(it.hashCode()) }
return ConstrainedLayoutReference(id)
}
/**
* This creates a flow helper
* Flow helpers allows a long sequence of Composable widgets to wrap onto
* multiple rows or columns.
* [flowVertically] if set to true aranges the Composables from top to bottom.
* Normally they are arranged from left to right.
* [verticalGap] defines the gap between views in the y axis
* [horizontalGap] defines the gap between views in the x axis
* [maxElement] defines the maximum element on a row before it if the
* [paddingHorizontal] sets paddingLeft and paddingRight of the content
* [paddingVertical] sets paddingTop and paddingBottom of the content
* [wrapMode] sets the way reach maxElements is handled
* Flow.WRAP_NONE (default) -- no wrap behavior,
* Flow.WRAP_CHAIN - create additional chains
* [verticalAlign] set the way elements are aligned vertically. Center is default
* [horizontalAlign] set the way elements are aligned horizontally. Center is default
* [horizontalFlowBias] set the way elements are aligned vertically Center is default
* [verticalFlowBias] sets the top bottom bias of the vertical chain
* [verticalStyle] sets the style of a vertical chain (Spread,Packed, or SpreadInside)
* [horizontalStyle] set the style of the horizontal chain (Spread, Packed, or SpreadInside)
*/
fun createFlow(
vararg elements: LayoutReference?,
flowVertically: Boolean = false,
verticalGap: Dp = 0.dp,
horizontalGap: Dp = 0.dp,
maxElement: Int = 0,
paddingHorizontal: Dp = 0.dp,
paddingVertical: Dp = 0.dp,
wrapMode: Wrap = Wrap.None,
verticalAlign: VerticalAlign = VerticalAlign.Center,
horizontalAlign: HorizontalAlign = HorizontalAlign.Center,
horizontalFlowBias: Float = 0.0f,
verticalFlowBias: Float = 0.0f,
verticalStyle: FlowStyle = FlowStyle.Packed,
horizontalStyle: FlowStyle = FlowStyle.Packed,
): ConstrainedLayoutReference {
val id = createHelperId()
tasks.add { state ->
state.getFlow(id, flowVertically).apply {
add(*(elements.map { it?.id }.toTypedArray()))
horizontalChainStyle = horizontalStyle.style
setVerticalChainStyle(verticalStyle.style)
verticalBias(verticalFlowBias)
horizontalBias(horizontalFlowBias)
setHorizontalAlign(horizontalAlign.mode)
setVerticalAlign(verticalAlign.mode)
setWrapMode(wrapMode.mode)
paddingLeft = state.convertDimension(paddingHorizontal)
paddingTop = state.convertDimension(paddingVertical)
paddingRight = state.convertDimension(paddingHorizontal)
paddingBottom = state.convertDimension(paddingVertical)
maxElementsWrap = maxElement
setHorizontalGap(state.convertDimension(horizontalGap))
setVerticalGap(state.convertDimension(verticalGap))
}
}
updateHelpersHashCode(16)
elements.forEach { updateHelpersHashCode(it.hashCode()) }
return ConstrainedLayoutReference(id)
}
/**
* This creates a flow helper
* Flow helpers allows a long sequence of Composable widgets to wrap onto
* multiple rows or columns.
* [flowVertically] if set to true aranges the Composables from top to bottom.
* Normally they are arranged from left to right.
* [verticalGap] defines the gap between views in the y axis
* [horizontalGap] defines the gap between views in the x axis
* [maxElement] defines the maximum element on a row before it if the
* [paddingLeft] sets paddingLeft of the content
* [paddingTop] sets paddingTop of the content
* [paddingRight] sets paddingRight of the content
* [paddingBottom] sets paddingBottom of the content
* [wrapMode] sets the way reach maxElements is handled
* Flow.WRAP_NONE (default) -- no wrap behavior,
* Flow.WRAP_CHAIN - create additional chains
* [verticalAlign] set the way elements are aligned vertically. Center is default
* [horizontalAlign] set the way elements are aligned horizontally. Center is default
* [horizontalFlowBias] set the way elements are aligned vertically Center is default
* [verticalFlowBias] sets the top bottom bias of the vertical chain
* [verticalStyle] sets the style of a vertical chain (Spread,Packed, or SpreadInside)
* [horizontalStyle] set the style of the horizontal chain (Spread, Packed, or SpreadInside)
*/
fun createFlow(
vararg elements: LayoutReference?,
flowVertically: Boolean = false,
verticalGap: Dp = 0.dp,
horizontalGap: Dp = 0.dp,
maxElement: Int = 0,
paddingLeft: Dp = 0.dp,
paddingTop: Dp = 0.dp,
paddingRight: Dp = 0.dp,
paddingBottom: Dp = 0.dp,
wrapMode: Wrap = Wrap.None,
verticalAlign: VerticalAlign = VerticalAlign.Center,
horizontalAlign: HorizontalAlign = HorizontalAlign.Center,
horizontalFlowBias: Float = 0.0f,
verticalFlowBias: Float = 0.0f,
verticalStyle: FlowStyle = FlowStyle.Packed,
horizontalStyle: FlowStyle = FlowStyle.Packed,
): ConstrainedLayoutReference {
val id = createHelperId()
tasks.add { state ->
state.getFlow(id, flowVertically).apply {
add(*(elements.map { it?.id }.toTypedArray()))
horizontalChainStyle = horizontalStyle.style
setVerticalChainStyle(verticalStyle.style)
verticalBias(verticalFlowBias)
horizontalBias(horizontalFlowBias)
setHorizontalAlign(horizontalAlign.mode)
setVerticalAlign(verticalAlign.mode)
setWrapMode(wrapMode.mode)
setPaddingLeft(state.convertDimension(paddingLeft))
setPaddingTop(state.convertDimension(paddingTop))
setPaddingRight(state.convertDimension(paddingRight))
setPaddingBottom(state.convertDimension(paddingBottom))
maxElementsWrap = maxElement
setHorizontalGap(state.convertDimension(horizontalGap))
setVerticalGap(state.convertDimension(verticalGap))
}
}
updateHelpersHashCode(16)
elements.forEach { updateHelpersHashCode(it.hashCode()) }
return ConstrainedLayoutReference(id)
}
/**
* Creates a horizontal chain including the referenced layouts.
*
* Use [constrain] with the resulting [HorizontalChainReference] to modify the start/left and
* end/right constraints of this chain.
*/
fun createHorizontalChain(
vararg elements: LayoutReference,
chainStyle: ChainStyle = ChainStyle.Spread
): HorizontalChainReference {
val id = createHelperId()
tasks.add { state ->
val helper = state.helper(
id,
androidx.constraintlayout.core.state.State.Helper.HORIZONTAL_CHAIN
) as androidx.constraintlayout.core.state.helpers.HorizontalChainReference
elements.forEach { chainElement ->
val elementParams = chainElement.getHelperParams() ?: ChainParams.Default
helper.addChainElement(
chainElement.id,
elementParams.weight,
state.convertDimension(elementParams.startMargin).toFloat(),
state.convertDimension(elementParams.endMargin).toFloat(),
state.convertDimension(elementParams.startGoneMargin).toFloat(),
state.convertDimension(elementParams.endGoneMargin).toFloat()
)
}
helper.style(chainStyle.style)
helper.apply()
if (chainStyle.bias != null) {
state.constraints(elements[0].id).horizontalBias(chainStyle.bias)
}
}
updateHelpersHashCode(16)
elements.forEach { updateHelpersHashCode(it.hashCode()) }
updateHelpersHashCode(chainStyle.hashCode())
return HorizontalChainReference(id)
}
/**
* Creates a vertical chain including the referenced layouts.
*
* Use [constrain] with the resulting [VerticalChainReference] to modify the top and
* bottom constraints of this chain.
*/
fun createVerticalChain(
vararg elements: LayoutReference,
chainStyle: ChainStyle = ChainStyle.Spread
): VerticalChainReference {
val id = createHelperId()
tasks.add { state ->
val helper = state.helper(
id,
androidx.constraintlayout.core.state.State.Helper.VERTICAL_CHAIN
) as androidx.constraintlayout.core.state.helpers.VerticalChainReference
elements.forEach { chainElement ->
val elementParams = chainElement.getHelperParams() ?: ChainParams.Default
helper.addChainElement(
chainElement.id,
elementParams.weight,
state.convertDimension(elementParams.topMargin).toFloat(),
state.convertDimension(elementParams.bottomMargin).toFloat(),
state.convertDimension(elementParams.topGoneMargin).toFloat(),
state.convertDimension(elementParams.bottomGoneMargin).toFloat()
)
}
helper.style(chainStyle.style)
helper.apply()
if (chainStyle.bias != null) {
state.constraints(elements[0].id).verticalBias(chainStyle.bias)
}
}
updateHelpersHashCode(17)
elements.forEach { updateHelpersHashCode(it.hashCode()) }
updateHelpersHashCode(chainStyle.hashCode())
return VerticalChainReference(id)
}
/**
* Sets the parameters that are used by chains to customize the resulting layout.
*
* Use margins to customize the space between widgets in the chain.
*
* Use weight to distribute available space to each widget when their dimensions are not
* fixed.
*
*
*
* Similarly named parameters available from [ConstrainScope.linkTo] are ignored in
* Chains.
*
* Since margins are only for widgets within the chain: Top, Start and End, Bottom margins are
* ignored when the widget is the first or the last element in the chain, respectively.
*
* @param startMargin Added space from the start of this widget to the previous widget
* @param topMargin Added space from the top of this widget to the previous widget
* @param endMargin Added space from the end of this widget to the next widget
* @param bottomMargin Added space from the bottom of this widget to the next widget
* @param startGoneMargin Added space from the start of this widget when the previous widget has [Visibility.Gone]
* @param topGoneMargin Added space from the top of this widget when the previous widget has [Visibility.Gone]
* @param endGoneMargin Added space from the end of this widget when the next widget has [Visibility.Gone]
* @param bottomGoneMargin Added space from the bottom of this widget when the next widget has [Visibility.Gone]
* @param weight Defines the proportion of space (relative to the total weight) occupied by this
* layout when the corresponding dimension is not a fixed value.
* @return The same [LayoutReference] instance with the applied values
*/
fun LayoutReference.withChainParams(
startMargin: Dp = 0.dp,
topMargin: Dp = 0.dp,
endMargin: Dp = 0.dp,
bottomMargin: Dp = 0.dp,
startGoneMargin: Dp = 0.dp,
topGoneMargin: Dp = 0.dp,
endGoneMargin: Dp = 0.dp,
bottomGoneMargin: Dp = 0.dp,
weight: Float = Float.NaN,
): LayoutReference =
this.apply {
setHelperParams(
ChainParams(
startMargin = startMargin,
topMargin = topMargin,
endMargin = endMargin,
bottomMargin = bottomMargin,
startGoneMargin = startGoneMargin,
topGoneMargin = topGoneMargin,
endGoneMargin = endGoneMargin,
bottomGoneMargin = bottomGoneMargin,
weight = weight
)
)
}
/**
* Sets the parameters that are used by horizontal chains to customize the resulting layout.
*
* Use margins to customize the space between widgets in the chain.
*
* Use weight to distribute available space to each widget when their horizontal dimension is
* not fixed.
*
*
*
* Similarly named parameters available from [ConstrainScope.linkTo] are ignored in
* Chains.
*
* Since margins are only for widgets within the chain: Start and End margins are
* ignored when the widget is the first or the last element in the chain, respectively.
*
* @param startMargin Added space from the start of this widget to the previous widget
* @param endMargin Added space from the end of this widget to the next widget
* @param startGoneMargin Added space from the start of this widget when the previous widget has [Visibility.Gone]
* @param endGoneMargin Added space from the end of this widget when the next widget has [Visibility.Gone]
* @param weight Defines the proportion of space (relative to the total weight) occupied by this
* layout when the width is not a fixed dimension.
* @return The same [LayoutReference] instance with the applied values
*/
fun LayoutReference.withHorizontalChainParams(
startMargin: Dp = 0.dp,
endMargin: Dp = 0.dp,
startGoneMargin: Dp = 0.dp,
endGoneMargin: Dp = 0.dp,
weight: Float = Float.NaN
): LayoutReference =
withChainParams(
startMargin = startMargin,
topMargin = 0.dp,
endMargin = endMargin,
bottomMargin = 0.dp,
startGoneMargin = startGoneMargin,
topGoneMargin = 0.dp,
endGoneMargin = endGoneMargin,
bottomGoneMargin = 0.dp,
weight = weight
)
/**
* Sets the parameters that are used by vertical chains to customize the resulting layout.
*
* Use margins to customize the space between widgets in the chain.
*
* Use weight to distribute available space to each widget when their vertical dimension is not
* fixed.
*
*
*
* Similarly named parameters available from [ConstrainScope.linkTo] are ignored in
* Chains.
*
* Since margins are only for widgets within the chain: Top and Bottom margins are
* ignored when the widget is the first or the last element in the chain, respectively.
*
* @param topMargin Added space from the top of this widget to the previous widget
* @param bottomMargin Added space from the bottom of this widget to the next widget
* @param topGoneMargin Added space from the top of this widget when the previous widget has [Visibility.Gone]
* @param bottomGoneMargin Added space from the bottom of this widget when the next widget has [Visibility.Gone]
* @param weight Defines the proportion of space (relative to the total weight) occupied by this
* layout when the height is not a fixed dimension.
* @return The same [LayoutReference] instance with the applied values
*/
fun LayoutReference.withVerticalChainParams(
topMargin: Dp = 0.dp,
bottomMargin: Dp = 0.dp,
topGoneMargin: Dp = 0.dp,
bottomGoneMargin: Dp = 0.dp,
weight: Float = Float.NaN
): LayoutReference =
withChainParams(
startMargin = 0.dp,
topMargin = topMargin,
endMargin = 0.dp,
bottomMargin = bottomMargin,
startGoneMargin = 0.dp,
topGoneMargin = topGoneMargin,
endGoneMargin = 0.dp,
bottomGoneMargin = bottomGoneMargin,
weight = weight
)
}
/**
* Represents a [ConstraintLayout] item that requires a unique identifier. Typically a layout or a
* helper such as barriers, guidelines or chains.
*/
@Stable
abstract class LayoutReference internal constructor(internal open val id: Any) {
/**
* This map should be used to store one instance of different implementations of [HelperParams].
*/
private val helperParamsMap: MutableMap<String, HelperParams> = mutableMapOf()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LayoutReference
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id.hashCode()
}
internal fun setHelperParams(helperParams: HelperParams) {
// Use the class name to force one instance per implementation
helperParamsMap[helperParams.javaClass.simpleName] = helperParams
}
/**
* Returns the [HelperParams] that corresponds to the class type [T]. Null if no instance of
* type [T] has been set.
*/
internal inline fun <reified T> getHelperParams(): T? where T : HelperParams {
return helperParamsMap[T::class.java.simpleName] as? T
}
}
/**
* Helpers that need parameters on a per-widget basis may implement this interface to store custom
* parameters within [LayoutReference].
*
* @see [LayoutReference.getHelperParams]
* @see [LayoutReference.setHelperParams]
*/
internal interface HelperParams
/**
* Parameters that may be defined for each widget within a chain.
*
* These will always be used instead of similarly named parameters defined with other calls such as
* [ConstrainScope.linkTo].
*/
internal class ChainParams(
val startMargin: Dp,
val topMargin: Dp,
val endMargin: Dp,
val bottomMargin: Dp,
val startGoneMargin: Dp,
val topGoneMargin: Dp,
val endGoneMargin: Dp,
val bottomGoneMargin: Dp,
val weight: Float,
) : HelperParams {
companion object {
internal val Default = ChainParams(
startMargin = 0.dp,
topMargin = 0.dp,
endMargin = 0.dp,
bottomMargin = 0.dp,
startGoneMargin = 0.dp,
topGoneMargin = 0.dp,
endGoneMargin = 0.dp,
bottomGoneMargin = 0.dp,
weight = Float.NaN
)
}
}
/**
* Basic implementation of [LayoutReference], used as fallback for items that don't fit other
* implementations of [LayoutReference], such as [ConstrainedLayoutReference].
*/
@Stable
internal class LayoutReferenceImpl internal constructor(id: Any) : LayoutReference(id)
/**
* Represents a layout within a [ConstraintLayout].
*
* This is a [LayoutReference] that may be constrained to other elements.
*/
@Stable
class ConstrainedLayoutReference(override val id: Any) : LayoutReference(id) {
/**
* The start anchor of this layout. Represents left in LTR layout direction, or right in RTL.
*/
@Stable
val start = ConstraintLayoutBaseScope.VerticalAnchor(id, -2, this)
/**
* The left anchor of this layout.
*/
@Stable
val absoluteLeft = ConstraintLayoutBaseScope.VerticalAnchor(id, 0, this)
/**
* The top anchor of this layout.
*/
@Stable
val top = ConstraintLayoutBaseScope.HorizontalAnchor(id, 0, this)
/**
* The end anchor of this layout. Represents right in LTR layout direction, or left in RTL.
*/
@Stable
val end = ConstraintLayoutBaseScope.VerticalAnchor(id, -1, this)
/**
* The right anchor of this layout.
*/
@Stable
val absoluteRight = ConstraintLayoutBaseScope.VerticalAnchor(id, 1, this)
/**
* The bottom anchor of this layout.
*/
@Stable
val bottom = ConstraintLayoutBaseScope.HorizontalAnchor(id, 1, this)
/**
* The baseline anchor of this layout.
*/
@Stable
val baseline = ConstraintLayoutBaseScope.BaselineAnchor(id, this)
}
/**
* Represents a horizontal chain within a [ConstraintLayout].
*
* The anchors correspond to the first and last elements in the chain.
*/
@Stable
class HorizontalChainReference internal constructor(id: Any) : LayoutReference(id) {
/**
* The start anchor of the first element in the chain.
*
* Represents left in LTR layout direction, or right in RTL.
*/
@Stable
val start = ConstraintLayoutBaseScope.VerticalAnchor(id, -2, this)
/**
* The left anchor of the first element in the chain.
*/
@Stable
val absoluteLeft = ConstraintLayoutBaseScope.VerticalAnchor(id, 0, this)
/**
* The end anchor of the last element in the chain.
*
* Represents right in LTR layout direction, or left in RTL.
*/
@Stable
val end = ConstraintLayoutBaseScope.VerticalAnchor(id, -1, this)
/**
* The right anchor of the last element in the chain.
*/
@Stable
val absoluteRight = ConstraintLayoutBaseScope.VerticalAnchor(id, 1, this)
}
/**
* Represents a vertical chain within a [ConstraintLayout].
*
* The anchors correspond to the first and last elements in the chain.
*/
@Stable
class VerticalChainReference internal constructor(id: Any) : LayoutReference(id) {
/**
* The top anchor of the first element in the chain.
*/
@Stable
val top = ConstraintLayoutBaseScope.HorizontalAnchor(id, 0, this)
/**
* The bottom anchor of the last element in the chain.
*/
@Stable
val bottom = ConstraintLayoutBaseScope.HorizontalAnchor(id, 1, this)
}
/**
* The style of a horizontal or vertical chain.
*/
@Immutable
class ChainStyle internal constructor(
internal val style: SolverChain,
internal val bias: Float? = null
) {
companion object {
/**
* A chain style that evenly distributes the contained layouts.
*/
@Stable
val Spread = ChainStyle(SolverChain.SPREAD)
/**
* A chain style where the first and last layouts are affixed to the constraints
* on each end of the chain and the rest are evenly distributed.
*/
@Stable
val SpreadInside = ChainStyle(SolverChain.SPREAD_INSIDE)
/**
* A chain style where the contained layouts are packed together and placed to the
* center of the available space.
*/
@Stable
val Packed = Packed(0.5f)
/**
* A chain style where the contained layouts are packed together and placed in
* the available space according to a given [bias].
*/
@Stable
fun Packed(bias: Float) = ChainStyle(SolverChain.PACKED, bias)
}
}
/**
* The overall visibility of a widget in a [ConstraintLayout].
*/
@Immutable
class Visibility internal constructor(
internal val solverValue: Int
) {
companion object {
/**
* Indicates that the widget will be painted in the [ConstraintLayout]. All render-time
* transforms will apply normally.
*/
@Stable
val Visible = Visibility(ConstraintWidget.VISIBLE)
/**
* The widget will not be painted in the [ConstraintLayout] but its dimensions and constraints
* will still apply.
*
* Equivalent to forcing the alpha to 0.0.
*/
@Stable
val Invisible = Visibility(ConstraintWidget.INVISIBLE)
/**
* Like [Invisible], but the dimensions of the widget will collapse to (0,0), the
* constraints will still apply.
*/
@Stable
val Gone = Visibility(ConstraintWidget.GONE)
}
}
/**
* Wrap defines the type of chain
*/
@Immutable
class Wrap internal constructor(
internal val mode: Int
) {
companion object {
val None =
Wrap(androidx.constraintlayout.core.widgets.Flow.WRAP_NONE)
val Chain =
Wrap(androidx.constraintlayout.core.widgets.Flow.WRAP_CHAIN)
val Aligned =
Wrap(androidx.constraintlayout.core.widgets.Flow.WRAP_ALIGNED)
}
}
/**
* Defines how objects align vertically within the chain
*/
@Immutable
class VerticalAlign internal constructor(
internal val mode: Int
) {
companion object {
val Top = VerticalAlign(androidx.constraintlayout.core.widgets.Flow.VERTICAL_ALIGN_TOP)
val Bottom =
VerticalAlign(androidx.constraintlayout.core.widgets.Flow.VERTICAL_ALIGN_BOTTOM)
val Center =
VerticalAlign(androidx.constraintlayout.core.widgets.Flow.VERTICAL_ALIGN_CENTER)
val Baseline =
VerticalAlign(androidx.constraintlayout.core.widgets.Flow.VERTICAL_ALIGN_BASELINE)
}
}
/**
* Defines how objects align horizontally in the chain
*/
@Immutable
class HorizontalAlign internal constructor(
internal val mode: Int
) {
companion object {
val Start =
HorizontalAlign(androidx.constraintlayout.core.widgets.Flow.HORIZONTAL_ALIGN_START)
val End = HorizontalAlign(androidx.constraintlayout.core.widgets.Flow.HORIZONTAL_ALIGN_END)
val Center =
HorizontalAlign(androidx.constraintlayout.core.widgets.Flow.HORIZONTAL_ALIGN_CENTER)
}
}
/**
* Defines how widgets are spaced in a chain
*/
@Immutable
class FlowStyle internal constructor(
internal val style: Int
) {
companion object {
val Spread = FlowStyle(0)
val SpreadInside = FlowStyle(1)
val Packed = FlowStyle(2)
}
} | apache-2.0 | c18f38d41e59fcce5c39a2d6a08f06e4 | 37.269129 | 118 | 0.651261 | 5.109324 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/text/input/InputMethodManager.kt | 3 | 5142 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.input
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.os.Build
import android.util.Log
import android.view.View
import android.view.Window
import android.view.inputmethod.ExtractedText
import androidx.annotation.DoNotInline
import androidx.annotation.RequiresApi
import androidx.compose.ui.window.DialogWindowProvider
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
internal interface InputMethodManager {
fun restartInput()
fun showSoftInput()
fun hideSoftInput()
fun updateExtractedText(
token: Int,
extractedText: ExtractedText
)
fun updateSelection(
selectionStart: Int,
selectionEnd: Int,
compositionStart: Int,
compositionEnd: Int
)
}
/**
* Wrapper class to prevent depending on getSystemService and final InputMethodManager.
* Let's us test TextInputServiceAndroid class.
*/
internal class InputMethodManagerImpl(private val view: View) : InputMethodManager {
private val imm by lazy(LazyThreadSafetyMode.NONE) {
view.context.getSystemService(Context.INPUT_METHOD_SERVICE)
as android.view.inputmethod.InputMethodManager
}
private val helper = if (Build.VERSION.SDK_INT < 30) {
ImmHelper21(view)
} else {
ImmHelper30(view)
}
override fun restartInput() {
imm.restartInput(view)
}
override fun showSoftInput() {
if (DEBUG && !view.hasWindowFocus()) {
Log.d(TAG, "InputMethodManagerImpl: requesting soft input on non focused field")
}
helper.showSoftInput(imm)
}
override fun hideSoftInput() {
helper.hideSoftInput(imm)
}
override fun updateExtractedText(
token: Int,
extractedText: ExtractedText
) {
imm.updateExtractedText(view, token, extractedText)
}
override fun updateSelection(
selectionStart: Int,
selectionEnd: Int,
compositionStart: Int,
compositionEnd: Int
) {
imm.updateSelection(view, selectionStart, selectionEnd, compositionStart, compositionEnd)
}
}
private interface ImmHelper {
fun showSoftInput(imm: android.view.inputmethod.InputMethodManager)
fun hideSoftInput(imm: android.view.inputmethod.InputMethodManager)
}
private class ImmHelper21(private val view: View) : ImmHelper {
@DoNotInline
override fun showSoftInput(imm: android.view.inputmethod.InputMethodManager) {
view.post {
imm.showSoftInput(view, 0)
}
}
@DoNotInline
override fun hideSoftInput(imm: android.view.inputmethod.InputMethodManager) {
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
@RequiresApi(30)
private class ImmHelper30(private val view: View) : ImmHelper {
/**
* Get a [WindowInsetsControllerCompat] for the view. This returns a new instance every time,
* since the view may return null or not null at different times depending on window attach
* state.
*/
private val insetsControllerCompat
// This can return null when, for example, the view is not attached to a window.
get() = view.findWindow()?.let { WindowInsetsControllerCompat(it, view) }
/**
* This class falls back to the legacy implementation when the window insets controller isn't
* available.
*/
private val immHelper21: ImmHelper21
get() = _immHelper21 ?: ImmHelper21(view).also { _immHelper21 = it }
private var _immHelper21: ImmHelper21? = null
@DoNotInline
override fun showSoftInput(imm: android.view.inputmethod.InputMethodManager) {
insetsControllerCompat?.apply {
show(WindowInsetsCompat.Type.ime())
} ?: immHelper21.showSoftInput(imm)
}
@DoNotInline
override fun hideSoftInput(imm: android.view.inputmethod.InputMethodManager) {
insetsControllerCompat?.apply {
hide(WindowInsetsCompat.Type.ime())
} ?: immHelper21.hideSoftInput(imm)
}
// TODO(b/221889664) Replace with composition local when available.
private fun View.findWindow(): Window? =
(parent as? DialogWindowProvider)?.window
?: context.findWindow()
private tailrec fun Context.findWindow(): Window? =
when (this) {
is Activity -> window
is ContextWrapper -> baseContext.findWindow()
else -> null
}
}
| apache-2.0 | 5bad4cfc1276df23814dfceb1e30d4de | 29.607143 | 97 | 0.69506 | 4.792171 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/ui/view/bbcode/BBTree.kt | 1 | 3320 | package me.proxer.app.ui.view.bbcode
import me.proxer.app.ui.view.bbcode.prototype.BBPrototype
import me.proxer.app.ui.view.bbcode.prototype.ConditionalTextMutatorPrototype
import me.proxer.app.ui.view.bbcode.prototype.TextMutatorPrototype
import me.proxer.app.ui.view.bbcode.prototype.TextPrototype
import me.proxer.app.util.extension.unsafeLazy
/**
* @author Ruben Gees
*/
class BBTree(
val prototype: BBPrototype,
val parent: BBTree?,
val children: MutableList<BBTree> = mutableListOf(),
val args: BBArgs = BBArgs()
) {
fun endsWith(code: String) = prototype.endRegex.matches(code)
fun makeViews(parent: BBCodeView, args: BBArgs) = prototype.makeViews(parent, children, args + this.args)
fun optimize(args: BBArgs = BBArgs()) = recursiveOptimize(args).first()
private fun recursiveOptimize(args: BBArgs): List<BBTree> {
val recursiveNewChildren by unsafeLazy { getRecursiveChildren(children) }
val canOptimize = prototype !is ConditionalTextMutatorPrototype || prototype.canOptimize(recursiveNewChildren)
if (prototype is TextMutatorPrototype && canOptimize) {
recursiveNewChildren.forEach {
if (it.prototype == TextPrototype) {
val mergedArgs = args + this.args + it.args
it.args.text = prototype.mutate(it.args.safeText.toSpannableStringBuilder(), mergedArgs)
}
}
}
val newChildren = mergeChildren(children.flatMap { it.recursiveOptimize(args) })
return when {
canOptimize && prototype is TextMutatorPrototype -> newChildren.map {
BBTree(it.prototype, parent, it.children, it.args)
}
else -> {
children.clear()
children.addAll(newChildren)
listOf(this)
}
}
}
private fun mergeChildren(newChildren: List<BBTree>): List<BBTree> {
val result = mutableListOf<BBTree>()
if (newChildren.isNotEmpty()) {
var current = newChildren.first()
newChildren.drop(1).forEach { next ->
if (current.prototype == TextPrototype && next.prototype == TextPrototype) {
current.args.text = current.args.safeText.toSpannableStringBuilder().append(next.args.safeText)
} else {
result += current
current = next
}
}
result += current
}
return result
}
private fun getRecursiveChildren(current: List<BBTree>): List<BBTree> = current
.plus(current.flatMap { getRecursiveChildren(it.children) })
@Suppress("EqualsAlwaysReturnsTrueOrFalse") // False positive
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BBTree
if (prototype != other.prototype) return false
if (children != other.children) return false
if (args != other.args) return false
return true
}
override fun hashCode(): Int {
var result = prototype.hashCode()
result = 31 * result + children.hashCode()
result = 31 * result + args.hashCode()
return result
}
}
| gpl-3.0 | 433c9db1acd7ab27be044cd3c86d2833 | 32.877551 | 118 | 0.623193 | 4.695898 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/service/QueueData.kt | 1 | 2632 | /*
* Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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.andstatus.app.service
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.timeline.ViewItem
/**
* @author [email protected]
*/
class QueueData protected constructor(val queueType: QueueType, val commandData: CommandData) : ViewItem<QueueData>(false, commandData.getCreatedDate()), Comparable<QueueData> {
override fun getId(): Long {
return commandData.hashCode().toLong()
}
override fun getDate(): Long {
return commandData.getCreatedDate()
}
fun toSharedSubject(): String {
return (queueType.acronym + "; "
+ commandData.toCommandSummary( MyContextHolder.myContextHolder.getNow()))
}
fun toSharedText(): String {
return (queueType.acronym + "; "
+ commandData.share( MyContextHolder.myContextHolder.getNow()))
}
override operator fun compareTo(other: QueueData): Int {
return -longCompare(getDate(), other.getDate())
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val queueData = other as QueueData
return if (queueType != queueData.queueType) false
else commandData.getCreatedDate() == queueData.commandData.getCreatedDate()
}
override fun hashCode(): Int {
var result = queueType.hashCode()
result = 31 * result + (commandData.getCreatedDate() xor (commandData.getCreatedDate() ushr 32)).toInt()
return result
}
companion object {
val EMPTY: QueueData = QueueData(QueueType.UNKNOWN, CommandData.EMPTY)
fun getNew(queueType: QueueType, commandData: CommandData): QueueData {
return QueueData(queueType, commandData)
}
// TODO: Replace with Long.compare for API >= 19
private fun longCompare(lhs: Long, rhs: Long): Int {
return if (lhs < rhs) -1 else if (lhs == rhs) 0 else 1
}
}
}
| apache-2.0 | 14da4a18f95e0ee4e3d3c8afebfb0faa | 35.054795 | 177 | 0.671733 | 4.633803 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/classificator/age/ClassificationAgeFragment.kt | 2 | 4400 | package ru.fantlab.android.ui.modules.classificator.age
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.annotation.StringRes
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.micro_grid_refresh_list.*
import kotlinx.android.synthetic.main.state_layout.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.Classificator
import ru.fantlab.android.data.dao.model.ClassificatorModel
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.helper.Bundler
import ru.fantlab.android.ui.adapter.viewholder.ClassificatorViewHolder
import ru.fantlab.android.ui.base.BaseFragment
import ru.fantlab.android.ui.modules.classificator.ClassificatorPagerMvp
import ru.fantlab.android.ui.widgets.treeview.TreeNode
import ru.fantlab.android.ui.widgets.treeview.TreeViewAdapter
import java.util.*
class ClassificationAgeFragment : BaseFragment<ClassificationAgeMvp.View, ClassificationAgePresenter>(),
ClassificationAgeMvp.View {
private var pagerCallback: ClassificatorPagerMvp.View? = null
var selectedItems = 0
override fun fragmentLayout() = R.layout.micro_grid_refresh_list
override fun providePresenter() = ClassificationAgePresenter()
override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
presenter.onFragmentCreated(arguments!!)
}
override fun onInitViews(classificators: ArrayList<ClassificatorModel>) {
hideProgress()
fastScroller.attachRecyclerView(recycler)
refresh.setOnRefreshListener(this)
val nodes = arrayListOf<TreeNode<*>>()
classificators.forEach {
val root = TreeNode(Classificator(it.name, it.descr, it.id))
nodes.add(root)
work(it, root, false)
}
val adapter = TreeViewAdapter(nodes, Arrays.asList(ClassificatorViewHolder()))
recycler.adapter = adapter
adapter.setOnTreeNodeListener(object : TreeViewAdapter.OnTreeNodeListener {
override fun onSelected(extra: Int, add: Boolean) {
if (add)
selectedItems++
else
selectedItems--
onSetTabCount(selectedItems)
pagerCallback?.onSelected(extra, add)
}
override fun onClick(node: TreeNode<*>, holder: RecyclerView.ViewHolder): Boolean {
val viewHolder = holder as ClassificatorViewHolder.ViewHolder
val state = viewHolder.checkbox.isChecked
if (!node.isLeaf) {
onToggle(!node.isExpand, holder)
if (!state && !node.isExpand) {
viewHolder.checkbox.isChecked = true
}
} else {
viewHolder.checkbox.isChecked = !state
}
return false
}
override fun onToggle(isExpand: Boolean, holder: RecyclerView.ViewHolder) {
val viewHolder = holder as ClassificatorViewHolder.ViewHolder
val ivArrow = viewHolder.arrow
val rotateDegree = if (isExpand) 90.0f else -90.0f
ivArrow.animate().rotationBy(rotateDegree)
.start()
}
})
}
private fun work(it: ClassificatorModel, root: TreeNode<Classificator>, lastLevel: Boolean) {
if (it.childs != null) {
val counter = root.childList.size - 1
it.childs.forEach {
val child = TreeNode(Classificator(it.name, it.descr, it.id))
if (lastLevel) {
val childB = TreeNode(Classificator(it.name, it.descr, it.id))
root.childList[counter].addChild(childB)
} else root.addChild(child)
work(it, root, true)
}
}
}
override fun showProgress(@StringRes resId: Int, cancelable: Boolean) {
refresh.isRefreshing = true
stateLayout.showProgress()
}
override fun hideProgress() {
refresh.isRefreshing = false
stateLayout.hideProgress()
}
override fun showErrorMessage(msgRes: String?) {
hideProgress()
super.showErrorMessage(msgRes)
}
override fun showMessage(titleRes: Int, msgRes: Int) {
hideProgress()
super.showMessage(titleRes, msgRes)
}
override fun onClick(v: View?) {
onRefresh()
}
override fun onRefresh() {
hideProgress()
}
fun onSetTabCount(count: Int) {
pagerCallback?.onSetBadge(6, count)
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is ClassificatorPagerMvp.View) {
pagerCallback = context
}
}
override fun onDetach() {
pagerCallback = null
super.onDetach()
}
companion object {
fun newInstance(workId: Int): ClassificationAgeFragment {
val view = ClassificationAgeFragment()
view.arguments = Bundler.start().put(BundleConstant.EXTRA, workId).end()
return view
}
}
} | gpl-3.0 | 918f01a7d91b8275d48249fc0ce8968f | 27.577922 | 104 | 0.748182 | 3.866432 | false | false | false | false |
elect86/helloTriangle | src/main/kotlin/gl3/gl_injection.kt | 1 | 2456 | package gl3
import com.jogamp.newt.event.KeyEvent
import com.jogamp.newt.event.KeyListener
import com.jogamp.newt.event.WindowAdapter
import com.jogamp.newt.event.WindowEvent
import com.jogamp.newt.opengl.GLWindow
import com.jogamp.opengl.*
import com.jogamp.opengl.GL2ES3.GL_COLOR
import com.jogamp.opengl.util.Animator
import com.jogamp.opengl.util.GLBuffers
import glm.set
import uno.buffer.toFloatBuffer
/**
* Created by GBarbieri on 27.03.2017.
*/
fun main(args: Array<String>) {
GL_injection_().setup()
}
class GL_injection_ : GLEventListener, KeyListener {
lateinit var window: GLWindow
lateinit var animator:Animator
val clearColor = floatArrayOf(0f, 0f, 0f, 0f).toFloatBuffer()
fun setup() {
val glProfile = GLProfile.get(GLProfile.GL3)
val glCapabilities = GLCapabilities(glProfile)
window = GLWindow.create(glCapabilities)
window.title = "gl injection"
window.setSize(1024, 768)
window.addGLEventListener(this)
window.addKeyListener(this)
window.autoSwapBufferMode = false
window.isVisible = true
animator = Animator(window)
animator.start()
window.addWindowListener(object : WindowAdapter() {
override fun windowDestroyed(e: WindowEvent?) {
animator.stop()
System.exit(1)
}
})
}
override fun init(drawable: GLAutoDrawable) {}
override fun reshape(drawable: GLAutoDrawable, x: Int, y: Int, width: Int, height: Int) {}
override fun display(drawable: GLAutoDrawable) {}
override fun dispose(drawable: GLAutoDrawable) {}
override fun keyPressed(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_ESCAPE)
Thread { window.destroy() }.start()
when (e.keyCode) {
KeyEvent.VK_R -> modified(0)
KeyEvent.VK_G -> modified(1)
KeyEvent.VK_B -> modified(2)
KeyEvent.VK_A -> modified(3)
}
}
fun modified(index: Int) {
clearColor[index] = if (clearColor[index] == 0f) 1f else 0f
println("clear color: (" + clearColor[0] + ", " + clearColor[1] + ", " + clearColor[2] + ", " + clearColor[3] + ")")
window.invoke(false) { drawable ->
drawable.gl.gL3.glClearBufferfv(GL_COLOR, 0, clearColor)
drawable.swapBuffers()
true
}
}
override fun keyReleased(e: KeyEvent) {}
} | mit | 003d3f94c00fd9d826a2588df882ed13 | 26.3 | 124 | 0.6307 | 4 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/user/AbstractInfoFakeDialogFragment.kt | 1 | 6602 | package de.westnordost.streetcomplete.user
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.ViewPropertyAnimator
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.view.animation.OvershootInterpolator
import androidx.fragment.app.Fragment
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.util.Transforms
import de.westnordost.streetcomplete.util.animateFrom
import de.westnordost.streetcomplete.util.animateTo
import de.westnordost.streetcomplete.util.applyTransforms
/** It is not a real dialog because a real dialog has its own window, or in other words, has a
* different root view than the rest of the UI. However, for the calculation to animate the icon
* from another view to the position in the "dialog", there must be a common root view.*/
abstract class AbstractInfoFakeDialogFragment(layoutId: Int) : Fragment(layoutId) {
/** View from which the title image view is animated from (and back on dismissal)*/
private var sharedTitleView: View? = null
var isShowing: Boolean = false
private set
// need to keep the animators here to be able to clear them on cancel
private val currentAnimators: MutableList<ViewPropertyAnimator> = mutableListOf()
private lateinit var dialogAndBackgroundContainer: ViewGroup
private lateinit var dialogBackground: View
private lateinit var dialogContentContainer: ViewGroup
private lateinit var dialogBubbleBackground: View
private lateinit var titleView: View
/* ---------------------------------------- Lifecycle --------------------------------------- */
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dialogAndBackgroundContainer = view.findViewById(R.id.dialogAndBackgroundContainer)
dialogBackground = view.findViewById(R.id.dialogBackground)
titleView = view.findViewById(R.id.titleView)
dialogContentContainer = view.findViewById(R.id.dialogContentContainer)
dialogBubbleBackground = view.findViewById(R.id.dialogBubbleBackground)
dialogAndBackgroundContainer.setOnClickListener { dismiss() }
}
override fun onDestroy() {
super.onDestroy()
sharedTitleView = null
clearAnimators()
}
/* ---------------------------------------- Interface --------------------------------------- */
open fun dismiss(): Boolean {
if (currentAnimators.isNotEmpty()) return false
isShowing = false
animateOut(sharedTitleView)
return true
}
protected fun show(sharedView: View): Boolean {
if (currentAnimators.isNotEmpty()) return false
isShowing = true
this.sharedTitleView = sharedView
animateIn(sharedView)
return true
}
/* ----------------------------------- Animating in and out --------------------------------- */
private fun animateIn(sharedView: View) {
dialogAndBackgroundContainer.visibility = View.VISIBLE
currentAnimators.addAll(
createDialogPopInAnimations() + listOf(
createTitleImageFlingInAnimation(sharedView),
createFadeInBackgroundAnimation()
)
)
currentAnimators.forEach { it.start() }
}
private fun animateOut(sharedView: View?) {
currentAnimators.addAll(createDialogPopOutAnimations())
if (sharedView != null) currentAnimators.add(createTitleImageFlingOutAnimation(sharedView))
currentAnimators.add(createFadeOutBackgroundAnimation())
currentAnimators.forEach { it.start() }
}
private fun createFadeInBackgroundAnimation(): ViewPropertyAnimator {
dialogBackground.alpha = 0f
return dialogBackground.animate()
.alpha(1f)
.setDuration(ANIMATION_TIME_IN_MS)
.setInterpolator(DecelerateInterpolator())
.withEndAction { currentAnimators.clear() }
}
private fun createFadeOutBackgroundAnimation(): ViewPropertyAnimator {
return dialogBackground.animate()
.alpha(0f)
.setDuration(ANIMATION_TIME_OUT_MS)
.setInterpolator(AccelerateInterpolator())
.withEndAction {
dialogAndBackgroundContainer.visibility = View.INVISIBLE
currentAnimators.clear()
}
}
private fun createTitleImageFlingInAnimation(sourceView: View): ViewPropertyAnimator {
sourceView.visibility = View.INVISIBLE
val root = sourceView.rootView as ViewGroup
titleView.applyTransforms(Transforms.IDENTITY)
return titleView.animateFrom(sourceView, root)
.setDuration(ANIMATION_TIME_IN_MS)
.setInterpolator(OvershootInterpolator())
}
private fun createTitleImageFlingOutAnimation(targetView: View): ViewPropertyAnimator {
val root = targetView.rootView as ViewGroup
return titleView.animateTo(targetView, root)
.setDuration(ANIMATION_TIME_OUT_MS)
.setInterpolator(AccelerateDecelerateInterpolator())
.withEndAction {
targetView.visibility = View.VISIBLE
sharedTitleView = null
}
}
private fun createDialogPopInAnimations(): List<ViewPropertyAnimator> {
return listOf(dialogContentContainer, dialogBubbleBackground).map {
it.alpha = 0f
it.scaleX = 0.5f
it.scaleY = 0.5f
it.translationY = 0f
it.animate()
.alpha(1f)
.scaleX(1f).scaleY(1f)
.setDuration(ANIMATION_TIME_IN_MS)
.setInterpolator(OvershootInterpolator())
}
}
private fun createDialogPopOutAnimations(): List<ViewPropertyAnimator> {
return listOf(dialogContentContainer, dialogBubbleBackground).map {
it.animate()
.alpha(0f)
.scaleX(0.5f).scaleY(0.5f)
.translationYBy(it.height * 0.2f)
.setDuration(ANIMATION_TIME_OUT_MS)
.setInterpolator(AccelerateInterpolator())
}
}
private fun clearAnimators() {
for (anim in currentAnimators) {
anim.cancel()
}
currentAnimators.clear()
}
companion object {
const val ANIMATION_TIME_IN_MS = 600L
const val ANIMATION_TIME_OUT_MS = 300L
}
}
| gpl-3.0 | a9437583b3beca0a27a8f6188c0ef166 | 37.383721 | 100 | 0.657831 | 5.618723 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/adapters/CommitFileAdapter.kt | 1 | 6510 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.adapters
import android.graphics.Color
import android.support.v7.widget.RecyclerView
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.BackgroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import giuliolodi.gitnav.R
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.row_commit_file.view.*
import org.eclipse.egit.github.core.CommitFile
import android.text.style.ForegroundColorSpan
/**
* Created by giulio on 06/01/2018.
*/
class CommitFileAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var mCommitFileList: MutableList<CommitFile?> = arrayListOf()
private val onFileClick: PublishSubject<CommitFile> = PublishSubject.create()
fun getPositionClicks(): Observable<CommitFile> {
return onFileClick
}
class CommitFileHolder(root: View) : RecyclerView.ViewHolder(root) {
fun bind (file: CommitFile) = with(itemView) {
row_commit_file_filename.text = file.filename.substring(file.filename.lastIndexOf("/") + 1, file.filename.length)
if (file.patch != null && !file.patch.isEmpty()) {
val raw = file.patch
val cleaned = raw.substring(raw.lastIndexOf("@@") + 3, raw.length)
val spannable = SpannableString(cleaned)
val c = cleaned.toCharArray()
val backslash: MutableList<String> = mutableListOf()
val piu: MutableList<String> = mutableListOf()
val meno: MutableList<String> = mutableListOf()
for (i in 0 until c.size - 1) {
if (c[i] == '\n') {
backslash.add(i.toString())
}
if (c[i] == '\n' && c[i + 1] == '+') {
piu.add(i.toString())
}
if (c[i] == '\n' && c[i + 1] == '-') {
meno.add(i.toString())
}
}
for (i in 0 until piu.size) {
for (j in 0 until backslash.size) {
if (Integer.valueOf(piu[i]) < Integer.valueOf(backslash[j])) {
spannable.setSpan(BackgroundColorSpan(Color.parseColor("#cff7cf")), Integer.valueOf(piu[i]), Integer.valueOf(backslash[j]), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
break
}
}
}
for (i in 0 until meno.size) {
for (j in 0 until backslash.size) {
if (Integer.valueOf(meno[i]) < Integer.valueOf(backslash[j])) {
spannable.setSpan(BackgroundColorSpan(Color.parseColor("#f7cdcd")), Integer.valueOf(meno[i]), Integer.valueOf(backslash[j]), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
break
}
}
}
row_commit_file_cv.setOnClickListener {
if (row_commit_file_content.text == "...")
row_commit_file_content.text = spannable
else
row_commit_file_content.text = "..."
}
}
val changed = "+ " + file.additions.toString() + " - " + file.deletions.toString()
val changedString = SpannableString(changed)
changedString.setSpan(ForegroundColorSpan(Color.parseColor("#099901")), 0, changed.indexOf("-"), Spanned.SPAN_INCLUSIVE_INCLUSIVE)
changedString.setSpan(ForegroundColorSpan(Color.parseColor("#c4071a")), changed.indexOf("-"), changedString.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
row_commit_file_changes.text = changedString
}
}
class LoadingHolder(root: View) : RecyclerView.ViewHolder(root)
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
val root: RecyclerView.ViewHolder
if (viewType == 1) {
val view = (LayoutInflater.from(parent?.context).inflate(R.layout.row_commit_file, parent, false))
root = CommitFileHolder(view)
} else {
val view = (LayoutInflater.from(parent?.context).inflate(R.layout.row_loading, parent, false))
root = LoadingHolder(view)
}
return root
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is CommitFileHolder) {
val file = mCommitFileList[position]!!
holder.bind(file)
holder.itemView.setOnClickListener { onFileClick.onNext(file) }
}
}
override fun getItemViewType(position: Int): Int { return if (mCommitFileList[position] != null) 1 else 0 }
override fun getItemCount(): Int { return mCommitFileList.size }
override fun getItemId(position: Int): Long { return position.toLong() }
fun addCommitFileList(commitFileList: List<CommitFile>) {
if (mCommitFileList.isEmpty()) {
mCommitFileList.addAll(commitFileList)
notifyDataSetChanged()
}
else if (!commitFileList.isEmpty()) {
val lastItemIndex = if (mCommitFileList.size > 0) mCommitFileList.size else 0
mCommitFileList.addAll(commitFileList)
notifyItemRangeInserted(lastItemIndex, mCommitFileList.size)
}
}
fun addCommitFile(commitFile: CommitFile) {
mCommitFileList.add(commitFile)
notifyItemInserted(mCommitFileList.size - 1)
}
fun addLoading() {
mCommitFileList.add(null)
notifyItemInserted(mCommitFileList.size - 1)
}
fun clear() {
mCommitFileList.clear()
notifyDataSetChanged()
}
} | apache-2.0 | 9d3e0b1052cf6b534be0874c9a63d5e2 | 41.006452 | 188 | 0.60722 | 4.69697 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/presentation/profile_courses/ProfileCoursesPresenter.kt | 1 | 6169 | package org.stepik.android.presentation.profile_courses
import android.os.Bundle
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.subscribeBy
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.MainScheduler
import ru.nobird.android.domain.rx.emptyOnErrorStub
import ru.nobird.android.core.model.mapPaged
import ru.nobird.android.core.model.mapToLongArray
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.domain.course_list.interactor.CourseListInteractor
import org.stepik.android.domain.course_list.model.CourseListItem
import org.stepik.android.domain.course_list.model.CourseListQuery
import org.stepik.android.domain.profile.model.ProfileData
import org.stepik.android.model.Course
import org.stepik.android.presentation.course_continue.delegate.CourseContinuePresenterDelegate
import org.stepik.android.presentation.course_continue.delegate.CourseContinuePresenterDelegateImpl
import org.stepik.android.view.injection.course.EnrollmentCourseUpdates
import org.stepik.android.view.injection.profile.UserId
import ru.nobird.android.presentation.base.PresenterBase
import ru.nobird.android.presentation.base.PresenterViewContainer
import ru.nobird.android.presentation.base.delegate.PresenterDelegate
import javax.inject.Inject
class ProfileCoursesPresenter
@Inject
constructor(
@UserId
private val userId: Long,
private val profileDataObservable: Observable<ProfileData>,
private val courseListInteractor: CourseListInteractor,
@EnrollmentCourseUpdates
private val enrollmentUpdatesObservable: Observable<Course>,
viewContainer: PresenterViewContainer<ProfileCoursesView>,
continueCoursePresenterDelegate: CourseContinuePresenterDelegateImpl,
@BackgroundScheduler
private val backgroundScheduler: Scheduler,
@MainScheduler
private val mainScheduler: Scheduler
) : PresenterBase<ProfileCoursesView>(viewContainer), CourseContinuePresenterDelegate by continueCoursePresenterDelegate {
companion object {
private const val KEY_COURSES = "courses"
}
override val delegates: List<PresenterDelegate<in ProfileCoursesView>> =
listOf(continueCoursePresenterDelegate)
private var state: ProfileCoursesView.State = ProfileCoursesView.State.Idle
set(value) {
field = value
view?.setState(value)
}
private var isBlockingLoading: Boolean = false
set(value) {
field = value
view?.setBlockingLoading(value)
}
init {
subscriberForEnrollmentUpdates()
}
override fun attachView(view: ProfileCoursesView) {
super.attachView(view)
view.setBlockingLoading(isBlockingLoading)
view.setState(state)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
val courseIds = savedInstanceState.getLongArray(KEY_COURSES)
if (courseIds != null) {
if (state == ProfileCoursesView.State.Idle) {
state = ProfileCoursesView.State.Loading
compositeDisposable += courseListInteractor // TODO Cache data source?
.getCourseListItems(courseIds.toList(), courseViewSource = CourseViewSource.Query(CourseListQuery(teacher = userId, order = CourseListQuery.Order.POPULARITY_DESC)))
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onSuccess = { state = ProfileCoursesView.State.Content(it) },
onError = { state = ProfileCoursesView.State.Idle; fetchCourses() }
)
}
}
}
fun fetchCourses(forceUpdate: Boolean = false) {
if (state == ProfileCoursesView.State.Idle || (forceUpdate && state is ProfileCoursesView.State.Error)) {
state = ProfileCoursesView.State.Loading
compositeDisposable += profileDataObservable
.firstElement()
.flatMapSingleElement { profileData ->
// TODO Pagination
courseListInteractor
.getCourseListItems(
CourseListQuery(
teacher = profileData.user.id,
order = CourseListQuery.Order.POPULARITY_DESC
)
)
}
.filter { it.isNotEmpty() }
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onSuccess = { state = ProfileCoursesView.State.Content(it) },
onComplete = { state = ProfileCoursesView.State.Empty },
onError = { state = ProfileCoursesView.State.Error }
)
}
}
private fun subscriberForEnrollmentUpdates() {
compositeDisposable += enrollmentUpdatesObservable
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onNext = { enrolledCourse ->
val oldState = state
if (oldState is ProfileCoursesView.State.Content) {
state = ProfileCoursesView.State.Content(
oldState.courseListDataItems.mapPaged {
if (it.course.id == enrolledCourse.id) it.copy(course = enrolledCourse) else it
}
)
}
},
onError = emptyOnErrorStub
)
}
override fun onSaveInstanceState(outState: Bundle) {
val courseListDataItems = (state as? ProfileCoursesView.State.Content)
?.courseListDataItems
?: return
outState.putLongArray(KEY_COURSES, courseListDataItems.mapToLongArray(CourseListItem.Data::id))
super.onSaveInstanceState(outState)
}
} | apache-2.0 | 74ee63d8224d7da0586beaf534c1a2cf | 40.689189 | 184 | 0.660885 | 5.706753 | false | false | false | false |
marius-m/racer_test | core/src/main/java/lt/markmerkk/app/RacerGame.kt | 1 | 2437 | package lt.markmerkk.app
import com.badlogic.gdx.Game
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.World
import lt.markmerkk.app.box2d.WorldProviderImpl
import lt.markmerkk.app.entities.PlayerServer
import lt.markmerkk.app.factory.PhysicsComponentFactory
import lt.markmerkk.app.mvp.*
import lt.markmerkk.app.screens.GameScreen
/**
* @author mariusmerkevicius
* @since 2016-06-04
*/
class RacerGame(
private val isHost: Boolean,
private val serverIp: String = Const.DEFAULT_SERVER_IP
) : Game() {
lateinit var camera: CameraHelper
lateinit var world: World
lateinit var componentFactory: PhysicsComponentFactory
lateinit var worldPresenter: WorldPresenter
lateinit var debugPresenter: DebugPresenter
lateinit var serverPresenter: ServerPresenter
lateinit var playerPresenterServer: PlayerPresenterServer
private val players = mutableListOf<PlayerServer>()
override fun create() {
camera = CameraHelper(GameScreen.VIRTUAL_WIDTH, GameScreen.VIRTUAL_HEIGHT)
world = World(Vector2(0.0f, 0.0f), true)
componentFactory = PhysicsComponentFactory(world, camera)
worldPresenter = WorldPresenterImpl(WorldInteractorImpl(world))
debugPresenter = DebugPresenterImpl(world, camera)
worldPresenter.onAttach()
debugPresenter.onAttach()
componentFactory.createBoundWalls()
componentFactory.createPen()
if (isHost) {
playerPresenterServer = PlayerPresenterServerImpl(
WorldProviderImpl(world),
players
)
serverPresenter = ServerPresenterImpl(
serverInteractor = ServerInteractorImpl(),
playerPresenterServer = playerPresenterServer
)
serverPresenter.onAttach()
}
setScreen(GameScreen(camera))
}
override fun render() {
super.render()
val deltaTime = Gdx.graphics.deltaTime
worldPresenter.render(deltaTime)
debugPresenter.render()
if (isHost) {
serverPresenter.update()
playerPresenterServer.render(deltaTime)
}
}
override fun dispose() {
debugPresenter.onDetach()
worldPresenter.onDetach()
if (isHost) {
serverPresenter.onDetach()
}
super.dispose()
}
} | apache-2.0 | 187811bf91aa6a240888e16ab7a6585b | 30.662338 | 82 | 0.673779 | 5.109015 | false | false | false | false |
savvasdalkitsis/gameframe | workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/element/tools/model/OvalTool.kt | 1 | 2865 | /**
* Copyright 2017 Savvas Dalkitsis
* 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.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.feature.workspace.element.tools.model
import com.savvasdalkitsis.gameframe.feature.workspace.element.grid.model.ColorGrid
import com.savvasdalkitsis.gameframe.feature.workspace.element.grid.model.Grid
/**
* Modified from http://stackoverflow.com/questions/15474122/is-there-a-midpoint-ellipse-algorithm
*/
open class OvalTool : ScratchTool() {
override fun drawOnScratch(scratch: Grid, startColumn: Int, startRow: Int, column: Int, row: Int, color: Int) {
val rx = Math.abs(startColumn - column) / 2f
val ry = Math.abs(startRow - row) / 2f
val cx = Math.min(startColumn, column) + rx
val cy = Math.min(startRow, row) + ry
val a2 = rx * rx
val b2 = ry * ry
val twoA2 = 2 * a2
val twoB2 = 2 * b2
var p: Float
var x = 0f
var y = ry
var px = 0f
var py = twoA2 * y
plot(cx, cy, x, y, scratch, color)
p = Math.round(b2 - a2 * ry + 0.25 * a2).toFloat()
while (px < py) {
x++
px += twoB2
if (p < 0)
p += b2 + px
else {
y--
py -= twoA2
p += b2 + px - py
}
plot(cx, cy, x, y, scratch, color)
}
p = Math.round(b2.toDouble() * (x + 0.5) * (x + 0.5) + a2 * (y - 1) * (y - 1) - a2 * b2).toFloat()
while (y > 0) {
y--
py -= twoA2
if (p > 0)
p += a2 - py
else {
x++
px += twoB2
p += a2 - py + px
}
plot(cx, cy, x, y, scratch, color)
}
}
private fun plot(xc: Float, yc: Float, x: Float, y: Float, scratch: Grid, color: Int) {
draw(xc + x, yc + y, scratch, color)
draw(xc - x, yc + y, scratch, color)
draw(xc + x, yc - y, scratch, color)
draw(xc - x, yc - y, scratch, color)
}
private fun draw(x: Float, y: Float, scratch: Grid, color: Int) {
val c = x.toInt()
val r = y.toInt()
if (!ColorGrid.isOutOfBounds(c, r)) {
scratch.setColor(color, c, r)
}
}
}
| apache-2.0 | 52782b6e3da202d3c29c213bcf3ccdaf | 31.556818 | 115 | 0.544852 | 3.56787 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ReaderChapter.kt | 1 | 1309 | package eu.kanade.tachiyomi.ui.reader.model
import com.jakewharton.rxrelay.BehaviorRelay
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.ui.reader.loader.PageLoader
import eu.kanade.tachiyomi.util.system.logcat
data class ReaderChapter(val chapter: Chapter) {
var state: State =
State.Wait
set(value) {
field = value
stateRelay.call(value)
}
private val stateRelay by lazy { BehaviorRelay.create(state) }
val stateObserver by lazy { stateRelay.asObservable() }
val pages: List<ReaderPage>?
get() = (state as? State.Loaded)?.pages
var pageLoader: PageLoader? = null
var requestedPage: Int = 0
var references = 0
private set
fun ref() {
references++
}
fun unref() {
references--
if (references == 0) {
if (pageLoader != null) {
logcat { "Recycling chapter ${chapter.name}" }
}
pageLoader?.recycle()
pageLoader = null
state = State.Wait
}
}
sealed class State {
object Wait : State()
object Loading : State()
class Error(val error: Throwable) : State()
class Loaded(val pages: List<ReaderPage>) : State()
}
}
| apache-2.0 | 1dbc92a3d7d0cee61de7652319a292a8 | 23.698113 | 66 | 0.597403 | 4.348837 | false | false | false | false |
Heiner1/AndroidAPS | diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SET_SQUARE_INJECTION.kt | 1 | 1843 | package info.nightscout.androidaps.diaconn.pumplog
import okhttp3.internal.and
import java.nio.ByteBuffer
import java.nio.ByteOrder
/*
* 스퀘어주입 설정(시작)
*/
class LOG_SET_SQUARE_INJECTION private constructor(
val data: String,
val dttm: String,
typeAndKind: Byte, // 47.5=4750
val setAmount: Short, // 1~30(10분 단위 값 의미)
private val injectTime: Byte,
val batteryRemain: Byte
) {
val type: Byte = PumplogUtil.getType(typeAndKind)
val kind: Byte = PumplogUtil.getKind(typeAndKind)
fun getInjectTime(): Int {
return injectTime and 0xff
}
override fun toString(): String {
val sb = StringBuilder("LOG_SET_SQUARE_INJECTION{")
sb.append("LOG_KIND=").append(LOG_KIND.toInt())
sb.append(", data='").append(data).append('\'')
sb.append(", dttm='").append(dttm).append('\'')
sb.append(", type=").append(type.toInt())
sb.append(", kind=").append(kind.toInt())
sb.append(", setAmount=").append(setAmount.toInt())
sb.append(", injectTime=").append(injectTime and 0xff)
sb.append(", batteryRemain=").append(batteryRemain.toInt())
sb.append('}')
return sb.toString()
}
companion object {
const val LOG_KIND: Byte = 0x0C
fun parse(data: String): LOG_SET_SQUARE_INJECTION {
val bytes = PumplogUtil.hexStringToByteArray(data)
val buffer = ByteBuffer.wrap(bytes)
buffer.order(ByteOrder.LITTLE_ENDIAN)
return LOG_SET_SQUARE_INJECTION(
data,
PumplogUtil.getDttm(buffer),
PumplogUtil.getByte(buffer),
PumplogUtil.getShort(buffer),
PumplogUtil.getByte(buffer),
PumplogUtil.getByte(buffer)
)
}
}
} | agpl-3.0 | 70da31178717f459253ef3fdbc7a4868 | 30.824561 | 67 | 0.603971 | 4.002208 | false | false | false | false |
pambrose/prometheus-proxy | src/main/kotlin/io/prometheus/proxy/AgentContext.kt | 1 | 3963 | /*
* Copyright © 2020 Paul Ambrose ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction")
package io.prometheus.proxy
import com.github.pambrose.common.delegate.AtomicDelegates.atomicBoolean
import com.github.pambrose.common.delegate.AtomicDelegates.nonNullableReference
import com.github.pambrose.common.dsl.GuavaDsl.toStringElements
import io.prometheus.grpc.RegisterAgentRequest
import kotlinx.coroutines.channels.Channel
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
import kotlin.time.TimeMark
import kotlin.time.TimeSource.Monotonic
internal class AgentContext(private val remoteAddr: String) {
val agentId = AGENT_ID_GENERATOR.incrementAndGet().toString()
private val scrapeRequestChannel = Channel<ScrapeRequestWrapper>(Channel.UNLIMITED)
private val channelBacklogSize = AtomicInteger(0)
private val clock = Monotonic
private var lastActivityTimeMark: TimeMark by nonNullableReference(clock.markNow())
private var lastRequestTimeMark: TimeMark by nonNullableReference(clock.markNow())
private var valid by atomicBoolean(true)
private var launchId: String by nonNullableReference("Unassigned")
var hostName: String by nonNullableReference("Unassigned")
private set
var agentName: String by nonNullableReference("Unassigned")
private set
var consolidated: Boolean by nonNullableReference(false)
private set
internal val desc: String
get() = if (consolidated) "consolidated " else ""
private val lastRequestDuration
get() = lastRequestTimeMark.elapsedNow()
val inactivityDuration
get() = lastActivityTimeMark.elapsedNow()
val scrapeRequestBacklogSize: Int
get() = channelBacklogSize.get()
init {
markActivityTime(true)
}
fun assignProperties(request: RegisterAgentRequest) {
launchId = request.launchId
agentName = request.agentName
hostName = request.hostName
consolidated = request.consolidated
}
suspend fun writeScrapeRequest(scrapeRequest: ScrapeRequestWrapper) {
scrapeRequestChannel.send(scrapeRequest)
channelBacklogSize.incrementAndGet()
}
suspend fun readScrapeRequest(): ScrapeRequestWrapper? =
scrapeRequestChannel.receiveCatching().getOrNull()
?.apply {
channelBacklogSize.decrementAndGet()
}
fun isValid() = valid && !scrapeRequestChannel.isClosedForReceive
fun isNotValid() = !isValid()
fun invalidate() {
valid = false
scrapeRequestChannel.close()
}
fun markActivityTime(isRequest: Boolean) {
lastActivityTimeMark = clock.markNow()
if (isRequest)
lastRequestTimeMark = clock.markNow()
}
override fun toString() =
toStringElements {
add("agentId", agentId)
add("launchId", launchId)
add("consolidated", consolidated)
add("valid", valid)
add("agentName", agentName)
add("hostName", hostName)
add("remoteAddr", remoteAddr)
add("lastRequestDuration", lastRequestDuration)
//add("inactivityDuration", inactivityDuration)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AgentContext
return agentId == other.agentId
}
override fun hashCode() = agentId.hashCode()
companion object {
private val AGENT_ID_GENERATOR = AtomicLong(0L)
}
} | apache-2.0 | facb65868f42f82706ebd1f4a370502e | 30.452381 | 85 | 0.747855 | 4.661176 | false | false | false | false |
Subsets and Splits