repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Soya93/Extract-Refactoring | platform/built-in-server/testSrc/BuiltInServerTestCase.kt | 2 | 1936 | package org.jetbrains.ide
import com.intellij.testFramework.DisposeModulesRule
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.RuleChain
import com.intellij.testFramework.TemporaryDirectory
import io.netty.handler.codec.http.HttpResponseStatus
import org.assertj.core.api.Assertions.assertThat
import org.junit.ClassRule
import org.junit.Rule
import org.junit.rules.Timeout
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.TimeUnit
internal abstract class BuiltInServerTestCase {
companion object {
@JvmField
@ClassRule val projectRule = ProjectRule()
}
protected val tempDirManager = TemporaryDirectory()
protected val manager = TestManager(projectRule, tempDirManager)
private val ruleChain = RuleChain(
tempDirManager,
Timeout(60, TimeUnit.SECONDS),
manager,
DisposeModulesRule(projectRule))
@Rule fun getChain() = ruleChain
protected open val urlPathPrefix = ""
protected fun doTest(filePath: String? = manager.filePath, additionalCheck: ((connection: HttpURLConnection) -> Unit)? = null) {
val serviceUrl = "http://localhost:${BuiltInServerManager.getInstance().port}$urlPathPrefix"
var url = serviceUrl + (if (filePath == null) "" else ("/$filePath"))
val line = manager.annotation?.line ?: -1
if (line != -1) {
url += ":$line"
}
val column = manager.annotation?.column ?: -1
if (column != -1) {
url += ":$column"
}
val connection = URL(url).openConnection() as HttpURLConnection
val expectedStatus = HttpResponseStatus.valueOf(manager.annotation?.status ?: 200)
assertThat(HttpResponseStatus.valueOf(connection.responseCode)).isEqualTo(expectedStatus)
check(serviceUrl, expectedStatus)
if (additionalCheck != null) {
additionalCheck(connection)
}
}
protected open fun check(serviceUrl: String, expectedStatus: HttpResponseStatus) {
}
} | apache-2.0 | 4b2a2dc78172d44e1cf111b9e404a415 | 32.396552 | 130 | 0.742252 | 4.676329 | false | true | false | false |
Soya93/Extract-Refactoring | platform/script-debugger/protocol/protocol-reader/src/TypeWriter.kt | 2 | 8348 | package org.jetbrains.protocolReader
import org.jetbrains.jsonProtocol.JsonObjectBased
import java.lang.reflect.Method
import java.util.*
internal val FIELD_PREFIX = '_'
internal val NAME_VAR_NAME = "_n"
private fun assignField(out: TextOutput, fieldName: String) = out.append(FIELD_PREFIX).append(fieldName).append(" = ")
internal class TypeRef<T>(val typeClass: Class<T>) {
var type: TypeWriter<T>? = null
}
internal class TypeWriter<T>(val typeClass: Class<T>, jsonSuperClass: TypeRef<*>?, private val volatileFields: List<VolatileFieldBinding>, private val methodHandlerMap: LinkedHashMap<Method, MethodHandler>,
/** Loaders that should read values and save them in field array on parse time. */
private val fieldLoaders: List<FieldLoader>, private val hasLazyFields: Boolean) {
/** Subtype aspects of the type or null */
val subtypeAspect = if (jsonSuperClass == null) null else ExistingSubtypeAspect(jsonSuperClass)
fun writeInstantiateCode(scope: ClassScope, out: TextOutput) {
writeInstantiateCode(scope, false, out)
}
fun writeInstantiateCode(scope: ClassScope, deferredReading: Boolean, out: TextOutput) {
val className = scope.getTypeImplReference(this)
if (deferredReading || subtypeAspect == null) {
out.append(className)
}
else {
subtypeAspect.writeInstantiateCode(className, out)
}
}
fun write(fileScope: FileScope) {
val out = fileScope.output
val valueImplClassName = fileScope.getTypeImplShortName(this)
out.append("private class ").append(valueImplClassName).append('(').append(JSON_READER_PARAMETER_DEF).comma().append("preReadName: String?")
subtypeAspect?.writeSuperFieldJava(out)
out.append(") : ").append(typeClass.canonicalName).openBlock()
if (hasLazyFields || JsonObjectBased::class.java.isAssignableFrom(typeClass)) {
out.append("private var ").append(PENDING_INPUT_READER_NAME).append(": ").append(JSON_READER_CLASS_NAME).append("? = reader.subReader()!!").newLine()
}
val classScope = fileScope.newClassScope()
for (field in volatileFields) {
field.writeFieldDeclaration(classScope, out)
out.newLine()
}
for (loader in fieldLoaders) {
if (loader.asImpl) {
out.append("override")
}
else {
out.append("private")
}
out.append(" var ").appendName(loader)
fun addType() {
out.append(": ")
loader.valueReader.appendFinishedValueTypeName(out)
out.append("? = null")
}
if (loader.valueReader is PrimitiveValueReader) {
val defaultValue = loader.defaultValue ?: loader.valueReader.defaultValue
if (defaultValue != null) {
out.append(" = ").append(defaultValue)
}
else {
addType()
}
}
else {
addType()
}
out.newLine()
}
if (fieldLoaders.isNotEmpty()) {
out.newLine()
}
writeConstructorMethod(classScope, out)
out.newLine()
subtypeAspect?.writeParseMethod(classScope, out)
for ((key, value) in methodHandlerMap.entries) {
out.newLine()
value.writeMethodImplementationJava(classScope, key, out)
out.newLine()
}
writeBaseMethods(out)
subtypeAspect?.writeGetSuperMethodJava(out)
writeEqualsMethod(valueImplClassName, out)
out.indentOut().append('}')
}
/**
* Generates Java implementation of standard methods of JSON type class (if needed):
* {@link org.jetbrains.jsonProtocol.JsonObjectBased#getDeferredReader()}
*/
private fun writeBaseMethods(out: TextOutput) {
val method: Method
try {
method = typeClass.getMethod("getDeferredReader")
}
catch (ignored: NoSuchMethodException) {
// Method not found, skip.
return
}
out.newLine()
writeMethodDeclarationJava(out, method)
out.append(" = ").append(PENDING_INPUT_READER_NAME)
}
private fun writeEqualsMethod(valueImplClassName: String, out: TextOutput) {
if (fieldLoaders.isEmpty()) {
return
}
out.newLine().append("override fun equals(other: Any?): Boolean = ")
out.append("other is ").append(valueImplClassName)
// at first we should compare primitive values, then enums, then string, then objects
fun fieldWeight(reader: ValueReader): Int {
var w = 10
if (reader is PrimitiveValueReader) {
w--
if (reader.className != "String") {
w--
}
}
else if (reader is EnumReader) {
// -1 as primitive, -1 as not a string
w -= 2
}
return w
}
for (loader in fieldLoaders.sortedWith(Comparator<FieldLoader> { f1, f2 -> fieldWeight((f1.valueReader)) - fieldWeight((f2.valueReader))})) {
out.append(" && ")
out.appendName(loader).append(" == ").append("other.").appendName(loader)
}
out.newLine()
}
private fun writeConstructorMethod(classScope: ClassScope, out: TextOutput) {
out.append("init").block {
if (fieldLoaders.isEmpty()) {
out.append(READER_NAME).append(".skipValue()")
}
else {
out.append("var ").append(NAME_VAR_NAME).append(" = preReadName")
out.newLine().append("if (").append(NAME_VAR_NAME).append(" == null && reader.hasNext() && reader.beginObject().hasNext())").block {
out.append(NAME_VAR_NAME).append(" = reader.nextName()")
}
out.newLine()
writeReadFields(out, classScope)
// we don't read all data if we have lazy fields, so, we should not check end of stream
//if (!hasLazyFields) {
out.newLine().newLine().append(READER_NAME).append(".endObject()")
//}
}
}
}
private fun writeReadFields(out: TextOutput, classScope: ClassScope) {
val stopIfAllFieldsWereRead = hasLazyFields
val hasOnlyOneFieldLoader = fieldLoaders.size == 1
val isTracedStop = stopIfAllFieldsWereRead && !hasOnlyOneFieldLoader
if (isTracedStop) {
out.newLine().append("var i = 0")
}
out.newLine().append("loop@ while (").append(NAME_VAR_NAME).append(" != null)").block {
(out + "when (" + NAME_VAR_NAME + ")").block {
var isFirst = true
for (fieldLoader in fieldLoaders) {
if (fieldLoader.skipRead) {
continue
}
if (!isFirst) {
out.newLine()
}
out.append('"')
if (fieldLoader.jsonName.first() == '$') {
out.append('\\')
}
out.append(fieldLoader.jsonName).append('"').append(" -> ")
if (stopIfAllFieldsWereRead && !isTracedStop) {
out.openBlock()
}
val primitiveValueName = if (fieldLoader.valueReader is ObjectValueReader) fieldLoader.valueReader.primitiveValueName else null
if (primitiveValueName != null) {
out.append("if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_OBJECT)").openBlock()
}
out.appendName(fieldLoader).append(" = ")
fieldLoader.valueReader.writeReadCode(classScope, false, out)
if (primitiveValueName != null) {
out.newLine().append("else").openBlock()
assignField(out, "${primitiveValueName}Type")
out.append("reader.peek()").newLine()
assignField(out, primitiveValueName)
out + "reader.nextString(true)"
}
if (stopIfAllFieldsWereRead && !isTracedStop) {
out.newLine().append(READER_NAME).append(".skipValues()").newLine().append("break@loop").closeBlock()
}
if (isFirst) {
isFirst = false
}
}
out.newLine().append("else ->")
if (isTracedStop) {
out.block {
out.append("reader.skipValue()")
out.newLine() + NAME_VAR_NAME + " = reader.nextNameOrNull()"
out.newLine() + "continue@loop"
}
}
else {
out.space().append("reader.skipValue()")
}
}
out.newLine() + NAME_VAR_NAME + " = reader.nextNameOrNull()"
if (isTracedStop) {
out.newLine().newLine().append("if (i++ == ").append(fieldLoaders.size - 1).append(")").block {
(out + READER_NAME + ".skipValues()").newLine() + "break"
}
}
}
}
} | apache-2.0 | ec183bce6fb2653e38e93e22cf229086 | 31.360465 | 206 | 0.616315 | 4.398314 | false | false | false | false |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/jpa/HibernateKotlinIntegrationTest.kt | 1 | 2272 | package com.baeldung.kotlin.jpa
import org.hibernate.cfg.Configuration
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase
import org.hibernate.testing.transaction.TransactionUtil.doInHibernate
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.IOException
import java.util.*
class HibernateKotlinIntegrationTest : BaseCoreFunctionalTestCase() {
private val properties: Properties
@Throws(IOException::class)
get() {
val properties = Properties()
properties.load(javaClass.classLoader.getResourceAsStream("hibernate.properties"))
return properties
}
override fun getAnnotatedClasses(): Array<Class<*>> {
return arrayOf(Person::class.java, PhoneNumber::class.java)
}
override fun configure(configuration: Configuration) {
super.configure(configuration)
configuration.properties = properties
}
@Test
fun givenPersonWithFullData_whenSaved_thenFound() {
doInHibernate(({ this.sessionFactory() }), { session ->
val personToSave = Person(0, "John", "[email protected]", Arrays.asList(PhoneNumber(0, "202-555-0171"), PhoneNumber(0, "202-555-0102")))
session.persist(personToSave)
val personFound = session.find(Person::class.java, personToSave.id)
session.refresh(personFound)
assertTrue(personToSave == personFound)
})
}
@Test
fun givenPerson_whenSaved_thenFound() {
doInHibernate(({ this.sessionFactory() }), { session ->
val personToSave = Person(0, "John")
session.persist(personToSave)
val personFound = session.find(Person::class.java, personToSave.id)
session.refresh(personFound)
assertTrue(personToSave == personFound)
})
}
@Test
fun givenPersonWithNullFields_whenSaved_thenFound() {
doInHibernate(({ this.sessionFactory() }), { session ->
val personToSave = Person(0, "John", null, null)
session.persist(personToSave)
val personFound = session.find(Person::class.java, personToSave.id)
session.refresh(personFound)
assertTrue(personToSave == personFound)
})
}
} | gpl-3.0 | ae9446498f8d6b570a0e91912c68e0ea | 33.439394 | 144 | 0.661532 | 4.655738 | false | true | false | false |
jvsegarra/kotlin-koans | src/i_introduction/_3_Default_Arguments/DefaultAndNamedParams.kt | 1 | 902 | package i_introduction._3_Default_Arguments
import util.*
fun todoTask3(): Nothing = TODO(
"""
Task 3.
Several overloads of 'JavaCode3.foo()' can be replaced with one function in Kotlin.
Change the declaration of the function 'foo' in a way that makes the code using 'foo' compile.
You have to add parameters and replace 'todoTask3()' with a real body.
Uncomment the commented code and make it compile.
""",
documentation = doc2(),
references = { name: String -> JavaCode3().foo(name); foo(name) })
fun foo(name: String, number: Int = 42, toUpperCase: Boolean = false): String =
(if (toUpperCase) name.toUpperCase() else name) + number
fun task3(): String {
return (foo("a") +
foo("b", number = 1) +
foo("c", toUpperCase = true) +
foo(name = "d", number = 2, toUpperCase = true))
}
| mit | 601a5cc9c6a4fdd7d38b0fbf1f53c03e | 36.583333 | 102 | 0.610865 | 4.081448 | false | false | false | false |
EventFahrplan/EventFahrplan | network/src/main/java/info/metadude/android/eventfahrplan/network/repositories/ScheduleNetworkRepository.kt | 1 | 1746 | package info.metadude.android.eventfahrplan.network.repositories
import info.metadude.android.eventfahrplan.commons.logging.Logging
import info.metadude.android.eventfahrplan.network.fetching.FetchFahrplan
import info.metadude.android.eventfahrplan.network.fetching.FetchScheduleResult
import info.metadude.android.eventfahrplan.network.models.Meta
import info.metadude.android.eventfahrplan.network.models.Session
import info.metadude.android.eventfahrplan.network.serialization.FahrplanParser
import okhttp3.OkHttpClient
class ScheduleNetworkRepository(
logging: Logging
) {
private val fetcher = FetchFahrplan(logging)
private val parser = FahrplanParser(logging)
fun fetchSchedule(okHttpClient: OkHttpClient,
url: String,
eTag: String,
onFetchScheduleFinished: (fetchScheduleResult: FetchScheduleResult) -> Unit) {
fetcher.setListener(onFetchScheduleFinished::invoke)
fetcher.fetch(okHttpClient, url, eTag)
}
fun parseSchedule(scheduleXml: String,
eTag: String,
onUpdateSessions: (sessions: List<Session>) -> Unit,
onUpdateMeta: (meta: Meta) -> Unit,
onParsingDone: (result: Boolean, version: String) -> Unit) {
parser.setListener(object : FahrplanParser.OnParseCompleteListener {
override fun onUpdateSessions(sessions: List<Session>) = onUpdateSessions.invoke(sessions)
override fun onUpdateMeta(meta: Meta) = onUpdateMeta.invoke(meta)
override fun onParseDone(result: Boolean, version: String) = onParsingDone.invoke(result, version)
})
parser.parse(scheduleXml, eTag)
}
}
| apache-2.0 | 88472dde9468d11d65fd736580ea2d0b | 41.585366 | 110 | 0.703895 | 4.770492 | false | false | false | false |
fumoffu/jaydeer-game | src/main/kotlin/fr/jaydeer/dice/dto/Dice.kt | 1 | 1151 | package fr.jaydeer.dice.dto
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonSubTypes.Type
import com.fasterxml.jackson.annotation.JsonTypeInfo
import fr.jaydeer.common.api.validation.NoneId
import fr.jaydeer.common.api.validation.groups.Creation
import fr.jaydeer.common.dto.EntityDto
import fr.jaydeer.dice.entity.DiceEntity
import javax.validation.constraints.NotNull
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type",
visible = false, defaultImpl = CustomDice::class)
@JsonSubTypes(
Type(value = NSideDice::class, name = DiceType.Id.N_SIDE),
Type(value = CustomDice::class, name = DiceType.Id.CUSTOM)
)
sealed class Dice
data class NSideDice(val n: Int,
val start: Int = 1,
val step: Int = 1) : Dice()
data class CustomDice(@get:NoneId(value = DiceEntity::class, groups = arrayOf(Creation::class))
override val id: String?,
@NotNull(groups = arrayOf(Creation::class))
val faces: Map<String, Int>?) : EntityDto, Dice() | gpl-3.0 | 20b9685613742143669b8b72f30cf47a | 41.666667 | 96 | 0.694179 | 3.982699 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/inspection/PlatformAnnotationEntryPoint.kt | 1 | 1128 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.inspection
import com.intellij.codeInspection.reference.EntryPoint
import com.intellij.codeInspection.reference.RefElement
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.WriteExternalException
import com.intellij.psi.PsiElement
import org.jdom.Element
class PlatformAnnotationEntryPoint : EntryPoint() {
override fun getDisplayName() = "Minecraft Entry Point"
override fun isEntryPoint(refElement: RefElement, psiElement: PsiElement) = false
override fun isEntryPoint(psiElement: PsiElement) = false
override fun isSelected() = false
override fun setSelected(selected: Boolean) {}
override fun getIgnoreAnnotations() =
arrayOf("org.spongepowered.api.event.Listener", "org.bukkit.event.EventHandler")
@Throws(InvalidDataException::class)
override fun readExternal(element: Element) {
}
@Throws(WriteExternalException::class)
override fun writeExternal(element: Element) {
}
}
| mit | cef0c8b9f7a756471c2f4c086d6ae82d | 30.333333 | 88 | 0.763298 | 4.585366 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/wall/dto/WallAttachedNote.kt | 1 | 2766 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.wall.dto
import com.google.gson.annotations.SerializedName
import com.vk.dto.common.id.UserId
import kotlin.Int
import kotlin.String
import kotlin.collections.List
/**
* @param comments - Comments number
* @param date - Date when the note has been created in Unixtime
* @param id - Note ID
* @param ownerId - Note owner's ID
* @param readComments - Read comments number
* @param title - Note title
* @param viewUrl - URL of the page with note preview
* @param text - Note text
* @param privacyView
* @param privacyComment
* @param canComment
* @param textWiki - Note wiki text
*/
data class WallAttachedNote(
@SerializedName("comments")
val comments: Int,
@SerializedName("date")
val date: Int,
@SerializedName("id")
val id: Int,
@SerializedName("owner_id")
val ownerId: UserId,
@SerializedName("read_comments")
val readComments: Int,
@SerializedName("title")
val title: String,
@SerializedName("view_url")
val viewUrl: String,
@SerializedName("text")
val text: String? = null,
@SerializedName("privacy_view")
val privacyView: List<String>? = null,
@SerializedName("privacy_comment")
val privacyComment: List<String>? = null,
@SerializedName("can_comment")
val canComment: Int? = null,
@SerializedName("text_wiki")
val textWiki: String? = null
)
| mit | a8c9c8e2db84ce98aa1cae12a557ce53 | 35.88 | 81 | 0.682213 | 4.308411 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/constant/AppList.kt | 1 | 455 | package com.intfocus.template.constant
/**
* ****************************************************
* author jameswong
* created on: 17/11/06 下午5:43
* e-mail: [email protected]
* name:
* desc:
* ****************************************************
*/
object AppList {
const val RS = "ruishang"
const val SYP = "shengyinplus"
const val YH = "yonghui"
const val YHTEST = "yonghuitest"
const val YHDEV = "yonghuidev"
}
| gpl-3.0 | b5d0d5a291353d28ee4c72f64f82b330 | 24.055556 | 55 | 0.496674 | 3.758333 | false | true | false | false |
docker-client/docker-compose-v3 | src/main/kotlin/de/gesellix/docker/compose/adapters/StringToServiceNetworksAdapter.kt | 1 | 3111 | package de.gesellix.docker.compose.adapters
import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonReader
import com.squareup.moshi.ToJson
import de.gesellix.docker.compose.types.ServiceNetwork
class StringToServiceNetworksAdapter {
@ToJson
fun toJson(@ServiceNetworksType networks: Map<String, ServiceNetwork>): List<String> {
throw UnsupportedOperationException()
}
@FromJson
@ServiceNetworksType
fun fromJson(reader: JsonReader): Map<String, ServiceNetwork?> {
val result = hashMapOf<String, ServiceNetwork?>()
when (reader.peek()) {
JsonReader.Token.BEGIN_OBJECT -> {
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
when (reader.peek()) {
JsonReader.Token.NULL -> result[name] = reader.nextNull()
JsonReader.Token.STRING -> throw UnsupportedOperationException("didn't expect a String value for network $name")
// result[name] = reader.nextString()
JsonReader.Token.BEGIN_OBJECT -> {
val serviceNetwork = ServiceNetwork()
reader.beginObject()
while (reader.hasNext()) {
when (reader.nextName()) {
"ipv4_address" -> serviceNetwork.ipv4Address = reader.nextString()
"ipv6_address" -> serviceNetwork.ipv6Address = reader.nextString()
"aliases" -> {
val aliases = arrayListOf<String>()
reader.beginArray()
while (reader.hasNext()) {
aliases.add(reader.nextString())
}
reader.endArray()
serviceNetwork.aliases = aliases
}
else -> {
// ...
}
}
}
reader.endObject()
result[name] = serviceNetwork
}
else -> {
// ...
}
}
}
reader.endObject()
}
JsonReader.Token.BEGIN_ARRAY -> {
reader.beginArray()
while (reader.hasNext()) {
val name = reader.nextString()
// def value = reader.nextNull()
result[name] = null
}
reader.endArray()
}
else -> {
// ...
}
}
return result
}
}
| mit | d6777496c5208b7cba952cdc1cafc255 | 40.48 | 136 | 0.406943 | 6.66167 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xquery/test/uk/co/reecedunn/intellij/plugin/xquery/tests/parser/UpdateFacilityParserTest.kt | 1 | 33715 | /*
* Copyright (C) 2016-2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.tests.parser
import com.intellij.openapi.extensions.PluginId
import org.hamcrest.CoreMatchers.`is`
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import uk.co.reecedunn.intellij.plugin.core.psi.toPsiTreeString
import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat
import uk.co.reecedunn.intellij.plugin.core.vfs.ResourceVirtualFileSystem
import uk.co.reecedunn.intellij.plugin.core.vfs.decode
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModule
@Suppress("RedundantVisibilityModifier", "Reformat")
@DisplayName("XQuery Update Facility 3.0 - Parser")
class UpdateFacilityParserTest : ParserTestCase() {
override val pluginId: PluginId = PluginId.getId("UpdateFacilityParserTest")
private val res = ResourceVirtualFileSystem(this::class.java.classLoader)
fun parseResource(resource: String): XQueryModule = res.toPsiFile(resource, project)
fun loadResource(resource: String): String? = res.findFileByPath(resource)!!.decode()
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (26) FunctionDecl")
internal inner class FunctionDecl {
@Test
@DisplayName("updating annotation; external")
fun testFunctionDecl_Updating() {
val expected = loadResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("updating annotation; function body")
fun testFunctionDecl_Updating_EnclosedExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating_EnclosedExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating_EnclosedExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("updating annotation; missing function keyword")
fun testFunctionDecl_Updating_MissingFunctionKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating_MissingFunctionKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating_MissingFunctionKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (141) RevalidationDecl")
internal inner class RevalidationDecl {
@Test
@DisplayName("revalidation declaration")
fun testRevalidationDecl() {
val expected = loadResource("tests/parser/xquery-update-1.0/RevalidationDecl.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RevalidationDecl.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("revalidation declaration; compact whitespace")
fun testRevalidationDecl_CompactWhitespace() {
val expected = loadResource("tests/parser/xquery-update-1.0/RevalidationDecl_CompactWhitespace.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RevalidationDecl_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing revalidation mode")
fun testRevalidationDecl_MissingRevalidationMode() {
val expected = loadResource("tests/parser/xquery-update-1.0/RevalidationDecl_MissingRevalidationMode.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RevalidationDecl_MissingRevalidationMode.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing revalidation keyword")
fun testRevalidationDecl_MissingRevalidationKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/RevalidationDecl_MissingRevalidationKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RevalidationDecl_MissingRevalidationKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing semicolon")
fun testRevalidationDecl_MissingSemicolon() {
val expected = loadResource("tests/parser/xquery-update-1.0/RevalidationDecl_MissingSemicolon.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RevalidationDecl_MissingSemicolon.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("prolog body statements before")
fun testRevalidationDecl_PrologBodyStatementsBefore() {
val expected = loadResource("tests/parser/xquery-update-1.0/RevalidationDecl_PrologBodyStatementsBefore.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RevalidationDecl_PrologBodyStatementsBefore.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("prolog body statements after")
fun testRevalidationDecl_PrologBodyStatementsAfter() {
val expected = loadResource("tests/parser/xquery-update-1.0/RevalidationDecl_PrologBodyStatementsAfter.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RevalidationDecl_PrologBodyStatementsAfter.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (142) InsertExprTargetChoice")
internal inner class InsertExprTargetChoice {
@Test
@DisplayName("into")
fun testInsertExprTargetChoice_Into() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_Node.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_Node.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("first")
fun testInsertExprTargetChoice_First() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_First.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_First.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("last")
fun testInsertExprTargetChoice_Last() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_Last.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_Last.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("first/last; missing 'as' keyword")
fun testInsertExprTargetChoice_FirstLast_MissingAsKeyword() {
val expected =
loadResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_FirstLast_MissingAsKeyword.txt")
val actual =
parseResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_FirstLast_MissingAsKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("first/last; missing 'first'/'last' keyword")
fun testInsertExprTargetChoice_FirstLast_MissingFirstLastKeyword() {
val expected =
loadResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_FirstLast_MissingFirstLastKeyword.txt")
val actual =
parseResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_FirstLast_MissingFirstLastKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("first/last; missing 'into' keyword")
fun testInsertExprTargetChoice_FirstLast_MissingIntoKeyword() {
val expected =
loadResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_FirstLast_MissingIntoKeyword.txt")
val actual =
parseResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_FirstLast_MissingIntoKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("before")
fun testInsertExprTargetChoice_Before() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_Before.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_Before.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("after")
fun testInsertExprTargetChoice_After() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_After.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExprTargetChoice_After.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (143) InsertExpr")
internal inner class InsertExpr {
@Test
@DisplayName("node")
fun testInsertExpr_Node() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_Node.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_Node.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("node; compact whitespace")
fun testInsertExpr_Node_CompactWhitespace() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_Node_CompactWhitespace.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_Node_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("nodes")
fun testInsertExpr_Nodes() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_Nodes.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_Nodes.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("nodes; compact whitespace")
fun testInsertExpr_Nodes_CompactWhitespace() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_Nodes_CompactWhitespace.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_Nodes_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing source SourceExpr")
fun testInsertExpr_MissingSourceExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_MissingSourceExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_MissingSourceExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing InsertExprTargetChoice")
fun testInsertExpr_MissingInsertExprTargetChoice() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_MissingInsertExprTargetChoice.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_MissingInsertExprTargetChoice.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing TargetExpr")
fun testInsertExpr_MissingTargetExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/InsertExpr_MissingTargetExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/InsertExpr_MissingTargetExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (144) DeleteExpr")
internal inner class DeleteExpr {
@Test
@DisplayName("node")
fun testDeleteExpr_Node() {
val expected = loadResource("tests/parser/xquery-update-1.0/DeleteExpr_Node.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/DeleteExpr_Node.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("nodes")
fun testDeleteExpr_Nodes() {
val expected = loadResource("tests/parser/xquery-update-1.0/DeleteExpr_Nodes.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/DeleteExpr_Nodes.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing TargetExpr")
fun testDeleteExpr_MissingTargetExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/DeleteExpr_MissingTargetExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/DeleteExpr_MissingTargetExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (145) ReplaceExpr")
internal inner class ReplaceExpr {
@Test
@DisplayName("replace expression")
fun testReplaceExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/ReplaceExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/ReplaceExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing TargetExpr")
fun testReplaceExpr_MissingTargetExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/ReplaceExpr_MissingTargetExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/ReplaceExpr_MissingTargetExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing 'with' keyword")
fun testReplaceExpr_MissingWithKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/ReplaceExpr_MissingWithKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/ReplaceExpr_MissingWithKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing ReplaceExpr")
fun testReplaceExpr_MissingReplaceExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/ReplaceExpr_MissingReplaceExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/ReplaceExpr_MissingReplaceExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("value of")
fun testReplaceExpr_ValueOf() {
val expected = loadResource("tests/parser/xquery-update-1.0/ReplaceExpr_ValueOf.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/ReplaceExpr_ValueOf.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("value of; missing 'node' keyword")
fun testReplaceExpr_ValueOf_MissingNodeKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/ReplaceExpr_ValueOf_MissingNodeKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/ReplaceExpr_ValueOf_MissingNodeKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("value of; missing 'of' keyword")
fun testReplaceExpr_ValueOf_MissingOfKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/ReplaceExpr_ValueOf_MissingOfKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/ReplaceExpr_ValueOf_MissingOfKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (145) ReplaceExpr")
internal inner class RenameExpr {
@Test
@DisplayName("rename expression")
fun testRenameExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/RenameExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RenameExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing TargetExpr")
fun testRenameExpr_MissingTargetExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/RenameExpr_MissingTargetExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RenameExpr_MissingTargetExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing 'as' keyword")
fun testRenameExpr_MissingAsKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/RenameExpr_MissingAsKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RenameExpr_MissingAsKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing NewNameExpr")
fun testRenameExpr_MissingNewNameExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/RenameExpr_MissingNewNameExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/RenameExpr_MissingNewNameExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 1.0 EBNF (150) TransformExpr ; XQuery Update Facility 3.0 EBNF (208) CopyModifyExpr")
internal inner class TransformExpr {
@Test
@DisplayName("copy modify expression")
fun testTransformExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("copy modify expression; compact whitespace")
fun testTransformExpr_CompactWhitespace() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_CompactWhitespace.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("copy modify expression; recover using '=' instead of ':='")
fun testTransformExpr_Equal() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_Equal.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_Equal.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing VarName")
fun testTransformExpr_MissingVarName() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MissingVarName.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MissingVarName.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing ':='")
fun testTransformExpr_MissingVarAssignOperator() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MissingVarAssignOperator.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MissingVarAssignOperator.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing variable assignment Expr")
fun testTransformExpr_MissingVarAssignExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MissingVarAssignExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MissingVarAssignExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing 'modify' keyword")
fun testTransformExpr_MissingModifyKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MissingModifyKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MissingModifyKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing modify Expr")
fun testTransformExpr_MissingModifyExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MissingModifyExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MissingModifyExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing 'return' keyword")
fun testTransformExpr_MissingReturnKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MissingReturnKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MissingReturnKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing return Expr")
fun testTransformExpr_MissingReturnExpr() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MissingReturnExpr.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MissingReturnExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("multiple VarName")
fun testTransformExpr_MultipleVarName() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MultipleVarName.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MultipleVarName.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("multiple VarName; compact whitespace")
fun testTransformExpr_MultipleVarName_CompactWhitespace() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MultipleVarName_CompactWhitespace.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MultipleVarName_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("multiple VarName; missing '$' variable indicator")
fun testTransformExpr_MultipleVarName_MissingVarIndicator() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_MultipleVarName_MissingVarIndicator.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_MultipleVarName_MissingVarIndicator.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("VarName as XQuery 3.0 EQName")
fun testTransformExpr_EQName() {
val expected = loadResource("tests/parser/xquery-update-1.0/TransformExpr_EQName.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/TransformExpr_EQName.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 3.0 EBNF (27) CompatibilityAnnotation")
internal inner class CompatibilityAnnotation {
@Test
@DisplayName("function declaration")
fun testCompatibilityAnnotation_FunctionDecl() {
val expected = loadResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("function declaration; missing 'function' keyword")
fun testCompatibilityAnnotation_FunctionDecl_MissingFunctionKeyword() {
val expected = loadResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating_MissingFunctionKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-1.0/FunctionDecl_Updating_MissingFunctionKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("variable declaration")
fun testCompatibilityAnnotation_VarDecl() {
val expected = loadResource("tests/parser/xquery-update-3.0/CompatibilityAnnotation_VarDecl.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/CompatibilityAnnotation_VarDecl.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("variable declaration; missing 'variable' keyword")
fun testCompatibilityAnnotation_VarDecl_MissingVariableKeyword() {
val expected = loadResource("tests/parser/xquery-update-3.0/CompatibilityAnnotation_VarDecl_MissingVariableKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/CompatibilityAnnotation_VarDecl_MissingVariableKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 3.0 EBNF (97) TransformWithExpr")
internal inner class TransformWithExpr30 {
@Test
@DisplayName("transform with expression")
fun testTransformWithExpr() {
val expected = loadResource("tests/parser/xquery-update-3.0/TransformWithExpr.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/TransformWithExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("transform with expression; compact whitespace")
fun testTransformWithExpr_CompactWhitespace() {
val expected = loadResource("tests/parser/xquery-update-3.0/TransformWithExpr_CompactWhitespace.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/TransformWithExpr_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing 'with' keyword")
fun testTransformWithExpr_MissingWithKeyword() {
val expected = loadResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingWithKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingWithKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing opening brace")
fun testTransformWithExpr_MissingOpeningBrace() {
val expected = loadResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingOpeningBrace.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingOpeningBrace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing Expr")
fun testTransformWithExpr_MissingExpr() {
val expected = loadResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingExpr.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing closing brace")
fun testTransformWithExpr_MissingClosingBrace() {
val expected = loadResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingClosingBrace.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/TransformWithExpr_MissingClosingBrace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 3.0 EBNF (207) UpdatingFunctionCall")
internal inner class UpdatingFunctionCall {
@Test
@DisplayName("updating function call")
fun testUpdatingFunctionCall() {
val expected = loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("updating function call; compact whitespace")
fun testUpdatingFunctionCall_CompactWhitespace() {
val expected = loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_CompactWhitespace.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing 'updating' keyword")
fun testUpdatingFunctionCall_MissingUpdatingKeyword() {
val expected =
loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingUpdatingKeyword.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingUpdatingKeyword.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing opening parenthesis")
fun testUpdatingFunctionCall_MissingOpeningParenthesis() {
val expected =
loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingOpeningParenthesis.txt")
val actual =
parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingOpeningParenthesis.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing PrimaryExpr")
fun testUpdatingFunctionCall_MissingPrimaryExpr() {
val expected = loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingPrimaryExpr.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingPrimaryExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("missing closing parenthesis")
fun testUpdatingFunctionCall_MissingClosingParenthesis() {
val expected =
loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingClosingParenthesis.txt")
val actual =
parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_MissingClosingParenthesis.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("arguments: single")
fun testUpdatingFunctionCall_Arguments_Single() {
val expected = loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_Arguments_Single.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_Arguments_Single.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("arguments: multiple")
fun testUpdatingFunctionCall_Arguments_Multiple() {
val expected = loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_Arguments_Multiple.txt")
val actual = parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_Arguments_Multiple.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
@Test
@DisplayName("arguments: multiple; compact whitespace")
fun testUpdatingFunctionCall_Arguments_Multiple_CompactWhitespace() {
val expected =
loadResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_Arguments_Multiple_CompactWhitespace.txt")
val actual =
parseResource("tests/parser/xquery-update-3.0/UpdatingFunctionCall_Arguments_Multiple_CompactWhitespace.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
@Nested
@DisplayName("XQuery Update Facility 3.1 EBNF (97) TransformWithExpr")
internal inner class TransformWithExpr31 {
@Test
@DisplayName("arrow expression")
fun testTransformWithExpr_ArrowExpr() {
val expected = loadResource("tests/parser/xquery-update-3.1/TransformWithExpr_ArrowExpr.txt")
val actual = parseResource("tests/parser/xquery-update-3.1/TransformWithExpr_ArrowExpr.xq")
assertThat(actual.toPsiTreeString(), `is`(expected))
}
}
}
| apache-2.0 | 2bd29cc6bf0d7081d932861066a4139e | 48.290936 | 132 | 0.67507 | 4.88694 | false | true | false | false |
andrewoma/kwery | fetcher/src/test/kotlin/com/github/andrewoma/kwery/fetcher/readme/Readme.kt | 1 | 3377 | /*
* Copyright (c) 2015 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.andrewoma.kwery.fetcher.readme
import com.github.andrewoma.kwery.fetcher.*
// Given the following domain model
data class Actor(val id: Int, val firstName: String, val lastName: String)
data class Language(val id: Int, val name: String)
data class Film(val id: Int, val language: Language, val actors: Set<Actor>,
val title: String, val releaseYear: Int)
@Suppress("UNUSED_PARAMETER")
class Dao<ID, T> {
fun findByIds(id: Collection<ID>): Map<ID, T> = mapOf()
fun findByFilmIds(id: Collection<ID>): Map<ID, Collection<T>> = mapOf()
fun findFilmsReleasedAfter(year: Int): List<Film> = listOf()
}
fun readme() {
val languageDao = Dao<Int, Language>()
val filmDao = Dao<Int, Film>()
val actorDao = Dao<Int, Actor>()
// Define types with functions describing how to fetch a batch by ids
val language = Type(Language::id, { languageDao.findByIds(it) })
val actor = Type(Actor::id, { actorDao.findByIds(it) })
// For types that reference other types describe how to apply fetched values
val film = Type(Film::id, { filmDao.findByIds(it) }, listOf(
// 1 to 1
Property(Film::language, language, { it.language.id }, { f, l -> f.copy(language = l) }),
// 1 to many requires a function to describe how to fetch the related objects
CollectionProperty(Film::actors, actor, { it.id },
{ f, a -> f.copy(actors = a.toSet()) },
{ actorDao.findByFilmIds(it) })
))
val fetcher = GraphFetcher(setOf(language, actor, film))
// Extension function to fetch the graph for any List using fetcher defined above
fun <T> List<T>.fetch(vararg nodes: Node) = fetcher.fetch(this, Node.create("", nodes.toSet()))
// We can now efficiently fetch various graphs for any list of films
// The following fetches the films with actors and languages in 3 queries
val filmsWithAll = filmDao.findFilmsReleasedAfter(2010).fetch(Node.all)
// The graph specification can also be built using properties
val filmsWithActors = filmDao.findFilmsReleasedAfter(2010).fetch(Film::actors.node())
println("$filmsWithAll $filmsWithActors")
}
fun main(args: Array<String>) {
readme()
} | mit | 124c7acaceb611733cb8dd0c116fcf25 | 41.759494 | 101 | 0.699733 | 4.128362 | false | false | false | false |
exponentjs/exponent | packages/expo-camera/android/src/main/java/expo/modules/camera/tasks/ResolveTakenPictureAsyncTask.kt | 2 | 8264 | package expo.modules.camera.tasks
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.net.Uri
import android.os.AsyncTask
import android.os.Bundle
import android.util.Base64
import androidx.exifinterface.media.ExifInterface
import expo.modules.camera.CameraViewHelper.getExifData
import expo.modules.camera.CameraViewHelper.addExifData
import expo.modules.camera.utils.FileSystemUtils
import expo.modules.core.Promise
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.lang.Exception
private const val DIRECTORY_NOT_FOUND_MSG = "Documents directory of the app could not be found."
private const val UNKNOWN_IO_EXCEPTION_MSG = "An unknown I/O exception has occurred."
private const val UNKNOWN_EXCEPTION_MSG = "An unknown exception has occurred."
private const val ERROR_TAG = "E_TAKING_PICTURE_FAILED"
private const val DIRECTORY_NAME = "Camera"
private const val EXTENSION = ".jpg"
private const val SKIP_PROCESSING_KEY = "skipProcessing"
private const val FAST_MODE_KEY = "fastMode"
private const val QUALITY_KEY = "quality"
private const val BASE64_KEY = "base64"
private const val HEIGHT_KEY = "height"
private const val WIDTH_KEY = "width"
private const val EXIF_KEY = "exif"
private const val DATA_KEY = "data"
private const val URI_KEY = "uri"
private const val ID_KEY = "id"
private const val DEFAULT_QUALITY = 1
class ResolveTakenPictureAsyncTask(
private var promise: Promise,
private var options: Map<String, Any>,
private val directory: File,
private var pictureSavedDelegate: PictureSavedDelegate
) : AsyncTask<Void?, Void?, Bundle?>() {
private var imageData: ByteArray? = null
private var bitmap: Bitmap? = null
constructor(imageData: ByteArray?, promise: Promise, options: Map<String, Any>, directory: File, delegate: PictureSavedDelegate) : this(
promise, options, directory, delegate
) {
this.imageData = imageData
}
constructor(bitmap: Bitmap?, promise: Promise, options: Map<String, Any>, directory: File, delegate: PictureSavedDelegate) : this(
promise, options, directory, delegate
) {
this.bitmap = bitmap
}
private val quality: Int
get() = options[QUALITY_KEY]?.let {
val requestedQuality = (it as Number).toDouble()
(requestedQuality * 100).toInt()
} ?: DEFAULT_QUALITY * 100
override fun doInBackground(vararg params: Void?): Bundle? {
// handle SkipProcessing
if (imageData != null && isOptionEnabled(SKIP_PROCESSING_KEY)) {
return handleSkipProcessing()
}
if (bitmap == null) {
bitmap = imageData?.let { BitmapFactory.decodeByteArray(imageData, 0, it.size) }
}
try {
ByteArrayInputStream(imageData).use { inputStream ->
val response = Bundle()
val exifInterface = ExifInterface(inputStream)
// Get orientation of the image from mImageData via inputStream
val orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED
)
// Rotate the bitmap to the proper orientation if needed
if (orientation != ExifInterface.ORIENTATION_UNDEFINED) {
bitmap = bitmap?.let {
rotateBitmap(it, getImageRotation(orientation))
}
}
// Write Exif data to the response if requested
if (isOptionEnabled(EXIF_KEY)) {
val exifData = getExifData(exifInterface)
response.putBundle(EXIF_KEY, exifData)
}
// Upon rotating, write the image's dimensions to the response
response.apply {
putInt(WIDTH_KEY, bitmap!!.width)
putInt(HEIGHT_KEY, bitmap!!.height)
}
// Cache compressed image in imageStream
ByteArrayOutputStream().use { imageStream ->
bitmap!!.compress(Bitmap.CompressFormat.JPEG, quality, imageStream)
// Write compressed image to file in cache directory
val filePath = writeStreamToFile(imageStream)
// Save Exif data to the image if requested
if (isOptionEnabled(EXIF_KEY)) {
val exifFromFile = ExifInterface(filePath!!)
addExifData(exifFromFile, exifInterface)
}
val imageFile = File(filePath)
val fileUri = Uri.fromFile(imageFile).toString()
response.putString(URI_KEY, fileUri)
// Write base64-encoded image to the response if requested
if (isOptionEnabled(BASE64_KEY)) {
response.putString(BASE64_KEY, Base64.encodeToString(imageStream.toByteArray(), Base64.NO_WRAP))
}
}
return response
}
} catch (e: Exception) {
when (e) {
is Resources.NotFoundException -> promise.reject(ERROR_TAG, DIRECTORY_NOT_FOUND_MSG, e)
is IOException -> promise.reject(ERROR_TAG, UNKNOWN_IO_EXCEPTION_MSG, e)
else -> promise.reject(ERROR_TAG, UNKNOWN_EXCEPTION_MSG, e)
}
e.printStackTrace()
}
// An exception had to occur, promise has already been rejected. Do not try to resolve it again.
return null
}
private fun handleSkipProcessing(): Bundle? {
try {
// save byte array (it's already a JPEG)
ByteArrayOutputStream().use { imageStream ->
imageStream.write(imageData)
// write compressed image to file in cache directory
val filePath = writeStreamToFile(imageStream)
val imageFile = File(filePath)
// handle image uri
val fileUri = Uri.fromFile(imageFile).toString()
// read exif information
val exifInterface = ExifInterface(filePath!!)
return Bundle().apply {
putString(URI_KEY, fileUri)
putInt(WIDTH_KEY, exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, -1))
putInt(HEIGHT_KEY, exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, -1))
// handle exif request
if (isOptionEnabled(EXIF_KEY)) {
val exifData = getExifData(exifInterface)
putBundle(EXIF_KEY, exifData)
}
// handle base64
if (isOptionEnabled(BASE64_KEY)) {
putString(BASE64_KEY, Base64.encodeToString(imageData, Base64.NO_WRAP))
}
}
}
} catch (e: Exception) {
if (e is IOException) {
promise.reject(ERROR_TAG, UNKNOWN_IO_EXCEPTION_MSG, e)
} else {
promise.reject(ERROR_TAG, UNKNOWN_EXCEPTION_MSG, e)
}
e.printStackTrace()
}
// error occurred
return null
}
override fun onPostExecute(response: Bundle?) {
super.onPostExecute(response)
// If the response is not null everything went well and we can resolve the promise.
if (response != null) {
if (isOptionEnabled(FAST_MODE_KEY)) {
val wrapper = Bundle()
wrapper.putInt(ID_KEY, (options[ID_KEY] as Double).toInt())
wrapper.putBundle(DATA_KEY, response)
pictureSavedDelegate.onPictureSaved(wrapper)
} else {
promise.resolve(response)
}
}
}
// Write stream to file in cache directory
@Throws(Exception::class)
private fun writeStreamToFile(inputStream: ByteArrayOutputStream): String? {
try {
val outputPath = FileSystemUtils.generateOutputPath(directory, DIRECTORY_NAME, EXTENSION)
FileOutputStream(outputPath).use { outputStream ->
inputStream.writeTo(outputStream)
}
return outputPath
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
private fun rotateBitmap(source: Bitmap, angle: Int): Bitmap {
val matrix = Matrix()
matrix.postRotate(angle.toFloat())
return Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true)
}
// Get rotation degrees from Exif orientation enum
private fun getImageRotation(orientation: Int) = when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> 90
ExifInterface.ORIENTATION_ROTATE_180 -> 180
ExifInterface.ORIENTATION_ROTATE_270 -> 270
else -> 0
}
private fun isOptionEnabled(key: String) = options[key] != null && (options[key] as Boolean)
}
| bsd-3-clause | 80a9d51d8e7917eaed81ad1bb791d948 | 34.774892 | 138 | 0.679816 | 4.481562 | false | false | false | false |
pambrose/prometheus-proxy | src/main/kotlin/io/prometheus/agent/AgentGrpcService.kt | 1 | 12150 | /*
* 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.agent
import brave.grpc.GrpcTracing
import com.github.pambrose.common.delegate.AtomicDelegates.atomicBoolean
import com.github.pambrose.common.dsl.GrpcDsl.channel
import com.github.pambrose.common.util.simpleClassName
import com.github.pambrose.common.utils.TlsContext
import com.github.pambrose.common.utils.TlsContext.Companion.PLAINTEXT_CONTEXT
import com.github.pambrose.common.utils.TlsUtils.buildClientTlsContext
import com.google.protobuf.Empty
import io.grpc.ClientInterceptors
import io.grpc.ManagedChannel
import io.grpc.Status
import io.grpc.StatusRuntimeException
import io.prometheus.Agent
import io.prometheus.common.BaseOptions.Companion.HTTPS_PREFIX
import io.prometheus.common.BaseOptions.Companion.HTTP_PREFIX
import io.prometheus.common.GrpcObjects
import io.prometheus.common.GrpcObjects.newAgentInfo
import io.prometheus.common.GrpcObjects.newRegisterAgentRequest
import io.prometheus.common.GrpcObjects.newScrapeResponseChunk
import io.prometheus.common.GrpcObjects.newScrapeResponseSummary
import io.prometheus.common.GrpcObjects.toScrapeResponse
import io.prometheus.common.GrpcObjects.toScrapeResponseHeader
import io.prometheus.common.ScrapeResults
import io.prometheus.grpc.ChunkedScrapeResponse
import io.prometheus.grpc.ProxyServiceGrpcKt
import io.prometheus.grpc.ScrapeRequest
import io.prometheus.grpc.ScrapeResponse
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import mu.KLogging
import java.io.ByteArrayInputStream
import java.util.concurrent.CountDownLatch
import java.util.zip.CRC32
import kotlin.properties.Delegates.notNull
internal class AgentGrpcService(
internal val agent: Agent,
private val options: AgentOptions,
private val inProcessServerName: String
) {
private var grpcStarted by atomicBoolean(false)
private var stub: ProxyServiceGrpcKt.ProxyServiceCoroutineStub by notNull()
private val tracing by lazy { agent.zipkinReporterService.newTracing("grpc_client") }
private val grpcTracing by lazy { GrpcTracing.create(tracing) }
var channel: ManagedChannel by notNull()
val hostName: String
val port: Int
private val tlsContext: TlsContext
init {
val schemeStripped =
options.proxyHostname
.run {
when {
startsWith(HTTP_PREFIX) -> removePrefix(HTTP_PREFIX)
startsWith(HTTPS_PREFIX) -> removePrefix(HTTPS_PREFIX)
else -> this
}
}
if (":" in schemeStripped) {
val vals = schemeStripped.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
hostName = vals[0]
port = Integer.valueOf(vals[1])
} else {
hostName = schemeStripped
port = 50051
}
tlsContext =
agent.options.run {
if (certChainFilePath.isNotEmpty() ||
privateKeyFilePath.isNotEmpty() ||
trustCertCollectionFilePath.isNotEmpty()
)
buildClientTlsContext(
certChainFilePath = certChainFilePath,
privateKeyFilePath = privateKeyFilePath,
trustCertCollectionFilePath = trustCertCollectionFilePath
)
else
PLAINTEXT_CONTEXT
}
resetGrpcStubs()
}
@Synchronized
fun shutDown() {
if (agent.isZipkinEnabled)
tracing.close()
if (grpcStarted)
channel.shutdownNow()
}
@Synchronized
fun resetGrpcStubs() {
logger.info { "Creating gRPC stubs" }
if (grpcStarted)
shutDown()
else
grpcStarted = true
channel =
channel(
hostName = hostName,
port = port,
enableRetry = true,
tlsContext = tlsContext,
overrideAuthority = agent.options.overrideAuthority,
inProcessServerName = inProcessServerName
) {
if (agent.isZipkinEnabled)
intercept(grpcTracing.newClientInterceptor())
}
val interceptors = listOf(AgentClientInterceptor(agent))
stub = ProxyServiceGrpcKt.ProxyServiceCoroutineStub(ClientInterceptors.intercept(channel, interceptors))
}
// If successful, this will create an agentContext on the Proxy and an interceptor will add an agent_id to the headers`
suspend fun connectAgent() =
try {
logger.info { "Connecting to proxy at ${agent.proxyHost} using ${tlsContext.desc()}..." }
stub.connectAgent(Empty.getDefaultInstance())
logger.info { "Connected to proxy at ${agent.proxyHost} using ${tlsContext.desc()}" }
agent.metrics { connectCount.labels(agent.launchId, "success").inc() }
true
} catch (e: StatusRuntimeException) {
agent.metrics { connectCount.labels(agent.launchId, "failure").inc() }
logger.info { "Cannot connect to proxy at ${agent.proxyHost} using ${tlsContext.desc()} - ${e.simpleClassName}: ${e.message}" }
false
}
suspend fun registerAgent(initialConnectionLatch: CountDownLatch) {
val request =
newRegisterAgentRequest(agent.agentId, agent.launchId, agent.agentName, hostName, agent.options.consolidated)
stub.registerAgent(request)
.also { response ->
agent.markMsgSent()
if (!response.valid)
throw RequestFailureException("registerAgent() - ${response.reason}")
}
initialConnectionLatch.countDown()
}
fun pathMapSize() =
runBlocking {
stub.pathMapSize(GrpcObjects.newPathMapSizeRequest(agent.agentId))
.run {
agent.markMsgSent()
pathCount
}
}
suspend fun registerPathOnProxy(path: String) =
stub.registerPath(GrpcObjects.newRegisterPathRequest(agent.agentId, path))
.apply {
agent.markMsgSent()
if (!valid)
throw RequestFailureException("registerPathOnProxy() - $reason")
}
suspend fun unregisterPathOnProxy(path: String) =
stub.unregisterPath(GrpcObjects.newUnregisterPathRequest(agent.agentId, path))
.apply {
agent.markMsgSent()
if (!valid)
throw RequestFailureException("unregisterPathOnProxy() - $reason")
}
suspend fun sendHeartBeat() {
agent.agentId
.also { agentId ->
if (agentId.isNotEmpty())
try {
stub.sendHeartBeat(GrpcObjects.newHeartBeatRequest(agentId))
.apply {
agent.markMsgSent()
if (!valid) {
logger.error { "AgentId $agentId not found on proxy" }
throw StatusRuntimeException(Status.NOT_FOUND)
}
}
} catch (e: StatusRuntimeException) {
logger.error { "sendHeartBeat() failed ${e.status}" }
}
}
}
suspend fun readRequestsFromProxy(agentHttpService: AgentHttpService, connectionContext: AgentConnectionContext) {
connectionContext
.use {
val agentInfo = newAgentInfo(agent.agentId)
stub.readRequestsFromProxy(agentInfo)
.collect { request: ScrapeRequest ->
// The actual fetch happens at the other end of the channel, not here.
logger.debug { "readRequestsFromProxy():\n$request" }
connectionContext.scrapeRequestsChannel.send { agentHttpService.fetchScrapeUrl(request) }
agent.scrapeRequestBacklogSize.incrementAndGet()
}
}
}
private suspend fun processScrapeResults(
agent: Agent,
scrapeResultsChannel: Channel<ScrapeResults>,
nonChunkedChannel: Channel<ScrapeResponse>,
chunkedChannel: Channel<ChunkedScrapeResponse>
) =
try {
for (scrapeResults: ScrapeResults in scrapeResultsChannel) {
val scrapeId = scrapeResults.scrapeId
if (!scrapeResults.zipped) {
logger.debug { "Writing non-chunked msg scrapeId: $scrapeId length: ${scrapeResults.contentAsText.length}" }
nonChunkedChannel.send(scrapeResults.toScrapeResponse())
agent.metrics { scrapeResultCount.labels(agent.launchId, "non-gzipped").inc() }
} else {
val zipped = scrapeResults.contentAsZipped
val chunkContentSize = options.chunkContentSizeKbs
logger.debug { "Comparing ${zipped.size} and $chunkContentSize" }
if (zipped.size < chunkContentSize) {
logger.debug { "Writing zipped non-chunked msg scrapeId: $scrapeId length: ${zipped.size}" }
nonChunkedChannel.send(scrapeResults.toScrapeResponse())
agent.metrics { scrapeResultCount.labels(agent.launchId, "gzipped").inc() }
} else {
scrapeResults.toScrapeResponseHeader()
.also {
logger.debug { "Writing header length: ${zipped.size} for scrapeId: $scrapeId " }
chunkedChannel.send(it)
}
var totalByteCount = 0
var totalChunkCount = 0
val checksum = CRC32()
val bais = ByteArrayInputStream(zipped)
val buffer = ByteArray(chunkContentSize)
var readByteCount: Int
while (bais.read(buffer).also { bytesRead -> readByteCount = bytesRead } > 0) {
totalChunkCount++
totalByteCount += readByteCount
checksum.update(buffer, 0, buffer.size)
newScrapeResponseChunk(scrapeId, totalChunkCount, readByteCount, checksum, buffer)
.also {
logger.debug { "Writing chunk $totalChunkCount for scrapeId: $scrapeId" }
chunkedChannel.send(it)
}
}
newScrapeResponseSummary(scrapeId, totalChunkCount, totalByteCount, checksum)
.also {
logger.debug { "Writing summary totalChunkCount: $totalChunkCount for scrapeID: $scrapeId" }
chunkedChannel.send(it)
agent.metrics { scrapeResultCount.labels(agent.launchId, "chunked").inc() }
}
}
}
agent.markMsgSent()
agent.scrapeRequestBacklogSize.decrementAndGet()
}
} finally {
nonChunkedChannel.close()
chunkedChannel.close()
}
suspend fun writeResponsesToProxyUntilDisconnected(agent: Agent, connectionContext: AgentConnectionContext) {
fun exceptionHandler() =
CoroutineExceptionHandler { _, e ->
if (agent.isRunning)
Status.fromThrowable(e)
.apply {
logger.error { "Error in writeResponsesToProxyUntilDisconnected(): $code $description" }
}
}
coroutineScope {
val nonChunkedChannel = Channel<ScrapeResponse>(Channel.UNLIMITED)
val chunkedChannel = Channel<ChunkedScrapeResponse>(Channel.UNLIMITED)
launch(Dispatchers.Default + exceptionHandler()) {
processScrapeResults(agent, connectionContext.scrapeResultsChannel, nonChunkedChannel, chunkedChannel)
}
connectionContext
.use {
coroutineScope {
launch(Dispatchers.Default + exceptionHandler()) {
stub.writeResponsesToProxy(nonChunkedChannel.consumeAsFlow())
}
launch(Dispatchers.Default + exceptionHandler()) {
stub.writeChunkedResponsesToProxy(chunkedChannel.consumeAsFlow())
}
}
logger.info { "Disconnected from proxy at ${agent.proxyHost}" }
}
}
}
companion object : KLogging()
} | apache-2.0 | 6a8f98ed84ea10561751284b8319ca61 | 35.053412 | 133 | 0.679233 | 4.842168 | false | false | false | false |
KeenenCharles/AndroidUnplash | androidunsplash/src/main/java/com/keenencharles/unsplash/models/Links.kt | 1 | 499 | package com.keenencharles.unsplash.models
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
@Parcelize
data class Links(
var self: String? = null,
var html: String? = null,
var photos: String? = null,
var likes: String? = null,
var portfolio: String? = null,
var download: String? = null,
@SerializedName("download_location") var downloadLocation: String? = null
) : Parcelable | mit | ab8f5f35456119699651a3de8a07e353 | 30.25 | 81 | 0.687375 | 4.264957 | false | false | false | false |
laminr/aeroknow | app/src/main/java/biz/eventually/atpl/utils/PrefUtils.kt | 1 | 3048 | package biz.eventually.atpl.utils
/**
* Created by Thibault de Lambilly on 19/06/2017.
*/
import android.content.Context
import android.preference.PreferenceManager
import biz.eventually.atpl.AtplApplication
import biz.eventually.atpl.R
object Prefields {
val PREF_TIMER_NBR: String = AtplApplication.get().getString(R.string.pref_timer_nbr)
val PREF_TIMER_ENABLE : String = AtplApplication.get().getString(R.string.pref_timer_enable)
val PREF_TOKEN : String = AtplApplication.get().getString(R.string.pref_token)
val PREF_LAST_DATA : String = AtplApplication.get().getString(R.string.pref_last_data)
}
fun prefsGetString(context: Context, key: String, defValue: String? = null) : String? {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
return pref.getString(key, defValue)
}
fun prefsPutString(context: Context, key: String, value: String) {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.putString(key, value)
editor.apply()
}
fun prefsPutInt(context: Context, key: String, value: Int) {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.putInt(key, value)
editor.apply()
}
inline fun <reified T> prefsGetValue(key: String, defValue: T): T {
val pref = PreferenceManager.getDefaultSharedPreferences(AtplApplication.get())
return when(T::class) {
Int::class -> pref.getInt(key, defValue as Int) as T
String::class -> pref.getString(key, defValue as String) as T
Boolean::class -> pref.getBoolean(key, defValue as Boolean) as T
Long::class -> pref.getLong(key, defValue as Long) as T
else -> defValue
}
}
fun prefsPutBool(context: Context, key: String, defValue: Boolean): Boolean {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
return pref.getBoolean(key, defValue)
}
fun getInt(context: Context, key: String, defValue: Int): Int {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
return pref.getInt(key, defValue)
}
fun putInt(context: Context, key: String, value: Int) {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.putInt(key, value)
editor.apply()
}
fun getLong(context: Context, key: String, defValue: Long): Long {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
return pref.getLong(key, defValue)
}
fun putLong(context: Context, key: String, value: Long) {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.putLong(key, value)
editor.apply()
}
fun exists(context: Context, key: String): Boolean {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
return pref.contains(key)
}
fun remove(context: Context, key: String) {
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.remove(key)
editor.apply()
} | mit | 459bbb320b301ed2c7f0d0eba444dbce | 33.647727 | 96 | 0.728346 | 4.037086 | false | false | false | false |
k9mail/k-9 | app/core/src/main/java/com/fsck/k9/notification/NotificationIds.kt | 2 | 2761 | package com.fsck.k9.notification
import com.fsck.k9.Account
internal object NotificationIds {
const val PUSH_NOTIFICATION_ID = 1
private const val NUMBER_OF_GENERAL_NOTIFICATIONS = 1
private const val OFFSET_SEND_FAILED_NOTIFICATION = 0
private const val OFFSET_CERTIFICATE_ERROR_INCOMING = 1
private const val OFFSET_CERTIFICATE_ERROR_OUTGOING = 2
private const val OFFSET_AUTHENTICATION_ERROR_INCOMING = 3
private const val OFFSET_AUTHENTICATION_ERROR_OUTGOING = 4
private const val OFFSET_FETCHING_MAIL = 5
private const val OFFSET_NEW_MAIL_SUMMARY = 6
private const val OFFSET_NEW_MAIL_SINGLE = 7
private const val NUMBER_OF_MISC_ACCOUNT_NOTIFICATIONS = 7
private const val NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS = MAX_NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS
private const val NUMBER_OF_NOTIFICATIONS_PER_ACCOUNT =
NUMBER_OF_MISC_ACCOUNT_NOTIFICATIONS + NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS
fun getNewMailSummaryNotificationId(account: Account): Int {
return getBaseNotificationId(account) + OFFSET_NEW_MAIL_SUMMARY
}
fun getSingleMessageNotificationId(account: Account, index: Int): Int {
require(index in 0 until NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS) { "Invalid index: $index" }
return getBaseNotificationId(account) + OFFSET_NEW_MAIL_SINGLE + index
}
fun getAllMessageNotificationIds(account: Account): List<Int> {
val singleMessageNotificationIdRange = (0 until NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS).map { index ->
getBaseNotificationId(account) + OFFSET_NEW_MAIL_SINGLE + index
}
return singleMessageNotificationIdRange.toList() + getNewMailSummaryNotificationId(account)
}
fun getFetchingMailNotificationId(account: Account): Int {
return getBaseNotificationId(account) + OFFSET_FETCHING_MAIL
}
fun getSendFailedNotificationId(account: Account): Int {
return getBaseNotificationId(account) + OFFSET_SEND_FAILED_NOTIFICATION
}
fun getCertificateErrorNotificationId(account: Account, incoming: Boolean): Int {
val offset = if (incoming) OFFSET_CERTIFICATE_ERROR_INCOMING else OFFSET_CERTIFICATE_ERROR_OUTGOING
return getBaseNotificationId(account) + offset
}
fun getAuthenticationErrorNotificationId(account: Account, incoming: Boolean): Int {
val offset = if (incoming) OFFSET_AUTHENTICATION_ERROR_INCOMING else OFFSET_AUTHENTICATION_ERROR_OUTGOING
return getBaseNotificationId(account) + offset
}
private fun getBaseNotificationId(account: Account): Int {
return 1 /* skip notification ID 0 */ + NUMBER_OF_GENERAL_NOTIFICATIONS +
account.accountNumber * NUMBER_OF_NOTIFICATIONS_PER_ACCOUNT
}
}
| apache-2.0 | b660784a9c825d6de94e6ea5834154a3 | 42.140625 | 113 | 0.737052 | 4.703578 | false | false | false | false |
Maccimo/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/impl/impl.kt | 3 | 6811 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("TestOnlyProblems") // KTIJ-19938
package com.intellij.lang.documentation.impl
import com.intellij.lang.documentation.*
import com.intellij.model.Pointer
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.readAction
import com.intellij.openapi.progress.ProgressManager
import com.intellij.util.AsyncSupplier
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
internal fun DocumentationTarget.documentationRequest(): DocumentationRequest {
ApplicationManager.getApplication().assertReadAccessAllowed()
return DocumentationRequest(createPointer(), presentation)
}
@ApiStatus.Internal
fun CoroutineScope.computeDocumentationAsync(targetPointer: Pointer<out DocumentationTarget>): Deferred<DocumentationResultData?> {
return async(Dispatchers.Default) {
computeDocumentation(targetPointer)
}
}
internal suspend fun computeDocumentation(targetPointer: Pointer<out DocumentationTarget>): DocumentationResultData? {
return withContext(Dispatchers.Default) {
val documentationResult: DocumentationResult? = readAction {
targetPointer.dereference()?.computeDocumentation()
}
@Suppress("REDUNDANT_ELSE_IN_WHEN")
when (documentationResult) {
is DocumentationResultData -> documentationResult
is AsyncDocumentation -> documentationResult.supplier.invoke() as DocumentationResultData?
null -> null
else -> error("Unexpected result: $documentationResult") // this fixes Kotlin incremental compilation
}
}
}
@ApiStatus.Internal
suspend fun handleLink(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult {
return withContext(Dispatchers.Default) {
tryResolveLink(targetPointer, url)
?: tryContentUpdater(targetPointer, url)
?: InternalLinkResult.CannotResolve
}
}
private suspend fun tryResolveLink(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult? {
return when (val resolveResult = resolveLink(targetPointer::dereference, url)) {
InternalResolveLinkResult.InvalidTarget -> InternalLinkResult.InvalidTarget
InternalResolveLinkResult.CannotResolve -> null
is InternalResolveLinkResult.Value -> InternalLinkResult.Request(resolveResult.value)
}
}
internal sealed class InternalResolveLinkResult<out X> {
object InvalidTarget : InternalResolveLinkResult<Nothing>()
object CannotResolve : InternalResolveLinkResult<Nothing>()
class Value<X>(val value: X) : InternalResolveLinkResult<X>()
}
internal suspend fun resolveLink(
targetSupplier: () -> DocumentationTarget?,
url: String,
): InternalResolveLinkResult<DocumentationRequest> {
return resolveLink(targetSupplier, url, DocumentationTarget::documentationRequest)
}
/**
* @param ram read action mapper - a function which would be applied to resolved [DocumentationTarget] while holding the read action
*/
internal suspend fun <X> resolveLink(
targetSupplier: () -> DocumentationTarget?,
url: String,
ram: (DocumentationTarget) -> X,
): InternalResolveLinkResult<X> {
val readActionResult = readAction {
resolveLinkInReadAction(targetSupplier, url, ram)
}
return when (readActionResult) {
is ResolveLinkInReadActionResult.Sync -> readActionResult.syncResult
is ResolveLinkInReadActionResult.Async -> asyncTarget(readActionResult.supplier, ram)
}
}
private suspend fun <X> asyncTarget(
supplier: AsyncSupplier<LinkResolveResult.Async?>,
ram: (DocumentationTarget) -> X,
): InternalResolveLinkResult<X> {
val asyncLinkResolveResult: LinkResolveResult.Async? = supplier.invoke()
if (asyncLinkResolveResult == null) {
return InternalResolveLinkResult.CannotResolve
}
when (asyncLinkResolveResult) {
is AsyncResolvedTarget -> {
val pointer = asyncLinkResolveResult.pointer
return readAction {
val target: DocumentationTarget? = pointer.dereference()
if (target == null) {
InternalResolveLinkResult.InvalidTarget
}
else {
InternalResolveLinkResult.Value(ram(target))
}
}
}
else -> error("Unexpected result: $asyncLinkResolveResult")
}
}
private sealed class ResolveLinkInReadActionResult<out X> {
class Sync<X>(val syncResult: InternalResolveLinkResult<X>) : ResolveLinkInReadActionResult<X>()
class Async(val supplier: AsyncSupplier<LinkResolveResult.Async?>) : ResolveLinkInReadActionResult<Nothing>()
}
private fun <X> resolveLinkInReadAction(
targetSupplier: () -> DocumentationTarget?,
url: String,
m: (DocumentationTarget) -> X,
): ResolveLinkInReadActionResult<X> {
val documentationTarget = targetSupplier()
?: return ResolveLinkInReadActionResult.Sync(InternalResolveLinkResult.InvalidTarget)
@Suppress("REDUNDANT_ELSE_IN_WHEN")
return when (val linkResolveResult: LinkResolveResult? = resolveLink(documentationTarget, url)) {
null -> ResolveLinkInReadActionResult.Sync(InternalResolveLinkResult.CannotResolve)
is ResolvedTarget -> ResolveLinkInReadActionResult.Sync(InternalResolveLinkResult.Value(m(linkResolveResult.target)))
is AsyncLinkResolveResult -> ResolveLinkInReadActionResult.Async(linkResolveResult.supplier)
else -> error("Unexpected result: $linkResolveResult") // this fixes Kotlin incremental compilation
}
}
private fun resolveLink(target: DocumentationTarget, url: String): LinkResolveResult? {
for (handler in DocumentationLinkHandler.EP_NAME.extensionList) {
ProgressManager.checkCanceled()
return handler.resolveLink(target, url) ?: continue
}
return null
}
private suspend fun tryContentUpdater(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult? {
return readAction {
contentUpdaterInReadAction(targetPointer, url)
}
}
private fun contentUpdaterInReadAction(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult? {
val target = targetPointer.dereference()
?: return InternalLinkResult.InvalidTarget
val updater = contentUpdater(target, url)
?: return null
return InternalLinkResult.Updater(updater)
}
private fun contentUpdater(target: DocumentationTarget, url: String): ContentUpdater? {
for (handler in DocumentationLinkHandler.EP_NAME.extensionList) {
ProgressManager.checkCanceled()
return handler.contentUpdater(target, url) ?: continue
}
return null
}
@TestOnly
fun computeDocumentationBlocking(targetPointer: Pointer<out DocumentationTarget>): DocumentationResultData? {
return runBlocking {
withTimeout(1000 * 60) {
computeDocumentation(targetPointer)
}
}
}
| apache-2.0 | 8e689513ffba9da157bc8272f5ce8d75 | 38.369942 | 132 | 0.77184 | 5.288043 | false | false | false | false |
JohnnyShieh/Gank | app/src/main/kotlin/com/johnny/gank/adapter/PicturePagerAdapter.kt | 1 | 2830 | package com.johnny.gank.adapter
/*
* Copyright (C) 2016 Johnny Shieh 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.
*/
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.PagerAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.johnny.gank.R
import com.johnny.gank.model.ui.GankNormalItem
import kotlinx.android.synthetic.main.pager_item_picture.view.*
/**
* description
*
* @author Johnny Shieh ([email protected])
* @version 1.0
*/
class PicturePagerAdapter : PagerAdapter() {
companion object {
const val ADD_FRONT = -1L
const val ADD_END = 1L
const val ADD_NONE = 0L
}
private val items = mutableListOf<GankNormalItem>()
fun initList(list: List<GankNormalItem>) {
items.addAll(list)
}
fun appendList(page: Int, list: List<GankNormalItem>): Long {
if (0 == count) return ADD_NONE
if (page == items[0].page - 1) {
items.addAll(0, list)
return ADD_FRONT
} else if (page == items.last().page + 1) {
items.addAll(items.size, list)
return ADD_END
}
return ADD_NONE
}
fun getItem(position: Int): GankNormalItem? {
if (position !in 0 until count) return null
return items[position]
}
override fun getCount(): Int {
return items.size
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view === `object`
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val view = LayoutInflater.from(container.context).inflate(R.layout.pager_item_picture, container, false)
val item = items[position]
Glide.with(container.context)
.load(item.gank.url)
.apply(RequestOptions()
.dontAnimate()
.centerCrop()
).into(view.pic)
container.addView(view)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
if (`object` is View) container.removeView(`object`)
}
override fun getItemPosition(`object`: Any): Int {
return POSITION_NONE
}
}
| apache-2.0 | 4a68894b265db335f14ca880646dd694 | 29.430108 | 112 | 0.655124 | 4.167894 | false | false | false | false |
theScrabi/NewPipe | app/src/main/java/org/schabi/newpipe/local/subscription/SubscriptionViewModel.kt | 3 | 2372 | package org.schabi.newpipe.local.subscription
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.xwray.groupie.Group
import io.reactivex.rxjava3.schedulers.Schedulers
import org.schabi.newpipe.local.feed.FeedDatabaseManager
import org.schabi.newpipe.local.subscription.item.ChannelItem
import org.schabi.newpipe.local.subscription.item.FeedGroupCardItem
import org.schabi.newpipe.util.DEFAULT_THROTTLE_TIMEOUT
import java.util.concurrent.TimeUnit
class SubscriptionViewModel(application: Application) : AndroidViewModel(application) {
private var feedDatabaseManager: FeedDatabaseManager = FeedDatabaseManager(application)
private var subscriptionManager = SubscriptionManager(application)
private val mutableStateLiveData = MutableLiveData<SubscriptionState>()
private val mutableFeedGroupsLiveData = MutableLiveData<List<Group>>()
val stateLiveData: LiveData<SubscriptionState> = mutableStateLiveData
val feedGroupsLiveData: LiveData<List<Group>> = mutableFeedGroupsLiveData
private var feedGroupItemsDisposable = feedDatabaseManager.groups()
.throttleLatest(DEFAULT_THROTTLE_TIMEOUT, TimeUnit.MILLISECONDS)
.map { it.map(::FeedGroupCardItem) }
.subscribeOn(Schedulers.io())
.subscribe(
{ mutableFeedGroupsLiveData.postValue(it) },
{ mutableStateLiveData.postValue(SubscriptionState.ErrorState(it)) }
)
private var stateItemsDisposable = subscriptionManager.subscriptions()
.throttleLatest(DEFAULT_THROTTLE_TIMEOUT, TimeUnit.MILLISECONDS)
.map { it.map { entity -> ChannelItem(entity.toChannelInfoItem(), entity.uid, ChannelItem.ItemVersion.MINI) } }
.subscribeOn(Schedulers.io())
.subscribe(
{ mutableStateLiveData.postValue(SubscriptionState.LoadedState(it)) },
{ mutableStateLiveData.postValue(SubscriptionState.ErrorState(it)) }
)
override fun onCleared() {
super.onCleared()
stateItemsDisposable.dispose()
feedGroupItemsDisposable.dispose()
}
sealed class SubscriptionState {
data class LoadedState(val subscriptions: List<Group>) : SubscriptionState()
data class ErrorState(val error: Throwable? = null) : SubscriptionState()
}
}
| gpl-3.0 | 3d734e3dc36bbfaa8d75dba03737e818 | 44.615385 | 119 | 0.759275 | 5.079229 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/insights/usecases/ActionCardReminderUseCase.kt | 1 | 2781 | package org.wordpress.android.ui.stats.refresh.lists.sections.insights.usecases
import kotlinx.coroutines.CoroutineDispatcher
import org.wordpress.android.R.string
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.fluxc.store.StatsStore.InsightType
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.stats.refresh.NavigationTarget.SetBloggingReminders
import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase.StatelessUseCase
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ListItemActionCard
import org.wordpress.android.ui.stats.refresh.utils.ActionCardHandler
import org.wordpress.android.ui.utils.ListItemInteraction
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import javax.inject.Inject
import javax.inject.Named
class ActionCardReminderUseCase @Inject constructor(
@Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher,
@Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher,
private val actionCardHandler: ActionCardHandler,
private val analyticsTrackerWrapper: AnalyticsTrackerWrapper
) : StatelessUseCase<Boolean>(InsightType.ACTION_REMINDER, mainDispatcher, backgroundDispatcher, listOf()) {
override suspend fun loadCachedData() = true
override suspend fun fetchRemoteData(forced: Boolean): State<Boolean> = State.Data(true)
override fun buildLoadingItem(): List<BlockListItem> = listOf()
override fun buildUiModel(domainModel: Boolean): List<BlockListItem> {
return listOf(
ListItemActionCard(
titleResource = string.stats_action_card_blogging_reminders_title,
text = string.stats_action_card_blogging_reminders_message,
positiveButtonText = string.stats_action_card_blogging_reminders_button_label,
positiveAction = ListItemInteraction.create(this::onSetReminders),
negativeButtonText = string.stats_management_dismiss_insights_news_card,
negativeAction = ListItemInteraction.create(this::onDismiss)
)
)
}
private fun onSetReminders() {
analyticsTrackerWrapper.track(Stat.STATS_INSIGHTS_ACTION_BLOGGING_REMINDERS_CONFIRMED)
navigateTo(SetBloggingReminders)
actionCardHandler.dismiss(InsightType.ACTION_REMINDER)
}
private fun onDismiss() {
analyticsTrackerWrapper.track(Stat.STATS_INSIGHTS_ACTION_BLOGGING_REMINDERS_DISMISSED)
actionCardHandler.dismiss(InsightType.ACTION_REMINDER)
}
}
| gpl-2.0 | 9d84070eb3b2f26646cf6e63f9219630 | 50.5 | 108 | 0.763754 | 4.853403 | false | false | false | false |
ingokegel/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebServer.kt | 1 | 14591 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet")
package org.jetbrains.builtInWebServer
import com.github.benmanes.caffeine.cache.Caffeine
import com.google.common.net.InetAddresses
import com.intellij.ide.SpecialConfigFiles.USER_WEB_TOKEN
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationType
import com.intellij.notification.SingletonNotificationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.endsWithName
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.util.text.Strings
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.io.*
import com.intellij.util.io.DigestUtil.randomToken
import com.intellij.util.net.NetUtils
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.*
import io.netty.handler.codec.http.cookie.DefaultCookie
import io.netty.handler.codec.http.cookie.ServerCookieDecoder
import io.netty.handler.codec.http.cookie.ServerCookieEncoder
import org.jetbrains.ide.BuiltInServerBundle
import org.jetbrains.ide.BuiltInServerManagerImpl
import org.jetbrains.ide.HttpRequestHandler
import org.jetbrains.ide.orInSafeMode
import org.jetbrains.io.send
import java.awt.datatransfer.StringSelection
import java.io.IOException
import java.net.InetAddress
import java.net.URI
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFileAttributeView
import java.nio.file.attribute.PosixFilePermission
import java.util.*
import java.util.concurrent.TimeUnit
import javax.swing.SwingUtilities
internal val LOG = logger<BuiltInWebServer>()
private val notificationManager by lazy {
SingletonNotificationManager(BuiltInServerManagerImpl.NOTIFICATION_GROUP, NotificationType.INFORMATION)
}
private val WEB_SERVER_PATH_HANDLER_EP_NAME = ExtensionPointName.create<WebServerPathHandler>("org.jetbrains.webServerPathHandler")
class BuiltInWebServer : HttpRequestHandler() {
override fun isAccessible(request: HttpRequest): Boolean {
return BuiltInServerOptions.getInstance().builtInServerAvailableExternally ||
request.isLocalOrigin(onlyAnyOrLoopback = false, hostsOnly = true)
}
override fun isSupported(request: FullHttpRequest): Boolean = super.isSupported(request) || request.method() == HttpMethod.POST
override fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean {
var hostName = getHostName(request) ?: return false
val projectName: String?
val isIpv6 = hostName[0] == '[' && hostName.length > 2 && hostName[hostName.length - 1] == ']'
if (isIpv6) {
hostName = hostName.substring(1, hostName.length - 1)
}
if (isIpv6 || InetAddresses.isInetAddress(hostName) || isOwnHostName(hostName) || hostName.endsWith(".ngrok.io")) {
if (urlDecoder.path().length < 2) {
return false
}
projectName = null
}
else {
if (hostName.endsWith(".localhost")) {
projectName = hostName.substring(0, hostName.lastIndexOf('.'))
}
else {
projectName = hostName
}
}
return doProcess(urlDecoder, request, context, projectName)
}
}
internal fun isActivatable() = Registry.`is`("ide.built.in.web.server.activatable", false)
const val TOKEN_PARAM_NAME = "_ijt"
const val TOKEN_HEADER_NAME = "x-ijt"
private val STANDARD_COOKIE by lazy {
val productName = ApplicationNamesInfo.getInstance().lowercaseProductName
val configPath = PathManager.getConfigPath()
val file = Path.of(configPath, USER_WEB_TOKEN)
var token: String? = null
if (file.exists()) {
try {
token = UUID.fromString(file.readText()).toString()
}
catch (e: Exception) {
LOG.warn(e)
}
}
if (token == null) {
token = UUID.randomUUID().toString()
file.write(token!!)
Files.getFileAttributeView(file, PosixFileAttributeView::class.java)
?.setPermissions(EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE))
}
// explicit setting domain cookie on localhost doesn't work for chrome
// http://stackoverflow.com/questions/8134384/chrome-doesnt-create-cookie-for-domain-localhost-in-broken-https
val cookie = DefaultCookie(productName + "-" + Integer.toHexString(configPath.hashCode()), token!!)
cookie.isHttpOnly = true
cookie.setMaxAge(TimeUnit.DAYS.toSeconds(365 * 10))
cookie.setPath("/")
cookie
}
// expire after access because we reuse tokens
private val tokens = Caffeine.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build<String, Boolean>()
fun acquireToken(): String {
var token = tokens.asMap().keys.firstOrNull()
if (token == null) {
token = randomToken()
tokens.put(token, java.lang.Boolean.TRUE)
}
return token
}
private fun doProcess(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext, projectNameAsHost: String?): Boolean {
val decodedPath = urlDecoder.path()
var offset: Int
var isEmptyPath: Boolean
val isCustomHost = projectNameAsHost != null
var projectName: String
if (isCustomHost) {
projectName = projectNameAsHost!!
// host mapped to us
offset = 0
isEmptyPath = decodedPath.isEmpty()
}
else {
offset = decodedPath.indexOf('/', 1)
projectName = decodedPath.substring(1, if (offset == -1) decodedPath.length else offset)
isEmptyPath = offset == -1
}
val referer = request.headers().get(HttpHeaderNames.REFERER)
val projectNameFromReferer =
if (!isCustomHost && referer != null) {
try {
val uri = URI.create(referer)
val refererPath = uri.path
if (refererPath != null && refererPath.startsWith('/')) {
val secondSlashOffset = refererPath.indexOf('/', 1)
if (secondSlashOffset > 1) refererPath.substring(1, secondSlashOffset)
else null
}
else null
}
catch (t: Throwable) {
null
}
}
else null
var candidateByDirectoryName: Project? = null
var isCandidateFromReferer = false
val project = ProjectManager.getInstance().openProjects.firstOrNull(fun(project: Project): Boolean {
if (project.isDisposed) {
return false
}
val name = project.name
if (isCustomHost) {
// domain name is case-insensitive
if (projectName.equals(name, ignoreCase = true)) {
if (!SystemInfo.isFileSystemCaseSensitive) {
// may be passed path is not correct
projectName = name
}
return true
}
}
else {
// WEB-17839 Internal web server reports 404 when serving files from project with slashes in name
if (decodedPath.regionMatches(1, name, 0, name.length, !SystemInfo.isFileSystemCaseSensitive)) {
val isEmptyPathCandidate = decodedPath.length == (name.length + 1)
if (isEmptyPathCandidate || decodedPath[name.length + 1] == '/') {
projectName = name
offset = name.length + 1
isEmptyPath = isEmptyPathCandidate
return true
}
}
}
if (candidateByDirectoryName == null && compareNameAndProjectBasePath(projectName, project)) {
candidateByDirectoryName = project
}
if (candidateByDirectoryName == null &&
projectNameFromReferer != null &&
(projectNameFromReferer == name || compareNameAndProjectBasePath(projectNameFromReferer, project))) {
candidateByDirectoryName = project
isCandidateFromReferer = true
}
return false
}) ?: candidateByDirectoryName
if (isActivatable() && !PropertiesComponent.getInstance().getBoolean("ide.built.in.web.server.active")) {
notificationManager.notify("", BuiltInServerBundle.message("notification.content.built.in.web.server.is.deactivated"), project) { }
return false
}
if (isCandidateFromReferer) {
projectName = projectNameFromReferer!!
offset = 0
isEmptyPath = false
}
if (isEmptyPath) {
// we must redirect "jsdebug" to "jsdebug/" as nginx does, otherwise browser will treat it as a file instead of a directory, so, relative path will not work
redirectToDirectory(request, context.channel(), projectName, null)
return true
}
val path = toIdeaPath(decodedPath, offset)
if (path == null) {
HttpResponseStatus.BAD_REQUEST.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(context.channel(), request)
return true
}
for (pathHandler in WEB_SERVER_PATH_HANDLER_EP_NAME.extensionList) {
LOG.runAndLogException {
if (pathHandler.process(path, project, request, context, projectName, decodedPath, isCustomHost)) {
return true
}
}
}
return false
}
fun HttpRequest.isSignedRequest(): Boolean {
if (BuiltInServerOptions.getInstance().allowUnsignedRequests) {
return true
}
// we must check referrer - if html cached, browser will send request without query
val token = headers().get(TOKEN_HEADER_NAME)
?: QueryStringDecoder(uri()).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull()
?: referrer?.let { QueryStringDecoder(it).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull() }
// we don't invalidate token - allow making subsequent requests using it (it is required for our javadoc DocumentationComponent)
return token != null && tokens.getIfPresent(token) != null
}
private const val FAVICON_PATH = "favicon.ico"
fun validateToken(request: HttpRequest, channel: Channel, isSignedRequest: Boolean): HttpHeaders? {
if (BuiltInServerOptions.getInstance().allowUnsignedRequests) {
return EmptyHttpHeaders.INSTANCE
}
request.headers().get(HttpHeaderNames.COOKIE)?.let {
for (cookie in ServerCookieDecoder.STRICT.decode(it)) {
if (cookie.name() == STANDARD_COOKIE.name()) {
if (cookie.value() == STANDARD_COOKIE.value()) {
return EmptyHttpHeaders.INSTANCE
}
break
}
}
}
if (isSignedRequest) {
return DefaultHttpHeaders().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(STANDARD_COOKIE) + "; SameSite=strict")
}
val urlDecoder = QueryStringDecoder(request.uri())
if (!urlDecoder.path().endsWith("/$FAVICON_PATH") && !urlDecoder.path().endsWith("/$FAVICON_PATH/")) {
val url = "${channel.uriScheme}://${request.host!!}${urlDecoder.path()}"
SwingUtilities.invokeAndWait {
ProjectUtil.focusProjectWindow(null, true)
if (MessageDialogBuilder
// escape - see https://youtrack.jetbrains.com/issue/IDEA-287428
.yesNo("", Strings.escapeXmlEntities(BuiltInServerBundle.message("dialog.message.page", StringUtil.trimMiddle(url, 50))))
.icon(Messages.getWarningIcon())
.yesText(BuiltInServerBundle.message("dialog.button.copy.authorization.url.to.clipboard"))
.guessWindowAndAsk()) {
CopyPasteManager.getInstance().setContents(StringSelection(url + "?" + TOKEN_PARAM_NAME + "=" + acquireToken()))
}
}
}
HttpResponseStatus.UNAUTHORIZED.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request)
return null
}
private fun toIdeaPath(decodedPath: String, offset: Int): String? {
// must be absolute path (relative to DOCUMENT_ROOT, i.e. scheme://authority/) to properly canonicalize
val path = decodedPath.substring(offset)
if (!path.startsWith('/')) {
return null
}
return FileUtil.toCanonicalPath(path, '/').substring(1)
}
fun compareNameAndProjectBasePath(projectName: String, project: Project): Boolean {
val basePath = project.basePath
return basePath != null && endsWithName(basePath, projectName)
}
fun findIndexFile(basedir: VirtualFile): VirtualFile? {
val children = basedir.children
if (children.isNullOrEmpty()) {
return null
}
for (indexNamePrefix in arrayOf("index.", "default.")) {
var index: VirtualFile? = null
val preferredName = indexNamePrefix + "html"
for (child in children) {
if (!child.isDirectory) {
val name = child.name
//noinspection IfStatementWithIdenticalBranches
if (name == preferredName) {
return child
}
else if (index == null && name.startsWith(indexNamePrefix)) {
index = child
}
}
}
if (index != null) {
return index
}
}
return null
}
fun findIndexFile(basedir: Path): Path? {
val children = basedir.directoryStreamIfExists({
val name = it.fileName.toString()
name.startsWith("index.") || name.startsWith("default.")
}) { it.toList() } ?: return null
for (indexNamePrefix in arrayOf("index.", "default.")) {
var index: Path? = null
val preferredName = "${indexNamePrefix}html"
for (child in children) {
if (!child.isDirectory()) {
val name = child.fileName.toString()
if (name == preferredName) {
return child
}
else if (index == null && name.startsWith(indexNamePrefix)) {
index = child
}
}
}
if (index != null) {
return index
}
}
return null
}
// is host loopback/any or network interface address (i.e. not custom domain)
// must be not used to check is host on local machine
internal fun isOwnHostName(host: String): Boolean {
if (NetUtils.isLocalhost(host)) {
return true
}
try {
val address = InetAddress.getByName(host)
if (host == address.hostAddress || host.equals(address.canonicalHostName, ignoreCase = true)) {
return true
}
val localHostName = InetAddress.getLocalHost().hostName
// WEB-8889
// develar.local is own host name: develar. equals to "develar.labs.intellij.net" (canonical host name)
return localHostName.equals(host, ignoreCase = true) || (host.endsWith(".local") && localHostName.regionMatches(0, host, 0, host.length - ".local".length, true))
}
catch (ignored: IOException) {
return false
}
}
| apache-2.0 | 44d6b717158b1b0ff2122bb1f344d8ca | 35.116337 | 165 | 0.711397 | 4.581162 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/SquareStripeButton.kt | 1 | 7792 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl
import com.intellij.icons.AllIcons
import com.intellij.ide.HelpTooltip
import com.intellij.ide.actions.ActivateToolWindowAction
import com.intellij.ide.actions.ToolWindowMoveAction
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.ScalableIcon
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID
import com.intellij.openapi.wm.impl.SquareStripeButton.Companion.createMoveGroup
import com.intellij.openapi.wm.safeToolWindowPaneId
import com.intellij.toolWindow.ToolWindowEventSource
import com.intellij.ui.MouseDragHelper
import com.intellij.ui.PopupHandler
import com.intellij.ui.ToggleActionButton
import com.intellij.ui.UIBundle
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import java.awt.Component
import java.awt.Dimension
import java.awt.Graphics
import java.awt.Rectangle
import java.awt.event.MouseEvent
import java.util.function.Supplier
internal class SquareStripeButton(val toolWindow: ToolWindowImpl) :
ActionButton(SquareAnActionButton(toolWindow), createPresentation(toolWindow), ActionPlaces.TOOLWINDOW_TOOLBAR_BAR, Dimension(40, 40)) {
companion object {
fun createMoveGroup(toolWindow: ToolWindowImpl): DefaultActionGroup {
val result = DefaultActionGroup.createPopupGroup(Supplier { UIBundle.message("tool.window.new.stripe.move.to.action.group.name") })
result.add(MoveToAction(toolWindow, ToolWindowMoveAction.Anchor.LeftTop))
result.add(MoveToAction(toolWindow, ToolWindowMoveAction.Anchor.BottomLeft))
result.add(MoveToAction(toolWindow, ToolWindowMoveAction.Anchor.RightTop))
result.add(MoveToAction(toolWindow, ToolWindowMoveAction.Anchor.BottomRight))
return result
}
}
init {
setLook(SquareStripeButtonLook(this))
addMouseListener(object : PopupHandler() {
override fun invokePopup(component: Component, x: Int, y: Int) {
val popupMenu = ActionManager.getInstance()
.createActionPopupMenu(ActionPlaces.TOOLWINDOW_POPUP, createPopupGroup(toolWindow))
popupMenu.component.show(component, x, y)
}
})
MouseDragHelper.setComponentDraggable(this, true)
}
override fun updateUI() {
super.updateUI()
myPresentation.icon = toolWindow.icon ?: AllIcons.Toolbar.Unknown
scaleIcon(myPresentation)
myPresentation.isEnabledAndVisible = true
}
fun updatePresentation() {
updateToolTipText()
myPresentation.icon = toolWindow.icon ?: AllIcons.Toolbar.Unknown
scaleIcon(myPresentation)
}
fun isHovered() = myRollover
fun isFocused() = toolWindow.isActive
fun resetDrop() = resetMouseState()
fun paintDraggingButton(g: Graphics) {
val areaSize = size.also {
JBInsets.removeFrom(it, insets)
JBInsets.removeFrom(it, SquareStripeButtonLook.ICON_PADDING)
}
val rect = Rectangle(areaSize)
buttonLook.paintLookBackground(g, rect, JBUI.CurrentTheme.ActionButton.pressedBackground())
icon.let {
val x = (areaSize.width - it.iconWidth) / 2
val y = (areaSize.height - it.iconHeight) / 2
buttonLook.paintIcon(g, this, it, x, y)
}
buttonLook.paintLookBorder(g, rect, JBUI.CurrentTheme.ActionButton.pressedBorder())
}
override fun updateToolTipText() {
@Suppress("DialogTitleCapitalization")
HelpTooltip()
.setTitle(toolWindow.stripeTitle)
.setLocation(getAlignment(toolWindow.anchor, toolWindow.isSplitMode))
.setShortcut(ActionManager.getInstance().getKeyboardShortcut(ActivateToolWindowAction.getActionIdForToolWindow(toolWindow.id)))
.setInitialDelay(0)
.setHideDelay(0)
.installOn(this)
HelpTooltip.setMasterPopupOpenCondition(this) { !(parent as AbstractDroppableStripe).isDroppingButton() }
}
override fun checkSkipPressForEvent(e: MouseEvent) = e.button != MouseEvent.BUTTON1
}
private fun getAlignment(anchor: ToolWindowAnchor, splitMode: Boolean): HelpTooltip.Alignment {
return when (anchor) {
ToolWindowAnchor.RIGHT -> HelpTooltip.Alignment.LEFT
ToolWindowAnchor.TOP -> HelpTooltip.Alignment.LEFT
ToolWindowAnchor.LEFT -> HelpTooltip.Alignment.RIGHT
ToolWindowAnchor.BOTTOM -> if (splitMode) HelpTooltip.Alignment.LEFT else HelpTooltip.Alignment.RIGHT
else -> HelpTooltip.Alignment.RIGHT
}
}
private fun createPresentation(toolWindow: ToolWindowImpl): Presentation {
val presentation = Presentation(toolWindow.stripeTitle)
presentation.icon = toolWindow.icon ?: AllIcons.Toolbar.Unknown
scaleIcon(presentation)
presentation.isEnabledAndVisible = true
return presentation
}
private fun scaleIcon(presentation: Presentation) {
if (presentation.icon is ScalableIcon && presentation.icon.iconWidth != 20) {
presentation.icon = IconLoader.loadCustomVersionOrScale(presentation.icon as ScalableIcon, 20f)
}
}
private fun createPopupGroup(toolWindow: ToolWindowImpl): DefaultActionGroup {
val group = DefaultActionGroup()
group.add(HideAction(toolWindow))
group.addSeparator()
group.add(createMoveGroup(toolWindow))
return group
}
private class MoveToAction(private val toolWindow: ToolWindowImpl,
private val targetAnchor: ToolWindowMoveAction.Anchor) : AnAction(targetAnchor.toString()), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
val toolWindowManager = toolWindow.toolWindowManager
val info = toolWindowManager.getLayout().getInfo(toolWindow.id)
toolWindowManager.setSideToolAndAnchor(id = toolWindow.id,
paneId = info?.safeToolWindowPaneId ?: WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID,
anchor = targetAnchor.anchor,
order = -1,
isSplit = targetAnchor.isSplit)
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = targetAnchor.anchor != toolWindow.anchor || toolWindow.isSplitMode != targetAnchor.isSplit
}
}
private class HideAction(private val toolWindow: ToolWindowImpl)
: AnAction(UIBundle.message("tool.window.new.stripe.hide.action.name")), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
toolWindow.toolWindowManager.hideToolWindow(id = toolWindow.id,
hideSide = false,
moveFocus = true,
removeFromStripe = true,
source = ToolWindowEventSource.SquareStripeButton)
}
}
private class SquareAnActionButton(private val window: ToolWindowImpl) : ToggleActionButton(window.stripeTitle, null), DumbAware {
override fun isSelected(e: AnActionEvent): Boolean {
e.presentation.icon = window.icon ?: AllIcons.Toolbar.Unknown
scaleIcon(e.presentation)
return window.isVisible
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (e.project!!.isDisposed) {
return
}
val manager = window.toolWindowManager
if (state) {
manager.activated(window, ToolWindowEventSource.SquareStripeButton)
}
else {
manager.hideToolWindow(id = window.id,
hideSide = false,
moveFocus = true,
removeFromStripe = false,
source = ToolWindowEventSource.SquareStripeButton)
}
}
} | apache-2.0 | 448601cedf17a2b7bc833dafd16c95ee | 39.170103 | 138 | 0.722279 | 4.845771 | false | false | false | false |
iMeiji/Daily | app/src/main/java/com/meiji/daily/util/RetrofitHelper.kt | 1 | 3851 | package com.meiji.daily.util
import android.content.Context
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.meiji.daily.BuildConfig
import com.meiji.daily.SdkManager
import com.meiji.daily.data.remote.IApi
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by Meiji on 2017/12/28.
*/
@Singleton
class RetrofitHelper
@Inject
constructor(private val mContext: Context) {
/**
* 缓存机制
* 在响应请求之后在 data/data/<包名>/cache 下建立一个response 文件夹,保持缓存数据。
* 这样我们就可以在请求的时候,如果判断到没有网络,自动读取缓存的数据。
* 同样这也可以实现,在我们没有网络的情况下,重新打开App可以浏览的之前显示过的内容。
* 也就是:判断网络,有网络,则从网络获取,并保存到缓存中,无网络,则从缓存中获取。
* https://werb.github.io/2016/07/29/%E4%BD%BF%E7%94%A8Retrofit2+OkHttp3%E5%AE%9E%E7%8E%B0%E7%BC%93%E5%AD%98%E5%A4%84%E7%90%86/
</包名> */
private val cacheControlInterceptor = Interceptor { chain ->
var request = chain.request()
if (!NetWorkUtil.isNetworkConnected(mContext)) {
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build()
}
val originalResponse = chain.proceed(request)
if (NetWorkUtil.isNetworkConnected(mContext)) {
// 有网络时 设置缓存为默认值
val cacheControl = request.cacheControl().toString()
originalResponse.newBuilder()
.header("Cache-Control", cacheControl)
.removeHeader("Pragma") // 清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效
.build()
} else {
// 无网络时 设置超时为1周
val maxStale = 60 * 60 * 24 * 7
originalResponse.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.removeHeader("Pragma")
.build()
}
}
// 指定缓存路径,缓存大小 50Mb
// Cookie 持久化
// Log 拦截器
val retrofit: Retrofit
get() {
val cache = Cache(File(mContext.cacheDir, "HttpCache"),
(1024 * 1024 * 50).toLong())
val cookieJar = PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(mContext))
var builder: OkHttpClient.Builder = OkHttpClient.Builder()
.cookieJar(cookieJar)
.cache(cache)
.addInterceptor(cacheControlInterceptor)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
if (BuildConfig.DEBUG) {
builder = SdkManager.initInterceptor(builder)
}
return Retrofit.Builder()
.baseUrl(IApi.API_BASE)
.client(builder.build())
.addConverterFactory(MoshiConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
}
| apache-2.0 | f0ab48e6a8769cdf6259429cac42aadd | 37.348315 | 131 | 0.63639 | 4.192875 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/base/fe10/analysis/DaemonCodeAnalyzerStatusService.kt | 7 | 1399 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.base.fe10.analysis
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
class DaemonCodeAnalyzerStatusService(project: Project) : Disposable {
companion object {
fun getInstance(project: Project): DaemonCodeAnalyzerStatusService = project.service()
}
@Volatile
var daemonRunning: Boolean = false
private set
init {
val messageBusConnection = project.messageBus.connect(this)
messageBusConnection.subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, object : DaemonCodeAnalyzer.DaemonListener {
override fun daemonStarting(fileEditors: MutableCollection<out FileEditor>) {
daemonRunning = true
}
override fun daemonFinished(fileEditors: MutableCollection<out FileEditor>) {
daemonRunning = false
}
override fun daemonCancelEventOccurred(reason: String) {
daemonRunning = false
}
})
}
override fun dispose() {}
} | apache-2.0 | 654d76b870e81f2e2173365387c23275 | 34.897436 | 122 | 0.714081 | 5.162362 | false | false | false | false |
Kyuubey/site | src/main/kotlin/moe/kyubey/site/views/components/Pushpin.kt | 1 | 1676 | package moe.kyubey.site.views.components
import kotlinx.html.*
fun BODY.donatePushpin() {
div {
classes = setOf("card", "kyubey-red", "z-depth-4")
id = "we-dont-like-ads-too"
div {
classes = setOf("card-content", "kyubey-greyish-text", "center")
span {
classes = setOf("card-title")
a {
classes = setOf("info kyubey-greyish-text")
i {
classes = setOf("fas fa-info-circle", "left")
}
}
+"Hey!"
a {
classes = setOf("close kyubey-greyish-text")
i {
classes = setOf("fas fa-times", "right")
}
}
}
p {
+"We know you hate ads, we do too, and that's why there aren't any ads here! But hosting a site costs money, so donating would help us keep the site (and Kyubey) online!"
}
br()
p {
a("https://paypal.me/awau") {
classes = setOf("waves-effect", "waves-teal", "btn", "white", "kyubey-red-text", "center")
i {
classes = setOf("left", "fas", "fa-dollar-sign")
}
+"Donate!"
}
}
p {
a("https://patreon.com/yuwui") {
classes = setOf("kyubey-greyish-text")
style = "font-size:12px;"
+"Or become a patreon!"
}
}
}
}
}
| mit | 2adb79121aad6719cf7c98b8bd1a3a8c | 33.204082 | 186 | 0.393795 | 4.51752 | false | false | false | false |
himikof/intellij-rust | src/main/kotlin/org/rust/ide/typing/utils.kt | 1 | 2071 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.typing
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.highlighter.HighlighterIterator
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.tree.IElementType
import com.intellij.util.text.CharSequenceSubSequence
import org.rust.lang.core.psi.RsComplexLiteral
import org.rust.lang.core.psi.RsLiteralKind
fun isValidOffset(offset: Int, text: CharSequence): Boolean =
0 <= offset && offset <= text.length
/**
* Beware that this returns `false` for EOF!
*/
fun isValidInnerOffset(offset: Int, text: CharSequence): Boolean =
0 <= offset && offset < text.length
/**
* Get previous and next token types relative to [iterator] position.
*/
fun getSiblingTokens(iterator: HighlighterIterator): Pair<IElementType?, IElementType?> {
iterator.retreat()
val prev = if (iterator.atEnd()) null else iterator.tokenType
iterator.advance()
iterator.advance()
val next = if (iterator.atEnd()) null else iterator.tokenType
iterator.retreat()
return prev to next
}
/**
* Creates virtual [RsLiteralKind] PSI element assuming that it is represented as
* single, contiguous token in highlighter, in other words - it doesn't contain
* any escape sequences etc. (hence 'dumb').
*/
fun getLiteralDumb(iterator: HighlighterIterator): RsComplexLiteral? {
val start = iterator.start
val end = iterator.end
val document = iterator.document
val text = document.charsSequence
val literalText = CharSequenceSubSequence(text, start, end)
val elementType = iterator.tokenType ?: return null
return RsLiteralKind.fromAstNode(LeafPsiElement(elementType, literalText)) as? RsComplexLiteral
}
fun Document.deleteChar(offset: Int) {
deleteString(offset, offset + 1)
}
// BACKCOMPAT: 2016.3
@Suppress("DEPRECATED_BINARY_MOD_AS_REM")
fun CharSequence.endsWithUnescapedBackslash(): Boolean =
takeLastWhile { it == '\\' }.length % 2 == 1
| mit | f999ae31d8322d60c4c1ad9ecf1d1394 | 31.359375 | 99 | 0.742636 | 4.142 | false | false | false | false |
NiciDieNase/chaosflix | common/src/main/java/de/nicidienase/chaosflix/common/viewmodel/DetailsViewModel.kt | 1 | 8525 | package de.nicidienase.chaosflix.common.viewmodel
import android.os.Bundle
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import de.nicidienase.chaosflix.common.ChaosflixDatabase
import de.nicidienase.chaosflix.common.ChaosflixUtil
import de.nicidienase.chaosflix.common.OfflineItemManager
import de.nicidienase.chaosflix.common.PreferencesManager
import de.nicidienase.chaosflix.common.mediadata.MediaRepository
import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Event
import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Recording
import de.nicidienase.chaosflix.common.userdata.entities.watchlist.WatchlistItem
import de.nicidienase.chaosflix.common.util.LiveEvent
import de.nicidienase.chaosflix.common.util.SingleLiveEvent
import java.io.File
import java.util.ArrayList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class DetailsViewModel(
private val database: ChaosflixDatabase,
private val offlineItemManager: OfflineItemManager,
private val preferencesManager: PreferencesManager,
private val mediaRepository: MediaRepository
) : ViewModel() {
val state: SingleLiveEvent<LiveEvent<State, Bundle, String>> =
SingleLiveEvent()
private var waitingForRecordings = false
var autoselectRecording: Boolean
get() = preferencesManager.autoselectRecording
set(value) { preferencesManager.autoselectRecording = value }
var autoselectStream: Boolean
get() = preferencesManager.autoselectStream
set(value) { preferencesManager.autoselectStream = value }
fun setEvent(event: Event): LiveData<Event?> {
viewModelScope.launch(Dispatchers.IO) {
val recordings = mediaRepository.updateRecordingsForEvent(event)
if (waitingForRecordings) {
if (recordings != null) {
waitingForRecordings = false
val bundle = Bundle()
bundle.putParcelable(EVENT, event)
bundle.putParcelableArrayList(KEY_SELECT_RECORDINGS, ArrayList(recordings))
state.postValue(LiveEvent(State.SelectRecording, data = bundle))
} else {
state.postValue(LiveEvent(State.Error, error = "Could not load recordings."))
}
}
}
return database.eventDao().findEventByGuid(event.guid)
}
fun play(event: Event, autoselect: Boolean = autoselectRecording) = viewModelScope.launch(Dispatchers.IO) {
if (autoselect) {
val recordings = database.recordingDao().findRecordingByEventSync(event.id)
val optimalRecording = ChaosflixUtil.getOptimalRecording(recordings, event.originalLanguage)
val recordingUrl = ChaosflixUtil.getRecordingForThumbs(recordings)?.recordingUrl
playRecording(event, optimalRecording, recordingUrl)
} else {
playEvent(event)
}
}
fun getBookmarkForEvent(guid: String): LiveData<WatchlistItem?> =
mediaRepository.getBookmark(guid)
fun createBookmark(guid: String) = viewModelScope.launch(Dispatchers.IO) {
mediaRepository.addBookmark(guid)
}
fun removeBookmark(guid: String) = viewModelScope.launch(Dispatchers.IO) {
mediaRepository.deleteBookmark(guid)
}
fun download(event: Event, recording: Recording) =
offlineItemManager.download(event, recording)
fun deleteOfflineItem(event: Event): LiveData<Boolean> {
val result = MutableLiveData<Boolean>()
viewModelScope.launch(Dispatchers.IO) {
database.offlineEventDao().getByEventGuidSuspend(event.guid)?.let {
offlineItemManager.deleteOfflineItem(it)
}
result.postValue(true)
}
return result
}
fun getRelatedEvents(event: Event): LiveData<List<Event>> = mediaRepository.getReleatedEvents(event)
fun relatedEventSelected(event: Event) {
val bundle = Bundle()
bundle.putParcelable(EVENT, event)
state.postValue(LiveEvent(State.DisplayEvent, data = bundle))
}
fun downloadRecordingForEvent(event: Event) =
postStateWithEventAndRecordings(State.DownloadRecording, event)
fun playInExternalPlayer(event: Event) = postStateWithEventAndRecordings(State.PlayExternal, event)
fun recordingSelected(e: Event, r: Recording) {
viewModelScope.launch(Dispatchers.IO) {
val recordings: List<Recording> = database.recordingDao().findRecordingByEventSync(e.id)
val url = ChaosflixUtil.getRecordingForThumbs(recordings)?.recordingUrl
playRecording(e, r, url)
}
}
private fun playEvent(event: Event) {
viewModelScope.launch(Dispatchers.IO) {
val offlineEvent = database.offlineEventDao().getByEventGuidSuspend(event.guid)
if (offlineEvent != null) {
// Play offlineEvent
val recording = database.recordingDao().findRecordingByIdSync(offlineEvent.recordingId)
if (!fileExists(event.guid)) {
state.postValue(LiveEvent(State.Error, error = "File is gone"))
} else {
val bundle = Bundle()
bundle.putString(KEY_LOCAL_PATH, offlineEvent.localPath)
bundle.putParcelable(RECORDING, recording)
bundle.putParcelable(EVENT, event)
if (preferencesManager.externalPlayer) {
state.postValue(LiveEvent(State.PlayExternal, bundle))
} else {
state.postValue(LiveEvent(State.PlayOfflineItem, data = bundle))
}
}
} else {
// select quality then playEvent
val items: List<Recording> = database.recordingDao().findRecordingByEventSync(event.id)
if (preferencesManager.autoselectStream && items.isNotEmpty()) {
val bundle = Bundle()
bundle.putParcelable(EVENT, event)
bundle.putParcelableArrayList(KEY_SELECT_RECORDINGS, ArrayList(items))
state.postValue(LiveEvent(State.SelectRecording, data = bundle))
} else {
state.postValue(LiveEvent(State.Loading))
waitingForRecordings = true
}
}
}
}
private suspend fun fileExists(guid: String): Boolean {
val offlineItem = database.offlineEventDao().getByEventGuidSuspend(guid)
return offlineItem != null && File(offlineItem.localPath).exists()
}
private fun playRecording(event: Event, recording: Recording, urlForThumbs: String? = null) = viewModelScope.launch(Dispatchers.IO) {
val progress = database.playbackProgressDao().getProgressForEventSync(event.guid)
val bundle = Bundle().apply {
putParcelable(RECORDING, recording)
putParcelable(EVENT, event)
putString(THUMBS_URL, urlForThumbs)
progress?.let {
putLong(PROGRESS, it.progress)
}
}
if (preferencesManager.externalPlayer) {
state.postValue(LiveEvent(State.PlayExternal, bundle))
} else {
state.postValue(LiveEvent(State.PlayOnlineItem, bundle))
}
}
private fun postStateWithEventAndRecordings(s: State, e: Event) {
viewModelScope.launch(Dispatchers.IO) {
val items = database.recordingDao().findRecordingByEventSync(e.id)
val bundle = Bundle()
bundle.putParcelable(EVENT, e)
bundle.putParcelableArrayList(KEY_SELECT_RECORDINGS, ArrayList(items))
state.postValue(LiveEvent(s, bundle))
}
}
enum class State {
PlayOfflineItem,
PlayOnlineItem,
SelectRecording,
DownloadRecording,
DisplayEvent,
PlayExternal,
Error,
Loading
}
companion object {
val TAG = DetailsViewModel::class.simpleName
const val KEY_LOCAL_PATH = "local_path"
const val KEY_SELECT_RECORDINGS = "select_recordings"
const val RECORDING = "recording"
const val EVENT = "event"
const val THUMBS_URL = "thumbs_url"
const val PROGRESS = "progress"
}
}
| mit | 3e595b159d32ea293fb899e73ef97a5d | 40.789216 | 137 | 0.65783 | 5.056346 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/response/ApplicationResponseProperties.kt | 1 | 2337 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("unused")
package io.ktor.server.response
import io.ktor.http.*
/**
* Appends a header with the specified [name] and [value] to a response.
*/
public fun ApplicationResponse.header(name: String, value: String): Unit = headers.append(name, value)
/**
* Appends a header with the specified [name] and [value] to a response.
*/
public fun ApplicationResponse.header(name: String, value: Int): Unit = headers.append(name, value.toString())
/**
* Appends a header with the specified [name] and [value] to a response.
*/
public fun ApplicationResponse.header(name: String, value: Long): Unit = headers.append(name, value.toString())
/**
* Appends the `E-Tag` header with the specified [value] to a response.
*/
public fun ApplicationResponse.etag(value: String): Unit = header(HttpHeaders.ETag, value)
/**
* Appends the `Cache-Control` header with the specified [value] to a response.
*/
public fun ApplicationResponse.cacheControl(value: CacheControl): Unit =
header(HttpHeaders.CacheControl, value.toString())
/**
* Appends the `Cache-Control` header with the specified [value] to a response.
*/
public fun HeadersBuilder.cacheControl(value: CacheControl): Unit = set(HttpHeaders.CacheControl, value.toString())
/**
* Appends the `Content-Range` header with the specified [range] and [fullLength] to a response.
*/
public fun HeadersBuilder.contentRange(
range: LongRange?,
fullLength: Long? = null,
unit: String = RangeUnits.Bytes.unitToken
) {
append(HttpHeaders.ContentRange, contentRangeHeaderValue(range, fullLength, unit))
}
/**
* Appends the `Content-Range` header with the specified [range] and [fullLength] to a response.
*/
public fun ApplicationResponse.contentRange(
range: LongRange?,
fullLength: Long? = null,
unit: RangeUnits
) {
contentRange(range, fullLength, unit.unitToken)
}
/**
* Appends the `Content-Range` header with the specified [range] and [fullLength] to a response.
*/
public fun ApplicationResponse.contentRange(
range: LongRange?,
fullLength: Long? = null,
unit: String = RangeUnits.Bytes.unitToken
) {
header(HttpHeaders.ContentRange, contentRangeHeaderValue(range, fullLength, unit))
}
| apache-2.0 | 31b91a74f252854d44652391bdc1144d | 31.013699 | 118 | 0.72914 | 3.921141 | false | false | false | false |
cfieber/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/ResumeTaskHandlerTest.kt | 1 | 2745 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus.PAUSED
import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.fixture.pipeline
import com.netflix.spinnaker.orca.fixture.stage
import com.netflix.spinnaker.orca.fixture.task
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.tasks.NoOpTask
import com.netflix.spinnaker.orca.q.ResumeTask
import com.netflix.spinnaker.orca.q.RunTask
import com.netflix.spinnaker.q.Queue
import com.nhaarman.mockito_kotlin.*
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
object ResumeTaskHandlerTest : SubjectSpek<ResumeTaskHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
subject(GROUP) {
ResumeTaskHandler(queue, repository)
}
fun resetMocks() = reset(queue, repository)
describe("resuming a paused execution") {
val pipeline = pipeline {
application = "spinnaker"
status = RUNNING
stage {
refId = "1"
status = RUNNING
task {
id = "1"
status = PAUSED
}
}
}
val message = ResumeTask(pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id, "1")
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("sets the stage status to running") {
verify(repository).storeStage(check {
assertThat(it.id).isEqualTo(message.stageId)
assertThat(it.tasks.first().status).isEqualTo(RUNNING)
})
}
it("resumes all paused tasks") {
verify(queue).push(RunTask(message, NoOpTask::class.java))
verifyNoMoreInteractions(queue)
}
}
})
| apache-2.0 | 0277698f359ab784706c235481011e4f | 31.294118 | 111 | 0.730783 | 4.134036 | false | false | false | false |
onnerby/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/category/fragment/AllCategoriesFragment.kt | 2 | 2680 | package io.casey.musikcube.remote.ui.category.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView
import io.casey.musikcube.remote.R
import io.casey.musikcube.remote.service.websocket.model.IMetadataProxy
import io.casey.musikcube.remote.ui.category.adapter.AllCategoriesAdapter
import io.casey.musikcube.remote.ui.navigation.Navigate
import io.casey.musikcube.remote.ui.shared.activity.ITitleProvider
import io.casey.musikcube.remote.ui.shared.extension.getLayoutId
import io.casey.musikcube.remote.ui.shared.extension.setupDefaultRecyclerView
import io.casey.musikcube.remote.ui.shared.fragment.BaseFragment
import io.casey.musikcube.remote.ui.shared.mixin.MetadataProxyMixin
import io.reactivex.rxkotlin.subscribeBy
class AllCategoriesFragment: BaseFragment(), ITitleProvider {
private lateinit var data: MetadataProxyMixin
private lateinit var adapter: AllCategoriesAdapter
override val title: String
get() = getString(R.string.category_activity)
override fun onCreate(savedInstanceState: Bundle?) {
component.inject(this)
data = mixin(MetadataProxyMixin())
super.onCreate(savedInstanceState)
adapter = AllCategoriesAdapter(adapterListener)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(this.getLayoutId(), container, false).apply {
val recyclerView = findViewById<FastScrollRecyclerView>(R.id.recycler_view)
setupDefaultRecyclerView(recyclerView, adapter)
}
override fun onInitObservables() {
disposables.add(data.provider.observeState().subscribeBy(
onNext = { states ->
if (states.first == IMetadataProxy.State.Connected) {
requery()
}
},
onError = {
}))
}
private fun requery() {
disposables.add(data.provider.listCategories().subscribeBy(
onNext = {
adapter.setModel(it)
},
onError = {
}))
}
private val adapterListener = object:AllCategoriesAdapter.EventListener {
override fun onItemClicked(category: String) =
Navigate.toCategoryList(
category,
appCompatActivity,
this@AllCategoriesFragment)
}
companion object {
const val TAG = "AllCategoriesFragment"
fun create(): AllCategoriesFragment = AllCategoriesFragment()
}
} | bsd-3-clause | 22619e9cb30f4420115e0b57cf8c1951 | 34.746667 | 116 | 0.699254 | 4.981413 | false | false | false | false |
onnerby/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/service/websocket/WebSocketService.kt | 2 | 21255 | package io.casey.musikcube.remote.service.websocket
import android.annotation.SuppressLint
import android.content.*
import android.content.Context.CONNECTIVITY_SERVICE
import android.net.ConnectivityManager
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import com.neovisionaries.ws.client.*
import io.casey.musikcube.remote.BuildConfig
import io.casey.musikcube.remote.service.websocket.model.IEnvironment
import io.casey.musikcube.remote.service.websocket.model.impl.remote.RemoteEnvironment
import io.casey.musikcube.remote.ui.settings.constants.Prefs
import io.casey.musikcube.remote.ui.shared.extension.getString
import io.casey.musikcube.remote.ui.shared.util.NetworkUtil
import io.casey.musikcube.remote.util.Preconditions
import io.reactivex.Observable
import io.reactivex.subjects.ReplaySubject
import org.json.JSONObject
import java.util.*
import java.util.concurrent.atomic.AtomicLong
class WebSocketService constructor(private val context: Context) {
interface Client {
fun onStateChanged(newState: State, oldState: State)
fun onMessageReceived(message: SocketMessage)
fun onInvalidPassword()
}
interface Responder {
fun respond(response: SocketMessage)
}
enum class State {
Connecting,
Connected,
Disconnected
}
private val handler = Handler(Looper.getMainLooper()) { message: Message ->
var result = false
if (message.what == MESSAGE_CONNECT_THREAD_FINISHED) {
if (message.obj == null) {
val invalidPassword = message.arg1 == FLAG_AUTHENTICATION_FAILED
disconnect(!invalidPassword) /* auto reconnect as long as password was not invalid */
if (invalidPassword) {
for (client in clients) {
client.onInvalidPassword()
}
}
}
else {
setSocket(message.obj as WebSocket)
state = State.Connected
ping()
}
result = true
}
else if (message.what == MESSAGE_RECEIVED) {
val msg = message.obj as SocketMessage
var dispatched = false
/* registered callback for THIS message */
val mdr = messageCallbacks.remove(msg.id)
val error = msg.getStringOption("error")
if (error.isNotEmpty()) {
mdr?.error?.let {
it.invoke(error)
dispatched = true
}
}
else if (mdr?.callback != null) {
mdr.callback?.invoke(msg)
dispatched = true
}
if (!dispatched) {
/* service-level callback */
for (client in clients) {
client.onMessageReceived(msg)
}
}
if (mdr != null) {
mdr.error = null
}
result = true
}
else if (message.what == MESSAGE_REMOVE_OLD_CALLBACKS) {
scheduleRemoveStaleCallbacks()
}
else if (message.what == MESSAGE_AUTO_RECONNECT) {
if (state == State.Disconnected && autoReconnect) {
reconnect()
}
}
else if (message.what == MESSAGE_SCHEDULE_PING) {
ping()
}
else if (message.what == MESSAGE_PING_TIMEOUT) {
if (DISCONNECT_ON_PING_TIMEOUT) {
removeInternalCallbacks()
disconnect(state == State.Connected || autoReconnect)
}
}
result
}
private enum class Type { Callback, Reactive }
private class MessageResultDescriptor {
var id: Long = 0
var enqueueTime: Long = 0
var intercepted: Boolean = false
var client: Client? = null
var callback: ((response: SocketMessage) -> Unit)? = null
var error: ((message: String) -> Unit)? = null
var type: Type = Type.Callback
}
private val prefs: SharedPreferences = context.getSharedPreferences(Prefs.NAME, Context.MODE_PRIVATE)
private var socket: WebSocket? = null
private val clients = HashSet<Client>()
private val messageCallbacks = HashMap<String, MessageResultDescriptor>()
private var autoReconnect = false
private val networkChanged = NetworkChangedReceiver()
private var thread: ConnectThread? = null
private val interceptors = HashSet<(SocketMessage, Responder) -> Boolean>()
var environment: IEnvironment = RemoteEnvironment()
private set
init {
scheduleRemoveStaleCallbacks()
}
var state = State.Disconnected
private set(newState) {
Preconditions.throwIfNotOnMainThread()
Log.d(TAG, "state=$newState")
if (state == State.Disconnected) {
environment = RemoteEnvironment()
}
if (state != newState) {
val old = state
field = newState
for (client in clients) {
client.onStateChanged(newState, old)
}
}
}
fun addInterceptor(interceptor: (SocketMessage, Responder) -> Boolean) {
Preconditions.throwIfNotOnMainThread()
interceptors.add(interceptor)
}
@Suppress("unused")
fun removeInterceptor(interceptor: (SocketMessage, Responder) -> Boolean) {
Preconditions.throwIfNotOnMainThread()
interceptors.remove(interceptor)
}
fun addClient(client: Client) {
Preconditions.throwIfNotOnMainThread()
if (!clients.contains(client)) {
clients.add(client)
if (clients.size >= 0 && state == State.Disconnected) {
registerReceiverAndScheduleFailsafe()
reconnect()
}
handler.removeCallbacks(autoDisconnectRunnable)
client.onStateChanged(state, state)
}
}
fun removeClient(client: Client) {
Preconditions.throwIfNotOnMainThread()
if (clients.remove(client)) {
removeCallbacksForClient(client)
if (clients.size == 0) {
unregisterReceiverAndCancelFailsafe()
handler.postDelayed(autoDisconnectRunnable, AUTO_DISCONNECT_DELAY_MILLIS)
}
}
}
fun hasClient(client: Client): Boolean {
Preconditions.throwIfNotOnMainThread()
return clients.contains(client)
}
fun reconnect() {
Preconditions.throwIfNotOnMainThread()
autoReconnect = true
connectIfNotConnected()
}
fun disconnect() {
disconnect(false) /* don't auto-reconnect */
}
fun cancelMessage(id: Long) {
Preconditions.throwIfNotOnMainThread()
removeCallbacks { mrd: MessageResultDescriptor -> mrd.id == id }
}
fun shouldUpgrade(): Boolean {
return environment.apiVersion > MINIMUM_SUPPORTED_API_VERSION
}
private fun scheduleRemoveStaleCallbacks() {
removeExpiredCallbacks()
handler.sendEmptyMessageDelayed(MESSAGE_REMOVE_OLD_CALLBACKS, CALLBACK_TIMEOUT_MILLIS)
}
private fun ping() {
if (state == State.Connected) {
removeInternalCallbacks()
handler.removeMessages(MESSAGE_PING_TIMEOUT)
handler.sendEmptyMessageDelayed(MESSAGE_PING_TIMEOUT, PING_INTERVAL_MILLIS)
val ping = SocketMessage.Builder.request(Messages.Request.Ping).build()
send(ping, INTERNAL_CLIENT) {
handler.removeMessages(MESSAGE_PING_TIMEOUT)
handler.sendEmptyMessageDelayed(MESSAGE_SCHEDULE_PING, PING_INTERVAL_MILLIS)
}
}
}
fun cancelMessages(client: Client) {
Preconditions.throwIfNotOnMainThread()
removeCallbacks { mrd: MessageResultDescriptor ->
mrd.client === client
}
}
fun send(message: SocketMessage,
client: Client? = null,
callback: ((response: SocketMessage) -> Unit)? = null): Long {
Preconditions.throwIfNotOnMainThread()
var intercepted = false
interceptors.forEach {
if (it(message, responder)) {
intercepted = true
}
}
if (!intercepted) {
/* it seems that sometimes the socket dies, but the onDisconnected() event matches not
raised. unclear if this matches our bug or a bug in the library. disconnect and trigger
a reconnect until we can find a better root cause. this matches very difficult to repro */
if (socket != null && !socket!!.isOpen) {
disconnect(true)
return -1
}
else if (socket == null) {
return -1
}
}
val id = NEXT_ID.incrementAndGet()
if (callback != null) {
if (!clients.contains(client) && client !== INTERNAL_CLIENT) {
throw IllegalArgumentException("client matches not registered")
}
val mrd = MessageResultDescriptor()
mrd.id = id
mrd.enqueueTime = System.currentTimeMillis()
mrd.client = client
mrd.callback = callback
mrd.type = Type.Callback
mrd.intercepted = intercepted
messageCallbacks[message.id] = mrd
}
when (intercepted) {
true -> Log.d(TAG, "send: message intercepted with id=$id")
false -> socket?.sendText(message.toString())
}
return id
}
@SuppressLint("CheckResult")
fun observe(message: SocketMessage, client: Client): Observable<SocketMessage> {
Preconditions.throwIfNotOnMainThread()
var intercepted = false
for (interceptor in interceptors) {
if (interceptor(message, responder)) {
intercepted = true
break
}
}
if (!intercepted) {
/* it seems that sometimes the socket dies, but the onDisconnected() event matches not
raised. unclear if this matches our bug or a bug in the library. disconnect and trigger
a reconnect until we can find a better root cause. this matches very difficult to repro */
if (socket != null && !socket!!.isOpen) {
disconnect(true)
throw Exception("socket disconnected")
}
else if (socket == null) {
val replay = ReplaySubject.create<SocketMessage>()
replay.onError(Exception("socket not connected"))
return replay
}
}
if (!clients.contains(client) && client !== INTERNAL_CLIENT) {
throw IllegalArgumentException("client not registered")
}
val subject = ReplaySubject.create<SocketMessage>()
val mrd = MessageResultDescriptor()
mrd.id = NEXT_ID.incrementAndGet()
mrd.enqueueTime = System.currentTimeMillis()
mrd.client = client
mrd.intercepted = intercepted
mrd.type = Type.Reactive
mrd.callback = { response: SocketMessage ->
subject.onNext(response)
subject.onComplete()
}
mrd.error = {
val ex = Exception()
ex.fillInStackTrace()
subject.onError(ex)
}
@Suppress("unused")
subject.doOnDispose { cancelMessage(mrd.id) }
if (!intercepted) {
socket?.sendText(message.toString())
}
messageCallbacks[message.id] = mrd
return subject
}
fun hasValidConnection(): Boolean {
val address = prefs.getString(Prefs.Key.ADDRESS) ?: ""
val port = prefs.getInt(Prefs.Key.MAIN_PORT, -1)
return address.isNotEmpty() && port >= 0
}
private fun disconnect(autoReconnect: Boolean) {
Preconditions.throwIfNotOnMainThread()
synchronized(this) {
thread?.interrupt()
thread = null
}
this.autoReconnect = autoReconnect
socket?.removeListener(webSocketAdapter)
socket?.disconnect()
socket = null
removeNonInterceptedCallbacks()
state = State.Disconnected
if (autoReconnect) {
handler.sendEmptyMessageDelayed(
MESSAGE_AUTO_RECONNECT,
AUTO_RECONNECT_INTERVAL_MILLIS)
}
else {
handler.removeMessages(MESSAGE_AUTO_RECONNECT)
}
}
private fun removeNonInterceptedCallbacks() =
removeCallbacks {
mrd -> !mrd.intercepted
}
private fun removeInternalCallbacks() =
removeCallbacks {
mrd: MessageResultDescriptor -> mrd.client === INTERNAL_CLIENT
}
private fun removeExpiredCallbacks() {
val now = System.currentTimeMillis()
removeCallbacks {
mrd: MessageResultDescriptor -> now - mrd.enqueueTime > CALLBACK_TIMEOUT_MILLIS
}
}
private fun removeCallbacksForClient(client: Client) =
removeCallbacks { mrd: MessageResultDescriptor ->
mrd.client === client
}
private fun removeCallbacks(predicate: (MessageResultDescriptor) -> Boolean) {
val it = messageCallbacks.entries.iterator()
while (it.hasNext()) {
val entry = it.next()
val mdr = entry.value
if (predicate(mdr)) {
mdr.error?.invoke("canceled")
it.remove()
}
}
}
private fun connectIfNotConnected() {
if (state == State.Disconnected) {
disconnect(autoReconnect)
handler.removeMessages(MESSAGE_AUTO_RECONNECT)
if (clients.size > 0) {
handler.removeCallbacks(autoDisconnectRunnable)
state = State.Connecting
thread = ConnectThread()
thread?.start()
}
}
}
private fun setSocket(newSocket: WebSocket) {
if (socket !== newSocket) {
socket?.removeListener(webSocketAdapter)
socket = newSocket
}
}
private fun registerReceiverAndScheduleFailsafe() {
unregisterReceiverAndCancelFailsafe()
/* generally raises a CONNECTIVITY_ACTION event immediately,
even if already connected. */
val filter = IntentFilter()
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
context.registerReceiver(networkChanged, filter)
/* however, CONNECTIVITY_ACTION doesn't ALWAYS seem to be raised,
so we schedule a failsafe just in case */
handler.postDelayed(autoReconnectFailsafeRunnable, AUTO_CONNECT_FAILSAFE_DELAY_MILLIS)
}
private fun unregisterReceiverAndCancelFailsafe() {
handler.removeCallbacks(autoReconnectFailsafeRunnable)
try {
context.unregisterReceiver(networkChanged)
}
catch (ex: Exception) {
/* om nom nom */
}
}
private val autoReconnectFailsafeRunnable = object: Runnable {
override fun run() {
if (autoReconnect && state == State.Disconnected) {
reconnect()
}
}
}
private val autoDisconnectRunnable = object: Runnable {
override fun run() {
disconnect()
}
}
private val responder = object : Responder {
override fun respond(response: SocketMessage) {
/* post to the back of the queue in case the interceptor responded immediately;
we need to ensure all of the request book-keeping has been finished. */
handler.post {
handler.sendMessage(Message.obtain(handler, MESSAGE_RECEIVED, response))
}
}
}
private val webSocketAdapter = object : WebSocketAdapter() {
@Throws(Exception::class)
override fun onTextMessage(websocket: WebSocket?, text: String?) {
val message = SocketMessage.create(text!!)
if (message != null) {
if (message.name == Messages.Request.Authenticate.toString()) {
environment = RemoteEnvironment(
message.getJsonObjectOption("environment") ?: JSONObject())
handler.sendMessage(Message.obtain(
handler, MESSAGE_CONNECT_THREAD_FINISHED, websocket))
}
else {
handler.sendMessage(Message.obtain(handler, MESSAGE_RECEIVED, message))
}
}
}
@Throws(Exception::class)
override fun onDisconnected(websocket: WebSocket?,
serverCloseFrame: WebSocketFrame?,
clientCloseFrame: WebSocketFrame?,
closedByServer: Boolean) {
var flags = 0
if (serverCloseFrame?.closeCode == WEBSOCKET_FLAG_POLICY_VIOLATION) {
flags = FLAG_AUTHENTICATION_FAILED
}
handler.sendMessage(Message.obtain(handler, MESSAGE_CONNECT_THREAD_FINISHED, flags, 0, null))
}
}
private inner class ConnectThread : Thread() {
override fun run() {
var socket: WebSocket?
try {
val factory = WebSocketFactory()
if (prefs.getBoolean(Prefs.Key.CERT_VALIDATION_DISABLED, Prefs.Default.CERT_VALIDATION_DISABLED)) {
NetworkUtil.disableCertificateValidation(factory)
}
val protocol = if (prefs.getBoolean(Prefs.Key.SSL_ENABLED, Prefs.Default.SSL_ENABLED)) "wss" else "ws"
val host = String.format(
Locale.ENGLISH,
"%s://%s:%d",
protocol,
prefs.getString(Prefs.Key.ADDRESS, Prefs.Default.ADDRESS),
prefs.getInt(Prefs.Key.MAIN_PORT, Prefs.Default.MAIN_PORT))
socket = factory.createSocket(host, CONNECTION_TIMEOUT_MILLIS)
socket?.addListener(webSocketAdapter)
socket.addExtension(WebSocketExtension.PERMESSAGE_DEFLATE)
socket.connect()
socket.pingInterval = PING_INTERVAL_MILLIS
/* authenticate */
val auth = SocketMessage.Builder
.request(Messages.Request.Authenticate)
.addOption("password", prefs.getString(Prefs.Key.PASSWORD, Prefs.Default.PASSWORD)!!)
.build()
.toString()
socket.sendText(auth)
}
catch (ex: Exception) {
socket = null
}
synchronized(this@WebSocketService) {
if (thread === this && socket == null) {
handler.sendMessage(Message.obtain(
handler, MESSAGE_CONNECT_THREAD_FINISHED, null))
}
if (thread === this) {
thread = null
}
}
}
}
private inner class NetworkChangedReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val cm = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
val info = cm.activeNetworkInfo
if (info != null && info.isConnected) {
if (autoReconnect) {
connectIfNotConnected()
}
}
}
}
companion object {
private const val TAG = "WebSocketService"
private const val AUTO_RECONNECT_INTERVAL_MILLIS = 2000L
private const val CALLBACK_TIMEOUT_MILLIS = 30000L
private const val CONNECTION_TIMEOUT_MILLIS = 5000
private const val PING_INTERVAL_MILLIS = 3500L
private const val AUTO_CONNECT_FAILSAFE_DELAY_MILLIS = 2000L
private const val AUTO_DISCONNECT_DELAY_MILLIS = 10000L
private const val FLAG_AUTHENTICATION_FAILED = 0xbeef
private const val WEBSOCKET_FLAG_POLICY_VIOLATION = 1008
private const val MINIMUM_SUPPORTED_API_VERSION = 20
private const val MESSAGE_BASE = 0xcafedead.toInt()
private const val MESSAGE_CONNECT_THREAD_FINISHED = MESSAGE_BASE + 0
private const val MESSAGE_RECEIVED = MESSAGE_BASE + 1
private const val MESSAGE_REMOVE_OLD_CALLBACKS = MESSAGE_BASE + 2
private const val MESSAGE_AUTO_RECONNECT = MESSAGE_BASE + 3
private const val MESSAGE_SCHEDULE_PING = MESSAGE_BASE + 4
private const val MESSAGE_PING_TIMEOUT = MESSAGE_BASE + 5
private val DISCONNECT_ON_PING_TIMEOUT = !BuildConfig.DEBUG
private val NEXT_ID = AtomicLong(0)
private val INTERNAL_CLIENT = object : Client {
override fun onStateChanged(newState: State, oldState: State) {}
override fun onMessageReceived(message: SocketMessage) {}
override fun onInvalidPassword() {}
}
}
}
| bsd-3-clause | b4695e2b1167abe97a4a6951d8ed65c0 | 32.472441 | 118 | 0.582733 | 5.325733 | false | false | false | false |
mdanielwork/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/util/ScreenshotTaker.kt | 3 | 2676 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testGuiFramework.util
import org.apache.log4j.Logger
import java.awt.*
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.IIOImage
import javax.imageio.ImageIO
import javax.imageio.ImageWriteParam
import javax.imageio.ImageWriter
class ScreenshotTaker(private val robot: Robot = Robot()) {
fun safeTakeScreenshotAndSave(file: File,
captureArea: Rectangle = FULL_SCREEN,
format: ImageFormat = ImageFormat.JPG,
compressionQuality: Float = 0.5f) =
try {
writeCompressed(takeScreenshot(captureArea), file, format, compressionQuality)
} catch (e: Exception) {
LOG.error("screenshot failed", e)
}
fun safeTakeScreenshotAndSave(file: File,
component: Component,
format: ImageFormat = ImageFormat.JPG,
compressionQuality: Float = 0.5f) =
safeTakeScreenshotAndSave(file, component.bounds, format, compressionQuality)
private fun takeScreenshot(captureArea: Rectangle = FULL_SCREEN): BufferedImage =
drawCursor(robot.createScreenCapture(captureArea), MouseInfo.getPointerInfo().location)
private fun writeCompressed(image: BufferedImage, file: File, format: ImageFormat, compressionQuality: Float) {
var writer: ImageWriter? = null
try {
ImageIO.createImageOutputStream(file).use { imageOutputStream ->
writer = ImageIO.getImageWritersByFormatName(format.formatName).next()
val params = writer!!.defaultWriteParam
params.compressionMode = ImageWriteParam.MODE_EXPLICIT
params.compressionQuality = compressionQuality
writer!!.output = imageOutputStream
writer!!.write(null, IIOImage(image, null, null), params)
}
} finally {
writer?.dispose()
}
}
private fun drawCursor(image: BufferedImage, cursorLocation: Point): BufferedImage {
val graphics: Graphics = image.graphics
graphics.color = Color.RED
graphics.fillRect(cursorLocation.x - 10, cursorLocation.y, 20, 1)
graphics.fillRect(cursorLocation.x, cursorLocation.y - 10, 1, 20)
graphics.dispose()
return image
}
enum class ImageFormat(val formatName: String) {
PNG("png"),
JPG("jpg")
}
companion object {
private val FULL_SCREEN: Rectangle = Rectangle(Toolkit.getDefaultToolkit().screenSize)
private val LOG: Logger = Logger.getLogger(ScreenshotTaker::class.java)
}
} | apache-2.0 | 2ed28d7dc2af794f969646a164defd08 | 37.242857 | 140 | 0.686846 | 4.597938 | false | false | false | false |
aerisweather/AerisAndroidSDK | Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/data/room/MyPlace.kt | 1 | 920 | package com.example.demoaerisproject.data.room
import androidx.room.Entity
import com.aerisweather.aeris.util.WeatherUtil
import java.util.*
@Entity(tableName = "my_place_table", primaryKeys = ["name", "state", "country"])
class MyPlace(
var name: String,
var state: String,
var country: String,
var myLoc: Boolean = false,
var latitude: Double = 0.0,
var longitude: Double = 0.0
) {
fun getTextDisplay(defaultText: String?): String {
return if(defaultText.isNullOrEmpty()) {
String.format(
"%s, %s", WeatherUtil.capitalize(name),
country.uppercase(Locale.getDefault())
)
}
else {
String.format(
"%s, %s, %s", WeatherUtil.capitalize(name),
state.uppercase(Locale.getDefault()),
country.uppercase(Locale.getDefault())
)
}
}
}
| mit | 7495aecf0c08556c680faa72945aa711 | 27.75 | 81 | 0.583696 | 4.200913 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddReturnToUnusedLastExpressionInFunctionFix.kt | 3 | 2727 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
class AddReturnToUnusedLastExpressionInFunctionFix(element: KtElement) : KotlinQuickFixAction<KtElement>(element) {
private val available: Boolean
init {
val expression = element as? KtExpression
available = expression?.analyze(BodyResolveMode.PARTIAL)?.let { context ->
if (expression.isLastStatementInFunctionBody()) {
expression.getType(context)?.takeIf { !it.isError }
} else null
}?.let { expressionType ->
val function = expression.parent?.parent as? KtNamedFunction
val functionReturnType = function?.resolveToDescriptorIfAny()?.returnType?.takeIf { !it.isError } ?: return@let false
expressionType.isSubtypeOf(functionReturnType)
} ?: false
}
override fun getText() = KotlinBundle.message("fix.add.return.before.expression")
override fun getFamilyName() = text
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean =
element != null && available
private fun KtExpression.isLastStatementInFunctionBody(): Boolean {
val body = this.parent as? KtBlockExpression ?: return false
val last = body.statements.lastOrNull() ?: return false
return last === this
}
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
element.replace(KtPsiFactory(project).createExpression("return ${element.text}"))
}
companion object Factory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val casted = Errors.UNUSED_EXPRESSION.cast(diagnostic)
return AddReturnToUnusedLastExpressionInFunctionFix(casted.psiElement).takeIf(AddReturnToUnusedLastExpressionInFunctionFix::available)
}
}
}
| apache-2.0 | cd3417a61d29da04f5dddf8bbecb0043 | 44.45 | 158 | 0.739274 | 5.059369 | false | false | false | false |
fwcd/kotlin-language-server | server/src/main/kotlin/org/javacs/kt/KotlinLanguageServer.kt | 1 | 7533 | package org.javacs.kt
import org.eclipse.lsp4j.*
import org.eclipse.lsp4j.jsonrpc.messages.Either
import org.eclipse.lsp4j.jsonrpc.services.JsonDelegate
import org.eclipse.lsp4j.services.LanguageClient
import org.eclipse.lsp4j.services.LanguageClientAware
import org.eclipse.lsp4j.services.LanguageServer
import org.eclipse.lsp4j.services.NotebookDocumentService
import org.javacs.kt.command.ALL_COMMANDS
import org.javacs.kt.externalsources.*
import org.javacs.kt.util.AsyncExecutor
import org.javacs.kt.util.TemporaryDirectory
import org.javacs.kt.util.parseURI
import org.javacs.kt.progress.Progress
import org.javacs.kt.progress.LanguageClientProgress
import org.javacs.kt.semantictokens.semanticTokensLegend
import java.io.Closeable
import java.nio.file.Paths
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.completedFuture
class KotlinLanguageServer : LanguageServer, LanguageClientAware, Closeable {
val config = Configuration()
val classPath = CompilerClassPath(config.compiler)
private val tempDirectory = TemporaryDirectory()
private val uriContentProvider = URIContentProvider(ClassContentProvider(config.externalSources, classPath, tempDirectory, CompositeSourceArchiveProvider(JdkSourceArchiveProvider(classPath), ClassPathSourceArchiveProvider(classPath))))
val sourcePath = SourcePath(classPath, uriContentProvider, config.indexing)
val sourceFiles = SourceFiles(sourcePath, uriContentProvider)
private val textDocuments = KotlinTextDocumentService(sourceFiles, sourcePath, config, tempDirectory, uriContentProvider, classPath)
private val workspaces = KotlinWorkspaceService(sourceFiles, sourcePath, classPath, textDocuments, config)
private val protocolExtensions = KotlinProtocolExtensionService(uriContentProvider, classPath, sourcePath)
private lateinit var client: LanguageClient
private val async = AsyncExecutor()
private var progressFactory: Progress.Factory = Progress.Factory.None
set(factory: Progress.Factory) {
field = factory
sourcePath.progressFactory = factory
}
companion object {
val VERSION: String? = System.getProperty("kotlinLanguageServer.version")
}
init {
LOG.info("Kotlin Language Server: Version ${VERSION ?: "?"}")
}
override fun connect(client: LanguageClient) {
this.client = client
connectLoggingBackend()
workspaces.connect(client)
textDocuments.connect(client)
LOG.info("Connected to client")
}
override fun getTextDocumentService(): KotlinTextDocumentService = textDocuments
override fun getWorkspaceService(): KotlinWorkspaceService = workspaces
@JsonDelegate
fun getProtocolExtensionService(): KotlinProtocolExtensions = protocolExtensions
override fun initialize(params: InitializeParams): CompletableFuture<InitializeResult> = async.compute {
val serverCapabilities = ServerCapabilities()
serverCapabilities.setTextDocumentSync(TextDocumentSyncKind.Incremental)
serverCapabilities.workspace = WorkspaceServerCapabilities()
serverCapabilities.workspace.workspaceFolders = WorkspaceFoldersOptions()
serverCapabilities.workspace.workspaceFolders.supported = true
serverCapabilities.workspace.workspaceFolders.changeNotifications = Either.forRight(true)
serverCapabilities.hoverProvider = Either.forLeft(true)
serverCapabilities.renameProvider = Either.forLeft(true)
serverCapabilities.completionProvider = CompletionOptions(false, listOf("."))
serverCapabilities.signatureHelpProvider = SignatureHelpOptions(listOf("(", ","))
serverCapabilities.definitionProvider = Either.forLeft(true)
serverCapabilities.documentSymbolProvider = Either.forLeft(true)
serverCapabilities.workspaceSymbolProvider = Either.forLeft(true)
serverCapabilities.referencesProvider = Either.forLeft(true)
serverCapabilities.semanticTokensProvider = SemanticTokensWithRegistrationOptions(semanticTokensLegend, true, true)
serverCapabilities.codeActionProvider = Either.forLeft(true)
serverCapabilities.documentFormattingProvider = Either.forLeft(true)
serverCapabilities.documentRangeFormattingProvider = Either.forLeft(true)
serverCapabilities.executeCommandProvider = ExecuteCommandOptions(ALL_COMMANDS)
serverCapabilities.documentHighlightProvider = Either.forLeft(true)
val clientCapabilities = params.capabilities
config.completion.snippets.enabled = clientCapabilities?.textDocument?.completion?.completionItem?.snippetSupport ?: false
if (clientCapabilities?.window?.workDoneProgress ?: false) {
progressFactory = LanguageClientProgress.Factory(client)
}
if (clientCapabilities?.textDocument?.rename?.prepareSupport ?: false) {
serverCapabilities.renameProvider = Either.forRight(RenameOptions(false))
}
@Suppress("DEPRECATION")
val folders = params.workspaceFolders?.takeIf { it.isNotEmpty() }
?: params.rootUri?.let(::WorkspaceFolder)?.let(::listOf)
?: params.rootPath?.let(Paths::get)?.toUri()?.toString()?.let(::WorkspaceFolder)?.let(::listOf)
?: listOf()
val progress = params.workDoneToken?.let { LanguageClientProgress("Workspace folders", it, client) }
folders.forEachIndexed { i, folder ->
LOG.info("Adding workspace folder {}", folder.name)
val progressPrefix = "[${i + 1}/${folders.size}] ${folder.name ?: ""}"
val progressPercent = (100 * i) / folders.size
progress?.update("$progressPrefix: Updating source path", progressPercent)
val root = Paths.get(parseURI(folder.uri))
sourceFiles.addWorkspaceRoot(root)
progress?.update("$progressPrefix: Updating class path", progressPercent)
val refreshed = classPath.addWorkspaceRoot(root)
if (refreshed) {
progress?.update("$progressPrefix: Refreshing source path", progressPercent)
sourcePath.refresh()
}
}
progress?.close()
textDocuments.lintAll()
val serverInfo = ServerInfo("Kotlin Language Server", VERSION)
InitializeResult(serverCapabilities, serverInfo)
}
private fun connectLoggingBackend() {
val backend: (LogMessage) -> Unit = {
client.logMessage(MessageParams().apply {
type = it.level.toLSPMessageType()
message = it.message
})
}
LOG.connectOutputBackend(backend)
LOG.connectErrorBackend(backend)
}
private fun LogLevel.toLSPMessageType(): MessageType = when (this) {
LogLevel.ERROR -> MessageType.Error
LogLevel.WARN -> MessageType.Warning
LogLevel.INFO -> MessageType.Info
else -> MessageType.Log
}
override fun close() {
textDocumentService.close()
classPath.close()
tempDirectory.close()
async.shutdown(awaitTermination = true)
}
override fun shutdown(): CompletableFuture<Any> {
close()
return completedFuture(null)
}
override fun exit() {}
// Fixed in https://github.com/eclipse/lsp4j/commit/04b0c6112f0a94140e22b8b15bb5a90d5a0ed851
// Causes issue in lsp 0.15
override fun getNotebookDocumentService(): NotebookDocumentService? {
return null;
}
}
| mit | ed344c5b35b4c0f61bfbb34768c990aa | 42.543353 | 239 | 0.724545 | 5.0625 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/createClassUtils.kt | 2 | 8134 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass
import com.intellij.codeInsight.daemon.quickFix.CreateClassOrPackageFix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiPackage
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.quickfix.DelegatingIntentionAction
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.containsStarProjections
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.guessTypes
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.noSubstitutions
import org.jetbrains.kotlin.idea.refactoring.canRefactor
import org.jetbrains.kotlin.idea.util.getTypeSubstitution
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.DescriptorUtils
import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.Qualifier
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.descriptors.ClassKind as ClassDescriptorKind
internal fun String.checkClassName(): Boolean = isNotEmpty() && Character.isUpperCase(first())
private fun String.checkPackageName(): Boolean = isNotEmpty() && Character.isLowerCase(first())
internal fun getTargetParentsByQualifier(
element: KtElement,
isQualified: Boolean,
qualifierDescriptor: DeclarationDescriptor?
): List<PsiElement> {
val file = element.containingKtFile
val project = file.project
val targetParents: List<PsiElement> = when {
!isQualified ->
element.parents.filterIsInstance<KtClassOrObject>().toList() + file
qualifierDescriptor is ClassDescriptor ->
listOfNotNull(DescriptorToSourceUtilsIde.getAnyDeclaration(project, qualifierDescriptor))
qualifierDescriptor is PackageViewDescriptor ->
if (qualifierDescriptor.fqName != file.packageFqName) {
listOfNotNull(JavaPsiFacade.getInstance(project).findPackage(qualifierDescriptor.fqName.asString()))
} else listOf(file)
else ->
emptyList()
}
return targetParents.filter { it.canRefactor() }
}
internal fun getTargetParentsByCall(call: Call, context: BindingContext): List<PsiElement> {
val callElement = call.callElement
return when (val receiver = call.explicitReceiver) {
null -> getTargetParentsByQualifier(callElement, false, null)
is Qualifier -> getTargetParentsByQualifier(
callElement,
true,
context[BindingContext.REFERENCE_TARGET, receiver.referenceExpression]
)
is ReceiverValue -> getTargetParentsByQualifier(callElement, true, receiver.type.constructor.declarationDescriptor)
else -> throw AssertionError("Unexpected receiver: $receiver")
}
}
internal fun isInnerClassExpected(call: Call) = call.explicitReceiver is ReceiverValue
internal fun KtExpression.guessTypeForClass(context: BindingContext, moduleDescriptor: ModuleDescriptor) =
guessTypes(context, moduleDescriptor, coerceUnusedToUnit = false).singleOrNull()
internal fun KotlinType.toClassTypeInfo(): TypeInfo {
return TypeInfo.ByType(this, Variance.OUT_VARIANCE).noSubstitutions()
}
internal fun getClassKindFilter(expectedType: KotlinType, containingDeclaration: PsiElement): (ClassKind) -> Boolean {
if (expectedType.isAnyOrNullableAny()) {
return { _ -> true }
}
val descriptor = expectedType.constructor.declarationDescriptor ?: return { _ -> false }
val canHaveSubtypes = !(expectedType.constructor.isFinal || expectedType.containsStarProjections()) || expectedType.isUnit()
val isEnum = DescriptorUtils.isEnumClass(descriptor)
if (!(canHaveSubtypes || isEnum)
|| descriptor is TypeParameterDescriptor
) return { _ -> false }
return { classKind ->
when (classKind) {
ClassKind.ENUM_ENTRY -> isEnum && containingDeclaration == DescriptorToSourceUtils.descriptorToDeclaration(descriptor)
ClassKind.INTERFACE -> containingDeclaration !is PsiClass
|| (descriptor as? ClassDescriptor)?.kind == ClassDescriptorKind.INTERFACE
else -> canHaveSubtypes
}
}
}
internal fun KtSimpleNameExpression.getCreatePackageFixIfApplicable(targetParent: PsiElement): IntentionAction? {
val name = getReferencedName()
if (!name.checkPackageName()) return null
val basePackage: PsiPackage =
when (targetParent) {
is KtFile -> JavaPsiFacade.getInstance(targetParent.project).findPackage(targetParent.packageFqName.asString())
is PsiPackage -> targetParent
else -> null
}
?: return null
val baseName = basePackage.qualifiedName
val fullName = if (baseName.isNotEmpty()) "$baseName.$name" else name
val javaFix = CreateClassOrPackageFix.createFix(fullName, resolveScope, this, basePackage, null, null, null) ?: return null
return object : DelegatingIntentionAction(javaFix) {
override fun getFamilyName(): String = KotlinBundle.message("fix.create.from.usage.family")
override fun getText(): String = KotlinBundle.message("create.package.0", fullName)
}
}
data class UnsubstitutedTypeConstraintInfo(
val typeParameter: TypeParameterDescriptor,
private val originalSubstitution: Map<TypeConstructor, TypeProjection>,
val upperBound: KotlinType
) {
fun performSubstitution(vararg substitution: Pair<TypeConstructor, TypeProjection>): TypeConstraintInfo? {
val currentSubstitution = LinkedHashMap<TypeConstructor, TypeProjection>().apply {
this.putAll(originalSubstitution)
this.putAll(substitution)
}
val substitutedUpperBound = TypeSubstitutor.create(currentSubstitution).substitute(upperBound, Variance.INVARIANT) ?: return null
return TypeConstraintInfo(typeParameter, substitutedUpperBound)
}
}
data class TypeConstraintInfo(
val typeParameter: TypeParameterDescriptor,
val upperBound: KotlinType
)
fun getUnsubstitutedTypeConstraintInfo(element: KtTypeElement): UnsubstitutedTypeConstraintInfo? {
val context = element.analyze(BodyResolveMode.PARTIAL)
val containingTypeArg = (element.parent as? KtTypeReference)?.parent as? KtTypeProjection ?: return null
val argumentList = containingTypeArg.parent as? KtTypeArgumentList ?: return null
val containingTypeRef = (argumentList.parent as? KtTypeElement)?.parent as? KtTypeReference ?: return null
val containingType = containingTypeRef.getAbbreviatedTypeOrType(context) ?: return null
val baseType = containingType.constructor.declarationDescriptor?.defaultType ?: return null
val typeParameter = containingType.constructor.parameters.getOrNull(argumentList.arguments.indexOf(containingTypeArg))
val upperBound = typeParameter?.upperBounds?.singleOrNull() ?: return null
val substitution = getTypeSubstitution(baseType, containingType) ?: return null
return UnsubstitutedTypeConstraintInfo(typeParameter, substitution, upperBound)
}
fun getTypeConstraintInfo(element: KtTypeElement) = getUnsubstitutedTypeConstraintInfo(element)?.performSubstitution()
| apache-2.0 | e0467c6603ae88d6011fc3d4add1ecb7 | 48 | 158 | 0.769855 | 5.330275 | false | false | false | false |
sreich/ore-infinium | core/src/com/ore/infinium/systems/client/EntityOverlaySystem.kt | 1 | 9012 | /**
MIT License
Copyright (c) 2016 Shaun Reich <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.ore.infinium.systems.client
import com.artemis.BaseSystem
import com.artemis.annotations.Wire
import com.artemis.managers.TagManager
import com.badlogic.gdx.math.Vector2
import com.ore.infinium.Inventory
import com.ore.infinium.OreWorld
import com.ore.infinium.components.*
import com.ore.infinium.util.isInvalidEntity
import com.ore.infinium.util.mapper
import com.ore.infinium.util.opt
import com.ore.infinium.util.system
@Wire
class EntityOverlaySystem(private val oreWorld: OreWorld) : BaseSystem() {
private val mPlayer by mapper<PlayerComponent>()
private val mSprite by mapper<SpriteComponent>()
private val mItem by mapper<ItemComponent>()
private val mBlock by mapper<BlockComponent>()
private val mTool by mapper<ToolComponent>()
private val powerOverlayRenderSystem by system<PowerOverlayRenderSystem>()
private val tagManager by system<TagManager>()
override fun initialize() {
createCrosshair()
}
private fun createCrosshair() {
val crosshair = getWorld().create()
tagManager.register(OreWorld.s_crosshair, crosshair)
val cSprite = mSprite.create(crosshair).apply {
sprite.setSize(1f, 1f)
sprite.setRegion(oreWorld.atlas.findRegion("crosshair-blockpicking"))
textureName = "crosshair-blockpicking"
noClip = true
}
}
private var crosshairShown: Boolean = false
/// this overlay actually gets deleted/recloned from the inventory item, each switch
private var itemPlacementOverlayExists: Boolean = false
private var initialized: Boolean = false
private fun slotSelected(index: Int, inventory: Inventory) {
val mainPlayer = tagManager.getEntity(OreWorld.s_mainPlayer).id
val cPlayer = mPlayer.get(mainPlayer)
val equippedPrimaryItem = cPlayer.equippedPrimaryItem
//we hide/delete it either way, because we'll either (a) respawn it if it when it needs it
//or (b) it doesn't want to be shown
deletePlacementOverlay()
//inventory is empty, we don't show crosshair or item overlay
if (isInvalidEntity(equippedPrimaryItem)) {
return
}
if (tryShowCrosshair(equippedPrimaryItem)) {
return
}
maybeShowPlacementOverlay(equippedPrimaryItem)
}
private fun maybeShowPlacementOverlay(equippedPrimaryItem: Int) {
//placement overlay shoudln't be visible if the power overlay is, so never create it in the first place
if (powerOverlayRenderSystem.overlayVisible) {
return
}
//this item is placeable, show an overlay of it so we can see where we're going to place it (by cloning its
// entity)
val newPlacementOverlay = oreWorld.cloneEntity(equippedPrimaryItem)
val cItem = mItem.get(newPlacementOverlay).apply {
//transition to the in world state, since the cloned source item was in the inventory state, so to would this
state = ItemComponent.State.InWorldState
}
val cSprite = mSprite.get(newPlacementOverlay).apply {
noClip = true
}
tagManager.register(OreWorld.s_itemPlacementOverlay, newPlacementOverlay)
itemPlacementOverlayExists = true
}
private fun deletePlacementOverlay() {
if (itemPlacementOverlayExists) {
assert(tagManager.isRegistered(OreWorld.s_itemPlacementOverlay))
val placementOverlay = tagManager.getEntity(OreWorld.s_itemPlacementOverlay)
getWorld().delete(placementOverlay.id)
itemPlacementOverlayExists = false
}
}
private fun tryShowCrosshair(equippedPrimaryEntity: Int): Boolean {
val crosshairSprite = mSprite.get(tagManager.getEntity(OreWorld.s_crosshair).id)
assert(crosshairSprite.noClip)
// if the switched to item is a block, we should show a crosshair overlay
if (mBlock.has(equippedPrimaryEntity)) {
crosshairShown = true
crosshairSprite.visible = true
//don't show the placement overlay for blocks, just items and other placeable things
return true
}
val entityToolComponent = mTool.opt(equippedPrimaryEntity)
if (entityToolComponent != null) {
if (entityToolComponent.type == ToolComponent.ToolType.Drill) {
//drill, one of the few cases we want to show the block crosshair...
crosshairShown = true
crosshairSprite.visible = true
return true
}
}
crosshairShown = false
crosshairSprite.visible = false
return false
}
override fun dispose() {
}
override fun begin() {
}
override fun processSystem() {
// batch.setProjectionMatrix(oreWorld.camera.combined);
if (!initialized && oreWorld.client!!.hotbarInventory != null) {
oreWorld.client!!.hotbarInventory!!.addListener(object : Inventory.SlotListener {
override fun slotItemSelected(index: Int, inventory: Inventory) {
slotSelected(index, inventory)
}
})
initialized = true
}
if (initialized) {
updateItemOverlay()
updateCrosshair()
}
//////////////////////ERROR
}
private fun updateCrosshair() {
val cSprite = mSprite.get(tagManager.getEntity(OreWorld.s_crosshair).id)
val mouse = oreWorld.mousePositionWorldCoords()
// OreWorld.BLOCK_SIZE * (mouse.y / OreWorld.BLOCK_SIZE).floor());
val crosshairPosition = Vector2(mouse)
//fixme this might not work..remove above dead code too
oreWorld.alignPositionToBlocks(crosshairPosition, Vector2(cSprite.sprite.width,
cSprite.sprite.height))
val crosshairOriginOffset = Vector2(cSprite.sprite.width, cSprite.sprite.height)
//new Vector2(cSprite.sprite.getWidth() * 0.5f, cSprite.sprite.getHeight() * 0.5f);
val crosshairFinalPosition = crosshairPosition.add(crosshairOriginOffset)
cSprite.sprite.setPosition(crosshairFinalPosition.x, crosshairFinalPosition.y)
}
private fun updateItemOverlay() {
val entity = tagManager.getEntity(OreWorld.s_itemPlacementOverlay) ?: return
val itemPlacementOverlayEntity = entity.id
val cSprite = mSprite.get(itemPlacementOverlayEntity)
val mouse = oreWorld.mousePositionWorldCoords()
oreWorld.alignPositionToBlocks(mouse, Vector2(cSprite.sprite.width,
cSprite.sprite.height))
val halfWidth = 0.0f//cSprite.sprite.getWidth() * 0.5f;
val halfHeight = 0.0f//cSprite.sprite.getHeight() * 0.5f;
cSprite.sprite.setPosition(mouse.x + halfWidth, mouse.y + halfHeight)
cSprite.placementValid = oreWorld.isPlacementValid(itemPlacementOverlayEntity)
}
/**
* sets the overlays visible or not. only toggles the overall hiding.
* if they don't exist for whatever reason, this method will not
* do anything to them.
* @param visible
*/
fun setOverlaysVisible(visible: Boolean) {
setPlacementOverlayVisible(visible)
setCrosshairVisible(visible)
}
private fun setCrosshairVisible(visible: Boolean) {
//getWorld().getSystem(TagManager.class).getEntity(OreWorld.s_crosshair);
}
fun setPlacementOverlayVisible(visible: Boolean) {
//if item placement overlay doesn't exist, no need to hide it
if (itemPlacementOverlayExists) {
val entity = tagManager.getEntity(OreWorld.s_itemPlacementOverlay).id
mSprite.get(entity).visible = visible
}
}
}
| mit | 3888a1e0216936b74a855afe29603758 | 35.634146 | 121 | 0.673768 | 4.895166 | false | false | false | false |
phylame/jem | imabw/src/main/kotlin/jem/imabw/Models.kt | 1 | 16739 | /*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* 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 jem.imabw
import javafx.concurrent.Task
import javafx.geometry.VPos
import javafx.scene.control.Alert
import javafx.scene.control.ButtonType
import javafx.scene.control.Label
import javafx.scene.layout.GridPane
import jclp.EventAction
import jclp.EventBus
import jclp.TypeManager
import jclp.io.*
import jclp.log.Log
import jclp.looseISODateTime
import jclp.text.or
import jclp.text.remove
import jem.Book
import jem.Chapter
import jem.asBook
import jem.epm.*
import jem.imabw.ui.*
import jem.title
import mala.App
import mala.App.optTr
import mala.App.tr
import mala.ixin.CommandHandler
import mala.ixin.IxIn
import mala.ixin.initAsForm
import mala.ixin.initAsInfo
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
private const val SWAP_SUFFIX = ".tmp"
enum class ModificationType {
ATTRIBUTE_MODIFIED,
EXTENSIONS_MODIFIED,
CONTENTS_MODIFIED,
TEXT_MODIFIED
}
data class ModificationEvent(val chapter: Chapter, val what: ModificationType, val count: Int = 1)
enum class WorkflowType {
BOOK_OPENED,
BOOK_CREATED,
BOOK_MODIFIED,
BOOK_CLOSED,
BOOK_SAVED
}
data class WorkflowEvent(val book: Book, val what: WorkflowType)
object Workbench : CommandHandler {
var work: Work? = null
private set
init {
History // init history
Imabw.register(this)
}
fun activateWork(work: Work) {
val last = this.work
require(work !== last) { "work is already activated" }
this.work = work.apply {
path?.let { History.remove(it) }
}
last?.apply {
path?.let { History.insert(it) }
EventBus.post(WorkflowEvent(book, WorkflowType.BOOK_CLOSED))
cleanup()
}
IxIn.actionMap.apply {
this["saveFile"]?.isDisable = work.path != null
this["fileDetails"]?.isDisable = work.path == null
}
}
fun ensureSaved(title: String, block: () -> Unit) {
val work = work
if (work == null) {
block()
} else if (!work.isModified) {
block()
} else with(alert(Alert.AlertType.CONFIRMATION, title, tr("d.askSave.hint", work.book.title))) {
buttonTypes.setAll(ButtonType.CANCEL, ButtonType.YES, ButtonType.NO)
when (showAndWait().get()) {
ButtonType.YES -> saveFile(block)
ButtonType.NO -> block()
}
}
}
fun newBook(title: String) {
with(Imabw.fxApp) {
showProgress()
activateWork(Work(Book(title)))
EventBus.post(WorkflowEvent(work!!.book, WorkflowType.BOOK_CREATED))
Imabw.message(tr("d.newBook.success", title))
hideProgress()
}
}
fun openBook(param: ParserParam) {
work?.path?.let {
if (Paths.get(it) == Paths.get(param.path)) {
Log.w("openBook") { "'${param.path} is already opened'" }
return
}
}
val parser = EpmManager[param.epmName]?.parser
if (parser != null) {
if (parser is FileParser && !File(param.path).exists()) {
error(tr("d.openBook.title"), tr("err.file.notFound", param.path))
History.remove(param.path)
return
}
} else {
error(tr("d.openBook.title"), tr("err.jem.unsupported", param.epmName))
return
}
with(LoadBookTask(param)) {
setOnSucceeded {
activateWork(Work(value, param))
EventBus.post(WorkflowEvent(work!!.book, WorkflowType.BOOK_OPENED))
Imabw.message(tr("jem.openBook.success", param.path))
hideProgress()
}
Imabw.submit(this)
}
}
fun saveBook(param: MakerParam, done: (() -> Unit)? = null) {
val work = work!!
require(param.book === work.book) { "book to save is not current book" }
work.inParam?.path?.let {
if (File(it) == File(param.actualPath)) {
error(tr("d.saveBook.title"), tr("err.file.opened", param.actualPath))
return
}
}
if (EpmManager[param.epmName]?.hasMaker != true) {
error(tr("d.saveBook.title"), tr("err.jem.unsupported", param.epmName))
return
}
val task = object : MakeBookTask(param) {
override fun call(): String {
EditorPane.cacheTabs(this.param.book)
return makeBook(this.param)
}
}
task.setOnRunning {
task.updateProgress(tr("jem.makeBook.hint", param.book.title, param.actualPath.remove(SWAP_SUFFIX)))
}
task.setOnSucceeded {
work.outParam = param
work.resetModifications()
IxIn.actionMap["saveFile"]?.isDisable = true
IxIn.actionMap["fileDetails"]?.isDisable = false
EventBus.post(WorkflowEvent(work.book, WorkflowType.BOOK_SAVED))
Imabw.message(tr("jem.saveBook.success", param.book.title, work.path))
task.hideProgress()
done?.invoke()
}
Imabw.submit(task)
}
fun exportBook(chapter: Chapter) {
val (file, format) = saveBookFile(chapter.title, Imabw.topWindow) ?: return
work?.path?.let {
if (File(it) == file) {
error(tr("d.saveBook.title"), tr("err.file.opened", file))
return
}
}
val task = object : MakeBookTask(MakerParam(chapter.asBook(), file.path, format, defaultMakerSettings())) {
override fun call(): String {
EditorPane.cacheTabs(this.param.book)
return makeBook(this.param)
}
}
Imabw.submit(task)
}
fun exportBooks(chapters: Collection<Chapter>) {
if (chapters.isEmpty()) return
if (chapters.size == 1) {
exportBook(chapters.first())
return
}
val dir = selectDirectory(tr("d.exportBook.title"), Imabw.topWindow) ?: return
val fxApp = Imabw.fxApp.apply { showProgress() }
val ignored = ArrayList<String>(4)
val succeed = Vector<String>(chapters.size)
val failed = Vector<String>(0)
val opened = work!!.path?.let(::File)
val counter = AtomicInteger()
for (chapter in chapters) {
val path = "${dir.path}/${chapter.title}.$PMAB_NAME"
if (opened != null && opened == File(path)) {
counter.incrementAndGet()
ignored += path
continue
}
val param = MakerParam(chapter.asBook(), path, PMAB_NAME, defaultMakerSettings())
val task = object : Task<String>() {
override fun call() = makeBook(param)
}
task.setOnRunning {
fxApp.updateProgress(tr("jem.makeBook.hint", param.book.title, param.actualPath))
}
task.setOnSucceeded {
succeed += param.actualPath
if (counter.incrementAndGet() == chapters.size) {
fxApp.hideProgress()
showExportResult(succeed, ignored, failed)
}
}
task.setOnFailed {
failed += param.actualPath
Log.d("exportBook", task.exception) { "failed to make book: ${param.path}" }
if (counter.incrementAndGet() == chapters.size) {
fxApp.hideProgress()
showExportResult(succeed, ignored, failed)
}
}
Imabw.submit(task)
}
if (ignored.size == chapters.size) { // all ignored
fxApp.hideProgress()
showExportResult(succeed, ignored, failed)
}
}
internal fun start() {
val path = App.arguments.firstOrNull()?.let { Paths.get(it) }
if (path != null && Files.isRegularFile(path)) {
openFile(path.toString())
} else {
newBook(tr("jem.book.untitled"))
}
}
internal fun dispose() {
work?.apply {
path?.let { History.insert(it) }
cleanup()
}
History.sync()
}
internal fun openFile(path: String) {
ensureSaved(tr("d.openBook.title")) {
if (path.isEmpty()) {
openBookFile(Imabw.topWindow)?.let { openBook(ParserParam(it.path)) }
} else {
val file = Paths.get(path).toAbsolutePath()
openBook(ParserParam(if (file.exists) file.normalize().toString() else path))
}
}
}
private fun saveFile(done: (() -> Unit)? = null) {
val work = work!!
check(work.isModified || work.path == null) { "book is not modified" }
var outParam = work.outParam
if (outParam == null) {
val inParam = work.inParam
val output = if (inParam?.epmName != PMAB_NAME) {
saveBookFile(work.book.title, PMAB_NAME, Imabw.topWindow)?.first?.path ?: return
} else { // save pmab to temp file
inParam.path + SWAP_SUFFIX
}
outParam = MakerParam(work.book, output, PMAB_NAME, defaultMakerSettings())
}
saveBook(outParam, done)
}
private fun showExportResult(succeed: List<String>, ignored: List<String>, failed: List<String>) {
with(alert(Alert.AlertType.INFORMATION, tr("d.exportBook.title"), "")) {
width = owner.width * 0.5
dialogPane.content = GridPane().apply {
val legend = Label(tr("d.exportBook.result")).apply {
style = "-fx-font-weight: bold;"
}
add(legend, 0, 0, 2, 1)
initAsForm(listOf(
Label(tr("d.exportBook.succeed")),
Label(tr("d.exportBook.ignored")),
Label(tr("d.exportBook.failed"))
), listOf(
Label(succeed.joinToString("\n") or { tr("misc.empty") }),
Label(ignored.joinToString("\n") or { tr("misc.empty") }),
Label(failed.joinToString("\n") or { tr("misc.empty") })
), 1, VPos.TOP)
}
showAndWait()
}
}
private fun showDetails() {
val work = requireNotNull(work) { "work is null" }
val epmName = work.outParam?.epmName ?: work.inParam?.epmName ?: return
val epmFactory = EpmManager[epmName]
val items = arrayListOf<Any?>()
if (epmFactory is FileParser) {
val path = Paths.get(work.path)
items.add(tr("d.fileDetails.name"))
items.add(path.fileName)
items.add(tr("d.fileDetails.location"))
items.add(path.parent)
items.add(tr("d.fileDetails.size"))
items.add(printableSize(path.size))
items.add(tr("d.fileDetails.lastModified"))
items.add(path.lastModified.toLocalDateTime().format(looseISODateTime))
items.add(null)
items.add(tr("d.fileDetails.format"))
items.add(epmName)
@Suppress("UNCHECKED_CAST")
(work.book.extensions[EXT_EPM_METADATA] as? Map<Any, Any>)?.let {
for (entry in it) {
items.add(optTr("name.jem.meta.${entry.key}") or entry.key.toString().capitalize())
items.add(TypeManager.printable(entry.value) ?: entry.value.toString())
}
}
var firstTime = true
for (entry in work.book.extensions) {
if (entry.key.startsWith("jem.ext.crawler.")) {
if (firstTime) {
items.add(null)
firstTime = false
}
val key = entry.key.removePrefix("jem.ext.crawler.")
items.add(optTr("name.jem.crawler.$key") or key.capitalize())
items.add(TypeManager.printable(entry.value) ?: entry.value.toString())
}
}
with(alert(Alert.AlertType.NONE, tr("d.fileDetails.title", work.book.title), "", Imabw.topWindow)) {
buttonTypes.setAll(ButtonType.CLOSE)
dialogPane.content = GridPane().apply {
initAsInfo(items.iterator(), Imabw.dashboard)
}
showAndWait()
}
} else {
}
}
override fun handle(command: String, source: Any): Boolean {
when (command) {
"exit" -> ensureSaved(tr("d.exit.title")) { App.exit() }
"newFile" -> ensureSaved(tr("d.newBook.title")) {
input(tr("d.newBook.title"), tr("d.newBook.label"), tr("jem.book.untitled"))?.let {
newBook(it)
}
}
"openFile" -> openFile("")
"saveFile" -> saveFile()
"saveAsFile" -> exportBook(work!!.book)
"fileDetails" -> showDetails()
"clearHistory" -> History.clear()
else -> return false
}
return true
}
}
class Work(val book: Book, val inParam: ParserParam? = null) : EventAction<ModificationEvent> {
val isModified get() = modifications.values.any { it.isModified }
var path = inParam?.path
private set
var outParam: MakerParam? = null
set(value) {
path = value?.actualPath?.remove(SWAP_SUFFIX)
field = value
}
private val modifications = IdentityHashMap<Chapter, Modification>()
init {
EventBus.register(this)
}
internal fun cleanup() {
EventBus.unregistere(this)
Imabw.submit {
book.cleanup()
adjustOutput()
}
}
internal fun resetModifications() {
modifications.values.forEach { it.reset() }
}
// rename *.pmab.swp to *.pmab
private fun adjustOutput() {
outParam?.actualPath?.takeIf { it.endsWith(SWAP_SUFFIX) }?.let { tmp ->
val swap = File(tmp)
if (!swap.exists()) {
Log.t("Work") { "no swap file found" }
return
}
File(tmp.substring(0, tmp.length - SWAP_SUFFIX.length)).apply {
if (!delete() || !swap.renameTo(this)) {
Log.e("Work") { "cannot rename '$tmp' to '$this'" }
}
}
}
}
private fun notifyModified() {
IxIn.actionMap["saveFile"]?.isDisable = !isModified
EventBus.post(WorkflowEvent(book, WorkflowType.BOOK_MODIFIED))
}
override fun invoke(e: ModificationEvent) {
val m = modifications.getOrPut(e.chapter) { Modification() }
when (e.what) {
ModificationType.ATTRIBUTE_MODIFIED -> m.attributes += e.count
ModificationType.EXTENSIONS_MODIFIED -> m.extensions += e.count
ModificationType.CONTENTS_MODIFIED -> m.contents += e.count
ModificationType.TEXT_MODIFIED -> m.text += e.count
}
notifyModified()
}
private class Modification {
var text = 0
var contents = 0
set(value) {
if (value != 0) println("contents modified")
field = value
}
var attributes = 0
set(value) {
if (value != 0) println("attributes modified")
field = value
}
var extensions = 0
set(value) {
if (value != 0) println("extensions modified")
field = value
}
val isModified get() = attributes > 0 || extensions > 0 || contents > 0 || text > 0
fun reset() {
text = 0
contents = 0
attributes = 0
extensions = 0
}
}
}
| apache-2.0 | 684fc7afb2c41271efab47a3c6f7121a | 33.371663 | 115 | 0.545074 | 4.38079 | false | false | false | false |
sreich/ore-infinium | core/src/com/ore/infinium/OreEntityFactory.kt | 1 | 8514 | package com.ore.infinium
import com.artemis.ComponentMapper
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Vector2
import com.ore.infinium.components.*
import com.ore.infinium.systems.server.TileLightingSystem
import java.util.*
class OreEntityFactory(val oreWorld: OreWorld) {
private lateinit var mAi: ComponentMapper<AIComponent>
private lateinit var mPlayer: ComponentMapper<PlayerComponent>
private lateinit var mDoor: ComponentMapper<DoorComponent>
private lateinit var mSprite: ComponentMapper<SpriteComponent>
private lateinit var mControl: ComponentMapper<ControllableComponent>
private lateinit var mItem: ComponentMapper<ItemComponent>
private lateinit var mVelocity: ComponentMapper<VelocityComponent>
private lateinit var mJump: ComponentMapper<JumpComponent>
private lateinit var mBlock: ComponentMapper<BlockComponent>
private lateinit var mTool: ComponentMapper<ToolComponent>
private lateinit var mAir: ComponentMapper<AirComponent>
private lateinit var mHealth: ComponentMapper<HealthComponent>
private lateinit var mLight: ComponentMapper<LightComponent>
private lateinit var mFlora: ComponentMapper<FloraComponent>
private lateinit var mPowerDevice: ComponentMapper<PowerDeviceComponent>
private lateinit var mPowerConsumer: ComponentMapper<PowerConsumerComponent>
private lateinit var mPowerGenerator: ComponentMapper<PowerGeneratorComponent>
val artemisWorld = oreWorld.artemisWorld
init {
oreWorld.artemisWorld.inject(this, true)
}
/**
* @param blockType
*/
fun createBlockItem(blockType: Byte): Int {
val entity = artemisWorld.create()
mVelocity.create(entity)
val cBlock = mBlock.create(entity)
cBlock.blockType = blockType
mSprite.create(entity).apply {
textureName = OreBlock.blockAttributes[cBlock.blockType]!!.textureName
sprite.setSize(1f, 1f)
}
mItem.create(entity).apply {
stackSize = 800
maxStackSize = 800
name = OreBlock.nameOfBlockType(blockType)!!
}
return entity
}
fun createLiquidGun(): Int {
val entity = artemisWorld.create()
mVelocity.create(entity)
mTool.create(entity).apply {
type = ToolComponent.ToolType.Bucket
attackIntervalMs = 100
}
mSprite.create(entity).apply {
textureName = "drill"
sprite.setSize(2f, 2f)
}
val newStackSize = 1
mItem.create(entity).apply {
stackSize = newStackSize
maxStackSize = newStackSize
name = "Liquid Gun"
}
return entity
}
fun createLight(): Int {
val entity = artemisWorld.create()
mVelocity.create(entity)
mItem.create(entity).apply {
stackSize = 800
maxStackSize = 900
name = "Light"
}
mLight.create(entity).apply {
radius = TileLightingSystem.MAX_TILE_LIGHT_LEVEL.toInt()
}
mPowerDevice.create(entity)
mSprite.create(entity).apply {
textureName = "light-yellow"
sprite.setSize(1f, 1f)
}
mPowerConsumer.create(entity).apply {
powerDemandRate = 100
}
return entity
}
fun createDoor(): Int {
val entity = artemisWorld.create()
mVelocity.create(entity)
mDoor.create(entity)
mItem.create(entity).apply {
stackSize = 50
maxStackSize = 60
name = "Door"
placementAdjacencyHints = EnumSet.of(
ItemComponent.PlacementAdjacencyHints.BottomSolid,
ItemComponent.PlacementAdjacencyHints.TopSolid)
}
mSprite.create(entity).apply {
textureName = "door-closed-16x36"
sprite.setSize(1f, 3f)
}
return entity
}
fun createPowerGenerator(): Int {
val entity = artemisWorld.create()
mVelocity.create(entity)
mItem.create(entity).apply {
stackSize = 800
maxStackSize = 900
name = "Power Generator"
}
mPowerDevice.create(entity)
mSprite.create(entity).apply {
textureName = "air-generator-64x64"
sprite.setSize(4f, 4f)
}
mPowerGenerator.create(entity).apply {
supplyRateEU = 100
fuelSources = GeneratorInventory(GeneratorInventory.MAX_SLOTS, artemisWorld)
artemisWorld.inject(fuelSources, true)
}
return entity
}
fun createExplosive(): Int {
val entity = artemisWorld.create()
mVelocity.create(entity)
mTool.create(entity).apply {
type = ToolComponent.ToolType.Explosive
blockDamage = 400f
explosiveRadius = 10
}
mSprite.create(entity).apply {
textureName = "drill"
sprite.setSize(2f, 2f)
}
val newStackSize = 64000
mItem.create(entity).apply {
stackSize = newStackSize
maxStackSize = newStackSize
name = "Explosives"
}
return entity
}
fun createBunny(): Int {
val entity = artemisWorld.create()
val cSprite = mSprite.create(entity)
mVelocity.create(entity)
cSprite.apply {
sprite.setSize(2f, 3f)
textureName = "bunny1-stand"
category = SpriteComponent.EntityCategory.Character
}
mControl.create(entity)
mJump.create(entity)
mHealth.create(entity).apply {
health = maxHealth
}
mAir.create(entity).apply {
air = maxAir
}
mAi.create(entity)
return entity
}
/**
* @param playerName
* *
* @param connectionId
* *
* *
* @return
*/
fun createPlayer(playerName: String, connectionId: Int): Int {
val entity = artemisWorld.create()
val cSprite = mSprite.create(entity)
mVelocity.create(entity)
val cPlayer = mPlayer.create(entity).apply {
connectionPlayerId = connectionId
loadedViewport.rect = Rectangle(0f, 0f, LoadedViewport.MAX_VIEWPORT_WIDTH.toFloat(),
LoadedViewport.MAX_VIEWPORT_HEIGHT.toFloat())
loadedViewport.centerOn(Vector2(cSprite.sprite.x, cSprite.sprite.y), world = oreWorld)
}
cPlayer.playerName = playerName
cSprite.apply {
sprite.setSize(2f, 3f)
textureName = "player1Standing1"
category = SpriteComponent.EntityCategory.Character
}
mControl.create(entity)
mJump.create(entity)
mHealth.create(entity).apply {
health = maxHealth
}
mAir.create(entity).apply {
air = maxAir
}
return entity
}
fun createDrill(): Int {
val entity = artemisWorld.create()
mVelocity.create(entity)
mTool.create(entity).apply {
type = ToolComponent.ToolType.Drill
blockDamage = 400f
}
mSprite.create(entity).apply {
textureName = "drill"
sprite.setSize(2f, 2f)
}
val newStackSize = 64000
mItem.create(entity).apply {
stackSize = newStackSize
maxStackSize = newStackSize
name = "Drill"
}
return entity
}
fun createWoodenTree(type: FloraComponent.TreeSize): Int {
val entity = artemisWorld.create()
val sprite = mSprite.create(entity)
val flora = mFlora.create(entity)
mVelocity.create(entity)
mItem.create(entity).apply {
state = ItemComponent.State.InWorldState
maxStackSize = 64
name = "Tree"
}
when (type) {
FloraComponent.TreeSize.Large -> {
sprite.textureName = "flora/tree-02"
sprite.sprite.setSize(5f, 13f)
flora.numberOfDropsWhenDestroyed = 4
flora.stackSizePerDrop = 2
}
else -> {
//undefined
}
}
mHealth.create(entity).apply {
maxHealth = 2000f
health = maxHealth
}
return entity
}
}
| mit | 61c2c76745d084483526c459e1141123 | 26.028571 | 98 | 0.592319 | 4.867925 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/athena/src/main/kotlin/com/kotlin/athena/StartQueryExample.kt | 1 | 4802 | // snippet-sourcedescription:[StartQueryExample.kt demonstrates how to submit a query to Amazon Athena for execution, wait until the results are available, and then process the results.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-keyword:[Amazon Athena]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.athena
// snippet-start:[athena.kotlin.StartQueryExample.import]
import aws.sdk.kotlin.services.athena.AthenaClient
import aws.sdk.kotlin.services.athena.model.GetQueryExecutionRequest
import aws.sdk.kotlin.services.athena.model.GetQueryResultsRequest
import aws.sdk.kotlin.services.athena.model.QueryExecutionContext
import aws.sdk.kotlin.services.athena.model.QueryExecutionState
import aws.sdk.kotlin.services.athena.model.ResultConfiguration
import aws.sdk.kotlin.services.athena.model.Row
import aws.sdk.kotlin.services.athena.model.StartQueryExecutionRequest
import kotlinx.coroutines.delay
import kotlin.system.exitProcess
// snippet-end:[athena.kotlin.StartQueryExample.import]
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<queryString> <database> <outputLocation>
Where:
queryString - The query string to use (for example, "SELECT * FROM mydatabase"; ).
database - The name of the database to use (for example, mydatabase ).
outputLocation - The output location (for example, the name of an Amazon S3 bucket - s3://mybucket).
"""
if (args.size != 3) {
println(usage)
exitProcess(0)
}
val queryString = args[0]
val database = args[1]
val outputLocation = args[2]
val queryExecutionId = submitAthenaQuery(queryString, database, outputLocation)
waitForQueryToComplete(queryExecutionId)
processResultRows(queryExecutionId)
}
// snippet-start:[athena.kotlin.StartQueryExample.main]
suspend fun submitAthenaQuery(queryStringVal: String, databaseVal: String, outputLocationVal: String): String? {
// The QueryExecutionContext allows us to set the database.
val queryExecutionContextOb = QueryExecutionContext {
database = databaseVal
}
// The result configuration specifies where the results of the query should go.
val resultConfigurationOb = ResultConfiguration {
outputLocation = outputLocationVal
}
val request = StartQueryExecutionRequest {
queryString = queryStringVal
queryExecutionContext = queryExecutionContextOb
resultConfiguration = resultConfigurationOb
}
AthenaClient { region = "us-west-2" }.use { athenaClient ->
val response = athenaClient.startQueryExecution(request)
return response.queryExecutionId
}
}
// Wait for an Amazon Athena query to complete, fail or to be cancelled.
suspend fun waitForQueryToComplete(queryExecutionIdVal: String?) {
var isQueryStillRunning = true
while (isQueryStillRunning) {
val request = GetQueryExecutionRequest {
queryExecutionId = queryExecutionIdVal
}
AthenaClient { region = "us-west-2" }.use { athenaClient ->
val response = athenaClient.getQueryExecution(request)
val queryState = response.queryExecution?.status?.state.toString()
if (queryState == QueryExecutionState.Succeeded.toString()) {
isQueryStillRunning = false
} else {
// Sleep an amount of time before retrying again.
delay(1000)
}
println("The current status is: $queryState")
}
}
}
// This code retrieves the results of a query.
suspend fun processResultRows(queryExecutionIdVal: String?) {
val request = GetQueryResultsRequest {
queryExecutionId = queryExecutionIdVal
}
AthenaClient { region = "us-west-2" }.use { athenaClient ->
val getQueryResultsResults = athenaClient.getQueryResults(request)
val results = getQueryResultsResults.resultSet
for (result in listOf(results)) {
val columnInfoList = result?.resultSetMetadata?.columnInfo
val response = result?.rows
if (response != null) {
if (columnInfoList != null) {
processRow(response)
}
}
}
}
}
private fun processRow(row: List<Row>) {
for (myRow in row) {
val allData = myRow.data
if (allData != null) {
for (data in allData) {
println("The value of the column is " + data.varCharValue)
}
}
}
}
// snippet-end:[athena.kotlin.StartQueryExample.main]
| apache-2.0 | 06a932ed5a291ee1bfeaa21db92b6988 | 34.378788 | 186 | 0.666805 | 4.666667 | false | false | false | false |
RockinRoel/FrameworkBenchmarks | frameworks/Kotlin/http4k/core/src/main/kotlin/WorldRoutes.kt | 13 | 1325 | import org.http4k.core.Body
import org.http4k.core.Method.GET
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.core.with
import org.http4k.format.Jackson.array
import org.http4k.format.Jackson.json
import org.http4k.lens.Query
import org.http4k.routing.RoutingHttpHandler
import org.http4k.routing.bind
import kotlin.math.max
import kotlin.math.min
object WorldRoutes {
private val jsonBody = Body.json().toLens()
private val numberOfQueries = Query.map {
try {
min(max(it.toInt(), 1), 500)
} catch (e: Exception) {
1
}
}.defaulted("queries", 1)
fun queryRoute(db: Database) = "/db" bind GET to {
let { Response(OK).with(jsonBody of db.findWorld()) }
}
fun multipleRoute(db: Database) = "/queries" bind GET to {
Response(OK).with(jsonBody of array(db.findWorlds(numberOfQueries(it))))
}
fun cachedRoute(db: Database): RoutingHttpHandler {
val cachedDb = CachedDatabase(db)
return "/cached" bind GET to {
Response(OK).with(jsonBody of array(cachedDb.findWorlds(numberOfQueries(it))))
}
}
fun updateRoute(db: Database) = "/updates" bind GET to {
Response(OK).with(jsonBody of array(db.updateWorlds(numberOfQueries(it))))
}
} | bsd-3-clause | 58892ed64ef1272bbc7ea2d78c90681c | 29.136364 | 90 | 0.672453 | 3.552279 | false | false | false | false |
android/privacy-codelab | PhotoLog_start/src/main/java/com/example/photolog_start/MediaRepository.kt | 1 | 2996 | /*
* Copyright (C) 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.example.photolog_start
import android.content.ContentUris
import android.content.Context
import android.net.Uri
import android.provider.MediaStore
import android.provider.MediaStore.Files.FileColumns.DATA
import android.provider.MediaStore.Files.FileColumns.DATE_ADDED
import android.provider.MediaStore.Files.FileColumns.DISPLAY_NAME
import android.provider.MediaStore.Files.FileColumns.MIME_TYPE
import android.provider.MediaStore.Files.FileColumns.SIZE
import android.provider.MediaStore.Files.FileColumns._ID
import kotlinx.coroutines.flow.flow
import java.io.File
class MediaRepository(private val context: Context) {
data class MediaEntry(
val uri: Uri,
val filename: String,
val mimeType: String,
val size: Long,
val path: String
) {
val file: File
get() = File(path)
}
fun fetchImages() = flow {
val externalContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val projection = arrayOf(
_ID,
DISPLAY_NAME,
SIZE,
MIME_TYPE,
DATA,
)
val cursor = context.contentResolver.query(
externalContentUri,
projection,
null,
null,
"$DATE_ADDED DESC"
) ?: throw Exception("Query could not be executed")
cursor.use {
while (cursor.moveToNext()) {
val idColumn = cursor.getColumnIndexOrThrow(_ID)
val displayNameColumn = cursor.getColumnIndexOrThrow(DISPLAY_NAME)
val sizeColumn = cursor.getColumnIndexOrThrow(SIZE)
val mimeTypeColumn = cursor.getColumnIndexOrThrow(MIME_TYPE)
val dataColumn = cursor.getColumnIndexOrThrow(DATA)
val contentUri = ContentUris.withAppendedId(
externalContentUri,
cursor.getLong(idColumn)
)
emit(
MediaEntry(
uri = contentUri,
filename = cursor.getString(displayNameColumn),
size = cursor.getLong(sizeColumn),
mimeType = cursor.getString(mimeTypeColumn),
path = cursor.getString(dataColumn),
)
)
}
}
}
} | apache-2.0 | 57f29611b54ed523cfdf56dd4a4d550a | 33.056818 | 82 | 0.623832 | 4.976744 | false | false | false | false |
ThePreviousOne/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsGeneralFragment.kt | 1 | 5119 | package eu.kanade.tachiyomi.ui.setting
import android.os.Bundle
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceFragmentCompat
import android.support.v7.preference.XpPreferenceFragment
import android.view.View
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.library.LibraryUpdateJob
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.util.plusAssign
import eu.kanade.tachiyomi.widget.preference.IntListPreference
import eu.kanade.tachiyomi.widget.preference.LibraryColumnsDialog
import eu.kanade.tachiyomi.widget.preference.SimpleDialogPreference
import net.xpece.android.support.preference.MultiSelectListPreference
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import uy.kohesive.injekt.injectLazy
class SettingsGeneralFragment : SettingsFragment(),
PreferenceFragmentCompat.OnPreferenceDisplayDialogCallback {
companion object {
fun newInstance(rootKey: String): SettingsGeneralFragment {
val args = Bundle()
args.putString(XpPreferenceFragment.ARG_PREFERENCE_ROOT, rootKey)
return SettingsGeneralFragment().apply { arguments = args }
}
}
private val preferences: PreferencesHelper by injectLazy()
private val db: DatabaseHelper by injectLazy()
val columnsPreference: SimpleDialogPreference by bindPref(R.string.pref_library_columns_dialog_key)
val updateInterval: IntListPreference by bindPref(R.string.pref_library_update_interval_key)
val updateRestriction: MultiSelectListPreference by bindPref(R.string.pref_library_update_restriction_key)
val themePreference: IntListPreference by bindPref(R.string.pref_theme_key)
val categoryUpdate: MultiSelectListPreference by bindPref(R.string.pref_library_update_categories_key)
override fun onViewCreated(view: View, savedState: Bundle?) {
super.onViewCreated(view, savedState)
subscriptions += preferences.libraryUpdateInterval().asObservable()
.subscribe { updateRestriction.isVisible = it > 0 }
subscriptions += Observable.combineLatest(
preferences.portraitColumns().asObservable(),
preferences.landscapeColumns().asObservable())
{ portraitColumns, landscapeColumns -> Pair(portraitColumns, landscapeColumns) }
.subscribe { updateColumnsSummary(it.first, it.second) }
updateInterval.setOnPreferenceChangeListener { preference, newValue ->
val interval = (newValue as String).toInt()
if (interval > 0)
LibraryUpdateJob.setupTask(interval)
else
LibraryUpdateJob.cancelTask()
true
}
updateRestriction.setOnPreferenceChangeListener { preference, newValue ->
// Post to event looper to allow the preference to be updated.
subscriptions += Observable.fromCallable {
LibraryUpdateJob.setupTask()
}.subscribeOn(AndroidSchedulers.mainThread()).subscribe()
true
}
val dbCategories = db.getCategories().executeAsBlocking()
categoryUpdate.apply {
entries = dbCategories.map { it.name }.toTypedArray()
entryValues = dbCategories.map { it.id.toString() }.toTypedArray()
}
subscriptions += preferences.libraryUpdateCategories().asObservable()
.subscribe {
val selectedCategories = it
.mapNotNull { id -> dbCategories.find { it.id == id.toInt() } }
.sortedBy { it.order }
val summary = if (selectedCategories.isEmpty())
getString(R.string.all)
else
selectedCategories.joinToString { it.name }
categoryUpdate.summary = summary
}
themePreference.setOnPreferenceChangeListener { preference, newValue ->
(activity as SettingsActivity).parentFlags = SettingsActivity.FLAG_THEME_CHANGED
activity.recreate()
true
}
}
override fun onPreferenceDisplayDialog(p0: PreferenceFragmentCompat?, p: Preference): Boolean {
if (p === columnsPreference) {
val fragment = LibraryColumnsDialog.newInstance(p)
fragment.setTargetFragment(this, 0)
fragment.show(fragmentManager, null)
return true
}
return false
}
private fun updateColumnsSummary(portraitColumns: Int, landscapeColumns: Int) {
val portrait = getColumnValue(portraitColumns)
val landscape = getColumnValue(landscapeColumns)
val msg = "${getString(R.string.portrait)}: $portrait, ${getString(R.string.landscape)}: $landscape"
columnsPreference.summary = msg
}
private fun getColumnValue(value: Int): String {
return if (value == 0) getString(R.string.default_columns) else value.toString()
}
}
| apache-2.0 | 1d44d0d9543b3274d0fcbed083afe418 | 39.307087 | 110 | 0.682164 | 5.377101 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/actpost/ActPostExtra.kt | 1 | 13637 | package jp.juggler.subwaytooter.actpost
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import jp.juggler.subwaytooter.ActMain
import jp.juggler.subwaytooter.ActPost
import jp.juggler.subwaytooter.App1
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.actmain.onCompleteActPost
import jp.juggler.subwaytooter.api.entity.TootPollsType
import jp.juggler.subwaytooter.api.entity.TootVisibility
import jp.juggler.subwaytooter.api.entity.unknownHostAndDomain
import jp.juggler.subwaytooter.dialog.ActionsDialog
import jp.juggler.subwaytooter.pref.PrefB
import jp.juggler.subwaytooter.table.PostDraft
import jp.juggler.subwaytooter.table.SavedAccount
import jp.juggler.subwaytooter.util.DecodeOptions
import jp.juggler.subwaytooter.util.PostAttachment
import jp.juggler.subwaytooter.util.PostImpl
import jp.juggler.subwaytooter.util.PostResult
import jp.juggler.util.*
private val log = LogCategory("ActPostExtra")
fun ActPost.appendContentText(
src: String?,
selectBefore: Boolean = false,
) {
if (src?.isEmpty() != false) return
val svEmoji = DecodeOptions(
context = this,
decodeEmoji = true,
authorDomain = account ?: unknownHostAndDomain,
).decodeEmoji(src)
if (svEmoji.isEmpty()) return
val editable = views.etContent.text
if (editable == null) {
val sb = StringBuilder()
if (selectBefore) {
val start = 0
sb.append(' ')
sb.append(svEmoji)
views.etContent.setText(sb)
views.etContent.setSelection(start)
} else {
sb.append(svEmoji)
views.etContent.setText(sb)
views.etContent.setSelection(sb.length)
}
} else {
if (editable.isNotEmpty() &&
!CharacterGroup.isWhitespace(editable[editable.length - 1].code)
) {
editable.append(' ')
}
if (selectBefore) {
val start = editable.length
editable.append(' ')
editable.append(svEmoji)
views.etContent.text = editable
views.etContent.setSelection(start)
} else {
editable.append(svEmoji)
views.etContent.text = editable
views.etContent.setSelection(editable.length)
}
}
}
fun ActPost.appendContentText(src: Intent) {
val list = ArrayList<String>()
var sv: String?
sv = src.getStringExtra(Intent.EXTRA_SUBJECT)
if (sv?.isNotEmpty() == true) list.add(sv)
sv = src.getStringExtra(Intent.EXTRA_TEXT)
if (sv?.isNotEmpty() == true) list.add(sv)
if (list.isNotEmpty()) {
appendContentText(list.joinToString(" "))
}
}
// returns true if has content
fun ActPost.hasContent(): Boolean {
val content = views.etContent.text.toString()
val contentWarning =
if (views.cbContentWarning.isChecked) views.etContentWarning.text.toString() else ""
return when {
content.isNotBlank() -> true
contentWarning.isNotBlank() -> true
hasPoll() -> true
else -> false
}
}
fun ActPost.resetText() {
isPostComplete = false
resetReply()
resetMushroom()
states.redraftStatusId = null
states.editStatusId = null
states.timeSchedule = 0L
attachmentPicker.reset()
scheduledStatus = null
attachmentList.clear()
views.cbQuote.isChecked = false
views.etContent.setText("")
views.spPollType.setSelection(0, false)
etChoices.forEach { it.setText("") }
accountList = SavedAccount.loadAccountList(this)
SavedAccount.sort(accountList)
if (accountList.isEmpty()) {
showToast(true, R.string.please_add_account)
finish()
return
}
}
fun ActPost.afterUpdateText() {
// 2017/9/13 VISIBILITY_WEB_SETTING から VISIBILITY_PUBLICに変更した
// VISIBILITY_WEB_SETTING だと 1.5未満のタンスでトラブルになるので…
states.visibility = states.visibility ?: account?.visibility ?: TootVisibility.Public
// アカウント未選択なら表示を更新する
// 選択済みなら変えない
if (account == null) selectAccount(null)
showContentWarningEnabled()
showMediaAttachment()
showVisibility()
showReplyTo()
showPoll()
showQuotedRenote()
showSchedule()
updateTextCount()
}
// 初期化時と投稿完了時とリセット確認後に呼ばれる
fun ActPost.updateText(
intent: Intent,
confirmed: Boolean = false,
saveDraft: Boolean = true,
resetAccount: Boolean = true,
) {
if (!canSwitchAccount()) return
if (!confirmed && hasContent()) {
AlertDialog.Builder(this)
.setMessage("編集中のテキストや文脈を下書きに退避して、新しい投稿を編集しますか? ")
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok) { _, _ ->
updateText(intent, confirmed = true)
}
.setCancelable(true)
.show()
return
}
if (saveDraft) saveDraft()
resetText()
// Android 9 から、明示的にフォーカスを当てる必要がある
views.etContent.requestFocus()
this.attachmentList.clear()
saveAttachmentList()
if (resetAccount) {
states.visibility = null
this.account = null
val accountDbId = intent.getLongExtra(ActPost.KEY_ACCOUNT_DB_ID, SavedAccount.INVALID_DB_ID)
accountList.find { it.db_id == accountDbId }?.let { selectAccount(it) }
}
val sharedIntent = intent.getIntentExtra(ActPost.KEY_SHARED_INTENT)
if (sharedIntent != null) {
initializeFromSharedIntent(sharedIntent)
}
appendContentText(intent.getStringExtra(ActPost.KEY_INITIAL_TEXT))
val account = this.account
if (account != null) {
intent.getStringExtra(ActPost.KEY_REPLY_STATUS)
?.let { initializeFromReplyStatus(account, it) }
}
appendContentText(account?.default_text, selectBefore = true)
views.cbNSFW.isChecked = account?.default_sensitive ?: false
if (account != null) {
// 再編集
intent.getStringExtra(ActPost.KEY_REDRAFT_STATUS)
?.let { initializeFromRedraftStatus(account, it) }
// 再編集
intent.getStringExtra(ActPost.KEY_EDIT_STATUS)
?.let { initializeFromEditStatus(account, it) }
// 予約編集の再編集
intent.getStringExtra(ActPost.KEY_SCHEDULED_STATUS)
?.let { initializeFromScheduledStatus(account, it) }
}
afterUpdateText()
}
fun ActPost.initializeFromSharedIntent(sharedIntent: Intent) {
try {
val hasUri = when (sharedIntent.action) {
Intent.ACTION_VIEW -> {
val uri = sharedIntent.data
val type = sharedIntent.type
if (uri != null) {
addAttachment(uri, type)
true
} else {
false
}
}
Intent.ACTION_SEND -> {
val uri = sharedIntent.getStreamUriExtra()
val type = sharedIntent.type
if (uri != null) {
addAttachment(uri, type)
true
} else {
false
}
}
Intent.ACTION_SEND_MULTIPLE -> {
val listUri = sharedIntent.getStreamUriListExtra()
?.filterNotNull()
if (listUri?.isNotEmpty() == true) {
for (uri in listUri) {
addAttachment(uri)
}
true
} else {
false
}
}
else -> false
}
if (!hasUri || !PrefB.bpIgnoreTextInSharedMedia(pref)) {
appendContentText(sharedIntent)
}
} catch (ex: Throwable) {
log.trace(ex)
}
}
fun ActPost.performMore() {
val dialog = ActionsDialog()
dialog.addAction(getString(R.string.open_picker_emoji)) {
completionHelper.openEmojiPickerFromMore()
}
dialog.addAction(getString(R.string.clear_text)) {
views.etContent.setText("")
views.etContentWarning.setText("")
}
dialog.addAction(getString(R.string.clear_text_and_media)) {
views.etContent.setText("")
views.etContentWarning.setText("")
attachmentList.clear()
showMediaAttachment()
}
if (PostDraft.hasDraft()) dialog.addAction(getString(R.string.restore_draft)) {
openDraftPicker()
}
dialog.addAction(getString(R.string.recommended_plugin)) {
showRecommendedPlugin(null)
}
dialog.show(this, null)
}
fun ActPost.performPost() {
val activity = this
launchAndShowError {
// アップロード中は投稿できない
if (attachmentList.any { it.status == PostAttachment.Status.Progress }) {
showToast(false, R.string.media_attachment_still_uploading)
return@launchAndShowError
}
val account = activity.account ?: return@launchAndShowError
var pollType: TootPollsType? = null
var pollItems: ArrayList<String>? = null
var pollExpireSeconds = 0
var pollHideTotals = false
var pollMultipleChoice = false
when (views.spPollType.selectedItemPosition) {
0 -> Unit // not poll
else -> {
pollType = TootPollsType.Mastodon
pollItems = pollChoiceList()
pollExpireSeconds = pollExpireSeconds()
pollHideTotals = views.cbHideTotals.isChecked
pollMultipleChoice = views.cbMultipleChoice.isChecked
}
}
val postResult = PostImpl(
activity = activity,
account = account,
content = views.etContent.text.toString().trim { it <= ' ' },
spoilerText = when {
!views.cbContentWarning.isChecked -> null
else -> views.etContentWarning.text.toString().trim { it <= ' ' }
},
visibilityArg = states.visibility ?: TootVisibility.Public,
bNSFW = views.cbNSFW.isChecked,
inReplyToId = states.inReplyToId,
attachmentListArg = activity.attachmentList,
enqueteItemsArg = pollItems,
pollType = pollType,
pollExpireSeconds = pollExpireSeconds,
pollHideTotals = pollHideTotals,
pollMultipleChoice = pollMultipleChoice,
scheduledAt = states.timeSchedule,
scheduledId = scheduledStatus?.id,
redraftStatusId = states.redraftStatusId,
editStatusId = states.editStatusId,
emojiMapCustom = App1.custom_emoji_lister.getMapNonBlocking(account),
useQuoteToot = views.cbQuote.isChecked,
lang = languages.elementAtOrNull(views.spLanguage.selectedItemPosition)?.first
?: SavedAccount.LANG_WEB
).runSuspend()
when (postResult) {
is PostResult.Normal -> {
val data = Intent()
data.putExtra(ActPost.EXTRA_POSTED_ACCT, postResult.targetAccount.acct.ascii)
postResult.status.id.putTo(data, ActPost.EXTRA_POSTED_STATUS_ID)
states.redraftStatusId?.putTo(data, ActPost.EXTRA_POSTED_REDRAFT_ID)
postResult.status.in_reply_to_id?.putTo(data, ActPost.EXTRA_POSTED_REPLY_ID)
if (states.editStatusId != null) {
data.putExtra(ActPost.KEY_EDIT_STATUS, postResult.status.json.toString())
}
ActMain.refActMain?.get()?.onCompleteActPost(data)
if (isMultiWindowPost) {
resetText()
updateText(Intent(), confirmed = true, saveDraft = false, resetAccount = false)
afterUpdateText()
} else {
// ActMainの復元が必要な場合に備えてintentのdataでも渡す
setResult(AppCompatActivity.RESULT_OK, data)
isPostComplete = true
[email protected]()
}
}
is PostResult.Scheduled -> {
showToast(false, getString(R.string.scheduled_status_sent))
val data = Intent()
data.putExtra(ActPost.EXTRA_POSTED_ACCT, postResult.targetAccount.acct.ascii)
if (isMultiWindowPost) {
resetText()
updateText(Intent(), confirmed = true, saveDraft = false, resetAccount = false)
afterUpdateText()
ActMain.refActMain?.get()?.onCompleteActPost(data)
} else {
setResult(AppCompatActivity.RESULT_OK, data)
isPostComplete = true
[email protected]()
}
}
}
}
}
fun ActPost.showContentWarningEnabled() {
views.etContentWarning.vg(views.cbContentWarning.isChecked)
}
| apache-2.0 | 87e127682ff6158eb424c17f82c311b8 | 31.627848 | 100 | 0.585485 | 4.586671 | false | false | false | false |
ahatem/Kotlin-Examples | Kotlin-Desktop-Software/Browser Software/Browser.kt | 1 | 3316 | import javafx.application.Application
import javafx.beans.value.ChangeListener
import javafx.beans.value.ObservableValue
import javafx.concurrent.Worker
import javafx.event.EventHandler
import javafx.geometry.Insets
import javafx.scene.Scene
import javafx.scene.control.ScrollPane
import javafx.scene.control.TextField
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import javafx.scene.layout.BorderPane
import javafx.scene.layout.HBox
import javafx.scene.web.WebEngine
import javafx.scene.web.WebView
import javafx.stage.Stage
import javafx.geometry.Pos
import javafx.scene.control.Button
import javafx.scene.control.Label
import javafx.scene.layout.Priority
class Browser : Application() {
var mainStage : Stage? = null;
var scene : Scene? = null;
var scrollPane : ScrollPane? = null;
var layout : BorderPane? = null;
var layout2 : HBox? = null;
var browser : WebView? = null;
var webEngine : WebEngine? = null;
var urlInput : TextField? = null;
override fun start(stage: Stage) {
this.mainStage = stage;
this.mainStage?.title = "Simple Browser Software Using Kotlin and Javafx";
this.browser = WebView();
this.webEngine = browser?.getEngine();
this.webEngine?.load("http://www.google.com");
this.scrollPane = ScrollPane();
this.scrollPane?.setContent(this.browser);
this.urlInput = TextField();
webEngine?.getLoadWorker()?.stateProperty()?.addListener(object : ChangeListener<Worker.State?> {
override fun changed(observableValue : ObservableValue<out Worker.State?>?, oldValue: Worker.State?, newValue : Worker.State? ) : Unit {
if (Worker.State.SUCCEEDED.equals(newValue)) {
urlInput?.setText(webEngine?.getLocation());
}
}
});
this.scrollPane?.widthProperty()?.addListener(object : ChangeListener<Number?> {
override fun changed(observableValue : ObservableValue<out Number?>?, oldSceneWidth: Number?, newSceneWidth : Number? ) : Unit {
browser?.setPrefWidth(newSceneWidth!!.toDouble());
}
});
this.scrollPane?.heightProperty()?.addListener(object : ChangeListener<Number?> {
override fun changed(observableValue : ObservableValue<out Number?>?, oldSceneHeight: Number?, newSceneHeight : Number? ) : Unit {
browser?.setPrefHeight(newSceneHeight!!.toDouble());
}
});
this.urlInput?.setOnKeyPressed(object : EventHandler<KeyEvent> {
override fun handle(key : KeyEvent) {
if (key.getCode().equals(KeyCode.ENTER)){
webEngine?.load("http://" + urlInput?.getText());
}
}
});
this.layout2 = HBox();
HBox.setHgrow(urlInput, Priority.SOMETIMES);
this.layout2?.setAlignment(Pos.CENTER);
this.layout2?.getChildren()?.addAll(Label("Search: "), urlInput);
this.layout2?.setPadding(Insets(10.0,10.0,10.0,10.0));
this.layout = BorderPane();
this.layout?.setCenter(this.scrollPane!!);
this.layout?.setTop(this.layout2!!);
this.scene = Scene(layout,600.0,400.0);
this.mainStage?.setScene(scene);
this.mainStage?.show();
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
launch(Browser::class.java)
}
}
}
| mit | a29df2bc20fc35e00b5e95a37dd6c129 | 32.16 | 139 | 0.677322 | 3.905771 | false | false | false | false |
lisuperhong/ModularityApp | CommonBusiness/src/main/java/com/company/commonbusiness/base/activity/BaseActivity.kt | 1 | 2817 | package com.company.commonbusiness.base.activity
import android.content.Intent
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import com.company.commonbusiness.util.ActivityUtils
import com.orhanobut.logger.Logger
/**
* @author 李昭鸿
* @desc: Activity基类
* @date Created on 2017/7/21 10:27
*/
abstract class BaseActivity : AppCompatActivity() {
protected val TAG = this.javaClass.simpleName
@get:LayoutRes
protected abstract val layoutId: Int
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Logger.d("onCreate Invoke...")
ActivityUtils.addActivity(this)
setContentView(layoutId)
if (null != intent) {
handleIntent(intent)
}
initPresenter()
initView()
initData(savedInstanceState)
}
override fun onDestroy() {
super.onDestroy()
Logger.d("onDestroy Invoke...")
ActivityUtils.removeActivity(this)
}
override fun onLowMemory() {
super.onLowMemory()
Logger.d("onLowMemory Invoke...")
}
override fun onBackPressed() {
super.onBackPressed()
Logger.d("onBackPressed Invoke...")
}
/**
* 处理跳转时传递的数据
* @param intent
*/
open fun handleIntent(intent: Intent) {
}
/**
* 如果Activity是使用MVP,初始化presenter
*/
open fun initPresenter() {
}
protected fun setToolBar(toolbar: Toolbar, title: String) {
toolbar.title = title
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setDisplayShowHomeEnabled(true)
}
/**
* 通过Class跳转界面
*/
protected fun startActivity(cls: Class<*>) {
startAcvitity(cls, null)
}
protected fun startAcvitity(cls: Class<*>, bundle: Bundle? = null) {
val intent = Intent(this, cls)
if (bundle != null) {
intent.putExtras(bundle)
}
startActivity(intent)
}
protected fun startActivityForResult(cls: Class<*>, requestCode: Int) {
startActivityForResult(cls, null, requestCode)
}
protected fun startActivityForResult(cls: Class<*>, bundle: Bundle? = null, requestCode: Int) {
val intent = Intent(this, cls)
if (bundle != null) {
intent.putExtras(bundle)
}
startActivityForResult(intent, requestCode)
}
/**
* 初始化View
*/
protected abstract fun initView()
/**
* 初始化数据,从服务端或本地加载数据
*/
protected abstract fun initData(savedInstanceState: Bundle?)
}
| apache-2.0 | 86d4c9825d01627e2d78289bf2037898 | 22.833333 | 99 | 0.634523 | 4.652397 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/dialog/BrowserWindow.kt | 2 | 1708 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.causeway.client.kroviz.ui.dialog
import io.kvision.panel.SimplePanel
import org.apache.causeway.client.kroviz.to.ValueType
import org.apache.causeway.client.kroviz.ui.core.FormItem
import org.apache.causeway.client.kroviz.ui.core.RoDialog
import org.apache.causeway.client.kroviz.ui.core.ViewManager
class BrowserWindow(val url: String) : Controller() {
init {
val formItems = mutableListOf<FormItem>()
formItems.add(FormItem("URL", ValueType.IFRAME, url))
dialog = RoDialog(
caption = url,
items = formItems,
controller = this,
widthPerc = 70,
heightPerc = 70,
defaultAction = "Pin"
)
}
fun execute() {
pin()
}
private fun pin() {
ViewManager.add(url, dialog.formPanel as SimplePanel)
dialog.close()
}
}
| apache-2.0 | e25b704646da75d48dd3b5e515505a40 | 32.490196 | 64 | 0.684426 | 4.095923 | false | false | false | false |
anddevbg/Bapp | app/src/main/kotlin/com.anddevbg.bapp/domain/place/PlaceDataProvider.kt | 1 | 1214 | package com.anddevbg.bapp.domain.place
import android.location.Location
import com.anddevbg.bapp.BuildConfig
import com.anddevbg.bapp.data.PlacesService
import rx.Observable
/**
* Created by teodorpenkov on 5/23/16.
*/
class PlaceDataProvider(val service: PlacesService, val nearbyResponseDataMapper: NearbyResponseDataMapper) {
fun nearbyBars(longitude: Double, latitude: Double): Observable<List<Place>> {
val requestLocation = Location("current_location")
requestLocation.longitude = longitude
requestLocation.latitude = latitude
return service.nearby(BuildConfig.GOOGLE_PLACES_API_KEY, "${latitude},${longitude}")
.map { nearbyResponseDataMapper.map(it) }
.map {
it.map {
val placeLocation = Location("place_location")
placeLocation.longitude = it.longitude
placeLocation.latitude = it.latidude
it.distanceTo = distanceBetweenLocations(requestLocation, placeLocation)
it
}
}
}
fun distanceBetweenLocations(a: Location, b: Location) = a.distanceTo(b)
} | apache-2.0 | b571bfa587eb9e14a52fe248160009b1 | 36.96875 | 109 | 0.633443 | 4.955102 | false | true | false | false |
moko256/twicalico | app/src/main/java/com/github/moko256/twitlatte/widget/AdapterObservableBinder.kt | 1 | 2381 | /*
* Copyright 2015-2019 The twitlatte authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.moko256.twitlatte.widget
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.github.moko256.twitlatte.entity.EventType
import com.github.moko256.twitlatte.entity.UpdateEvent
/**
* Created by moko256 on 2018/10/11.
*
* @author moko256
*/
fun convertObservableConsumer(
recyclerView: RecyclerView,
adapter: RecyclerView.Adapter<in RecyclerView.ViewHolder>,
layoutManager: RecyclerView.LayoutManager
): (UpdateEvent) -> Unit = {
when (it.type) {
EventType.ADD_FIRST -> adapter.notifyDataSetChanged()
EventType.ADD_TOP -> adapter.notifyItemRangeInserted(it.position, it.size)
EventType.ADD_BOTTOM -> adapter.notifyItemRangeInserted(it.position, it.size)
EventType.REMOVE -> adapter.notifyItemRangeRemoved(it.position, it.size)
EventType.INSERT -> {
val startView = layoutManager.findViewByPosition(it.position)
val offset = if (startView == null) {
0
} else {
startView.top - recyclerView.paddingTop
}
if (layoutManager is LinearLayoutManager) {
adapter.notifyItemRangeInserted(it.position, it.size)
layoutManager.scrollToPositionWithOffset(it.position + it.size, offset)
} else {
(layoutManager as StaggeredGridLayoutManager).scrollToPositionWithOffset(it.position + it.size, offset)
adapter.notifyItemRangeChanged(it.position, it.size)
}
}
EventType.UPDATE -> adapter.notifyItemRangeChanged(it.position, it.size)
else -> {
}
}
} | apache-2.0 | 8efc4927885254432ab7c03d0390931a | 34.552239 | 119 | 0.691306 | 4.781124 | false | false | false | false |
aconsuegra/algorithms-playground | src/main/kotlin/me/consuegra/datastructure/KListNode.kt | 1 | 623 | package me.consuegra.datastructure
@Suppress("UnsafeCast")
data class KListNode<T>(val data: T, var next: KListNode<T>? = null) {
fun append(value: T): KListNode<T> {
val newNode = KListNode(value)
var currentNode = this
while (currentNode.next != null) {
currentNode = currentNode.next as KListNode<T>
}
currentNode.next = newNode
return this
}
fun size(): Int {
var size = 1
var head = this
while (head.next != null) {
size++
head = head.next as KListNode<T>
}
return size
}
}
| mit | 76e51289e7289fa24a4ad22ba88fc916 | 22.961538 | 70 | 0.548957 | 4.209459 | false | false | false | false |
android/compose-samples | Crane/benchmark/src/main/java/androidx/compose/samples/crane/benchmark/CalendarScrollBenchmark.kt | 1 | 3598 | /*
* 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 androidx.compose.samples.crane.benchmark
import androidx.benchmark.macro.CompilationMode
import androidx.benchmark.macro.FrameTimingMetric
import androidx.benchmark.macro.StartupMode
import androidx.benchmark.macro.junit4.MacrobenchmarkRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.uiautomator.By
import androidx.test.uiautomator.Direction
import androidx.test.uiautomator.Until
import java.util.concurrent.TimeUnit
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
private const val ITERATIONS = 5
@Ignore("This test cannot run on an emulator so is disabled for CI, it is here as a sample.")
@RunWith(AndroidJUnit4::class)
class CalendarScrollBenchmark {
@get:Rule
val benchmarkRule = MacrobenchmarkRule()
/**
* When developing a screen, you can use a benchmark test like this one to
* tweak and optimise it's performance. For example, wondering if you should remember something?
* Try it without remember and save the results of the test, try it again with remember and
* see if the results were improved.
**/
@Test
fun testCalendarScroll() {
benchmarkRule.measureRepeated(
// [START_EXCLUDE]
packageName = "androidx.compose.samples.crane",
metrics = listOf(FrameTimingMetric()),
// Try switching to different compilation modes to see the effect
// it has on frame timing metrics.
compilationMode = CompilationMode.Full(),
startupMode = StartupMode.WARM, // restarts activity each iteration
iterations = ITERATIONS,
// [END_EXCLUDE]
setupBlock = {
startActivityAndWait()
val buttonSelector = By.text("Select Dates")
device.wait(
Until.hasObject(buttonSelector),
TimeUnit.SECONDS.toMillis(3)
)
val calendarButton = device.findObject(buttonSelector)
calendarButton.click()
// Select some dates to ensure selection composables are taken in
// to account.
// Text in the form of "August 15 2022"
val firstDateSelector = By.textContains(" 15")
device.wait(
Until.hasObject(firstDateSelector),
TimeUnit.SECONDS.toMillis(3)
)
device.findObject(firstDateSelector).click()
device.findObject(By.textContains(" 19")).click()
}
) {
val column = device.findObject(By.scrollable(true))
// Set gesture margin to avoid triggering gesture navigation
// with input events from automation.
column.setGestureMargin(device.displayWidth / 5)
// Scroll down several times
repeat(3) { column.fling(Direction.DOWN) }
}
}
}
| apache-2.0 | 0656678aa294a742127570c9fcade4ed | 37.688172 | 100 | 0.65731 | 4.922025 | false | true | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/ide/impl/popup.kt | 1 | 3279 | // 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.lang.documentation.ide.impl
import com.intellij.codeInsight.documentation.DocumentationManager.NEW_JAVADOC_LOCATION_AND_SIZE
import com.intellij.codeWithMe.ClientId
import com.intellij.lang.documentation.ide.ui.DEFAULT_UI_RESPONSE_TIMEOUT
import com.intellij.lang.documentation.ide.ui.DocumentationPopupUI
import com.intellij.lang.documentation.ide.ui.DocumentationUI
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.asContextElement
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.DimensionService
import com.intellij.openapi.util.Disposer
import com.intellij.ui.popup.AbstractPopup
import com.intellij.util.ui.EDT
import kotlinx.coroutines.*
internal fun createDocumentationPopup(
project: Project,
browser: DocumentationBrowser,
popupContext: PopupContext
): AbstractPopup {
EDT.assertIsEdt()
val popupUI = DocumentationPopupUI(project, DocumentationUI(project, browser))
val builder = JBPopupFactory.getInstance()
.createComponentPopupBuilder(popupUI.component, popupUI.preferableFocusComponent)
.setProject(project)
.addUserData(ClientId.current)
.setResizable(true)
.setMovable(true)
.setFocusable(true)
.setModalContext(false)
popupContext.preparePopup(builder)
val popup = builder.createPopup() as AbstractPopup
popupUI.setPopup(popup)
popupContext.setUpPopup(popup, popupUI)
return popup
}
internal fun CoroutineScope.showPopupLater(popup: AbstractPopup, browseJob: Job, popupContext: PopupContext) {
EDT.assertIsEdt()
val showJob = launch(ModalityState.current().asContextElement()) {
browseJob.tryJoin() // to avoid flickering: show popup immediately after the request is loaded OR after a timeout
withContext(Dispatchers.EDT) {
check(!popup.isDisposed) // popup disposal should've cancelled this coroutine
check(popup.canShow()) // sanity check
popupContext.showPopup(popup)
}
}
Disposer.register(popup, showJob::cancel)
}
/**
* Suspends until the job is done, or timeout is exceeded.
*/
private suspend fun Job.tryJoin() {
withTimeoutOrNull(DEFAULT_UI_RESPONSE_TIMEOUT) {
[email protected]()
}
}
internal fun resizePopup(popup: AbstractPopup) {
popup.size = popup.component.preferredSize
}
fun storeSize(project: Project, popup: AbstractPopup, parent: Disposable) {
val resizeState = PopupResizeState(project, popup)
popup.addResizeListener(resizeState, parent)
val storedSize = DimensionService.getInstance().getSize(NEW_JAVADOC_LOCATION_AND_SIZE, project)
if (storedSize != null) {
resizeState.manuallyResized = true
popup.size = storedSize
}
}
private class PopupResizeState(
private val project: Project,
private val popup: AbstractPopup,
) : Runnable {
var manuallyResized = false
override fun run() {
manuallyResized = true
DimensionService.getInstance().setSize(NEW_JAVADOC_LOCATION_AND_SIZE, popup.contentSize, project)
}
}
| apache-2.0 | e00a2a560ffe55964f5de8c429b3dbe3 | 35.433333 | 158 | 0.783776 | 4.209243 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/controller/usecases/Canvas.kt | 1 | 8521 | package com.cout970.modeler.controller.usecases
import com.cout970.modeler.api.model.IModel
import com.cout970.modeler.api.model.mesh.IMesh
import com.cout970.modeler.api.model.selection.IRef
import com.cout970.modeler.api.model.selection.SelectionTarget
import com.cout970.modeler.api.model.selection.SelectionType
import com.cout970.modeler.controller.tasks.*
import com.cout970.modeler.core.config.Config
import com.cout970.modeler.core.helpers.PickupHelper
import com.cout970.modeler.gui.Gui
import com.cout970.modeler.gui.canvas.Canvas
import com.cout970.modeler.gui.canvas.CanvasContainer
import com.cout970.modeler.gui.canvas.helpers.CanvasHelper
import com.cout970.modeler.input.event.IInput
import com.cout970.modeler.util.absolutePositionV
import com.cout970.modeler.util.getClosest
import com.cout970.modeler.util.toNullable
import com.cout970.modeler.util.toRads
import com.cout970.raytrace.IRayObstacle
import com.cout970.raytrace.Ray
import com.cout970.raytrace.RayTraceResult
import com.cout970.raytrace.RayTraceUtil
import com.cout970.vector.api.IVector2
import com.cout970.vector.extensions.*
import org.liquidengine.legui.component.Component
/**
* Created by cout970 on 2017/07/20.
*/
@UseCase("view.switch.ortho")
private fun switchCameraProjection(comp: Component?, canvasContainer: CanvasContainer): ITask {
val index: Int = comp?.metadata?.get("canvas") as? Int ?: -1
val canvas = canvasContainer.canvas.getOrNull(index) ?: canvasContainer.selectedCanvas
return if (canvas != null) {
ModifyGui { canvas.cameraHandler.setOrtho(canvas.cameraHandler.camera.perspective) }
} else {
TaskNone
}
}
@UseCase("view.set.texture.mode")
private fun setCanvasModeTexture(comp: Component?, canvasContainer: CanvasContainer): ITask {
val index: Int = comp?.metadata?.get("canvas") as? Int ?: -1
val canvas = canvasContainer.canvas.getOrNull(index) ?: canvasContainer.selectedCanvas
return if (canvas != null) {
ModifyGui { canvas.viewMode = SelectionTarget.TEXTURE }
} else {
TaskNone
}
}
@UseCase("view.set.model.mode")
private fun setCanvasModeModel(comp: Component?, canvasContainer: CanvasContainer): ITask {
val index: Int = comp?.metadata?.get("canvas") as? Int ?: -1
val canvas = canvasContainer.canvas.getOrNull(index) ?: canvasContainer.selectedCanvas
return if (canvas != null) {
ModifyGui { canvas.viewMode = SelectionTarget.MODEL }
} else {
TaskNone
}
}
@UseCase("view.set.camera.lock.position")
private fun setCanvasCameraLockPos(comp: Component?, canvasContainer: CanvasContainer): ITask {
val index: Int = comp?.metadata?.get("canvas") as? Int ?: -1
val canvas = canvasContainer.canvas.getOrNull(index) ?: canvasContainer.selectedCanvas
return if (canvas != null) {
ModifyGui { canvas.cameraHandler.lockPos = !canvas.cameraHandler.lockPos; it.root.reRender() }
} else {
TaskNone
}
}
@UseCase("view.set.camera.lock.rotation")
private fun setCanvasCameraLockRot(comp: Component?, canvasContainer: CanvasContainer): ITask {
val index: Int = comp?.metadata?.get("canvas") as? Int ?: -1
val canvas = canvasContainer.canvas.getOrNull(index) ?: canvasContainer.selectedCanvas
return if (canvas != null) {
ModifyGui { canvas.cameraHandler.lockRot = !canvas.cameraHandler.lockRot; it.root.reRender() }
} else {
TaskNone
}
}
@UseCase("view.set.camera.lock.scale")
private fun setCanvasCameraLockScale(comp: Component?, canvasContainer: CanvasContainer): ITask {
val index: Int = comp?.metadata?.get("canvas") as? Int ?: -1
val canvas = canvasContainer.canvas.getOrNull(index) ?: canvasContainer.selectedCanvas
return if (canvas != null) {
ModifyGui { canvas.cameraHandler.lockScale = !canvas.cameraHandler.lockScale; it.root.reRender() }
} else {
TaskNone
}
}
@UseCase("camera.set.isometric")
private fun setIsometricCamera(canvasContainer: CanvasContainer): ITask {
canvasContainer.selectedCanvas?.let { canvas ->
if (canvas.viewMode.is3D) {
return ModifyGui {
canvas.modelCamera.setOrtho(true)
canvas.modelCamera.setRotation(45.toRads(), (-45).toRads())
}
}
}
return TaskNone
}
@UseCase("canvas.jump.camera")
private fun jumpCameraToCanvas(component: Component, gui: Gui, input: IInput, model: IModel): ITask {
if (gui.state.cursor.getParts().any { it.hovered }) return TaskNone
val canvas = component as Canvas
val pos = input.mouse.getMousePos()
val (result, _) = PickupHelper.pickup3D(canvas, pos, model, SelectionType.OBJECT, gui.animator) ?: return TaskNone
return ModifyGui { canvas.cameraHandler.setPosition(-result.hit) }
}
@UseCase("canvas.select.model")
private fun selectPartInCanvas(component: Component, input: IInput, gui: Gui): ITask {
val canvas = component as Canvas
if (canvas.viewMode != SelectionTarget.MODEL) return TaskNone
if (gui.state.cursor.visible && gui.state.cursor.getParts().any { it.hovered }) return TaskNone
return onModel(canvas, gui, input)
}
@UseCase("canvas.select.texture")
private fun selectPartInCanvas2(component: Component, input: IInput, gui: Gui): ITask {
val canvas = component as Canvas
if (canvas.viewMode != SelectionTarget.TEXTURE) return TaskNone
return onTexture(canvas, input, gui)
}
private fun onModel(canvas: Canvas, gui: Gui, input: IInput): ITask {
tryClickOrientationCube(gui, canvas, input)?.let { return it }
val multiSelection = Config.keyBindings.multipleSelection.check(input)
val (model, selection) = gui.programState
val pos = input.mouse.getMousePos()
val obj = PickupHelper.pickup3D(canvas, pos, model, gui.state.selectionType, gui.animator)?.second
val newSelection = gui.programState.modelSelectionHandler.updateSelection(
selection.toNullable(),
multiSelection,
obj
)
return TaskUpdateModelSelection(
oldSelection = selection,
newSelection = newSelection
)
}
private fun tryClickOrientationCube(gui: Gui, canvas: Canvas, input: IInput): ITask? {
val pos = input.mouse.getMousePos()
val viewportPos = vec2Of(canvas.absolutePosition.x, canvas.absolutePositionV.yf + canvas.size.y - 150f)
val context = CanvasHelper.getContextForOrientationCube(canvas, viewportPos, vec2Of(150, 150), pos)
val obstacles = getOrientationCubeFaces(gui.resources.orientationCubeMesh)
val res = obstacles.mapNotNull { (obj, ref) -> obj.rayTrace(context.mouseRay)?.let { result -> result to ref } }
val obj = res.getClosest(context.mouseRay)
val angles = obj?.second ?: return null
return ModifyGui { canvas.cameraHandler.setRotation(angles.xd.toRads(), angles.yd.toRads()) }
}
private fun onTexture(canvas: Canvas, input: IInput, gui: Gui): ITask {
val selHandler = gui.programState.textureSelectionHandler
val obj = getTextureSelection(canvas, input, gui)
val multiSelection = Config.keyBindings.multipleSelection.check(input)
val selection = selHandler.getSelection()
return TaskUpdateTextureSelection(
oldSelection = selection,
newSelection = selHandler.updateSelection(
selection.toNullable(),
multiSelection,
obj
)
)
}
fun getTextureSelection(canvas: Canvas, input: IInput, gui: Gui): IRef? {
val (model, modSel) = gui.programState
val mouse = input.mouse.getMousePos()
val actualMaterial = model.getMaterial(gui.state.selectedMaterial)
val selectionType = gui.state.selectionType
return PickupHelper.pickup2D(canvas, mouse, model, modSel, actualMaterial, selectionType)?.second
}
private fun getOrientationCubeFaces(mesh: IMesh): List<Pair<IRayObstacle, IVector2>> {
val obstacles = mesh.faces.map { face ->
val pos = face.pos.map { mesh.pos[it] }.map { (it * 2.0) + vec3Of(-8) }
object : IRayObstacle {
override fun rayTrace(ray: Ray): RayTraceResult? {
return RayTraceUtil.rayTraceQuad(ray, this, pos[0], pos[1], pos[2], pos[3])
}
}
}
return listOf(
obstacles[0] to vec2Of(-90.0, 0.0), // bottom
obstacles[1] to vec2Of(90.0, 0.0), // top
obstacles[2] to vec2Of(0.0, 180.0), // north
obstacles[3] to vec2Of(0.0, 0.0), // south
obstacles[4] to vec2Of(0.0, 90.0), // west
obstacles[5] to vec2Of(0.0, -90.0) // east
)
} | gpl-3.0 | 4774834180788203d4abbc4e0495e151 | 36.377193 | 118 | 0.709306 | 3.935797 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt | 1 | 2647 | package info.nightscout.androidaps.plugins.general.automation.actions
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.elements.InputString
import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement
import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationUserMessage
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.JsonHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.json.JSONObject
import javax.inject.Inject
class ActionNotification(injector: HasAndroidInjector) : Action(injector) {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var nsUpload: NSUpload
var text = InputString(injector)
override fun friendlyName(): Int = R.string.notification
override fun shortDescription(): String = resourceHelper.gs(R.string.notification_message, text.value)
@DrawableRes override fun icon(): Int = R.drawable.ic_notifications
override fun doAction(callback: Callback) {
val notification = NotificationUserMessage(text.value)
rxBus.send(EventNewNotification(notification))
nsUpload.uploadError(text.value)
rxBus.send(EventRefreshOverview("ActionNotification"))
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run()
}
override fun toJSON(): String {
val data = JSONObject().put("text", text.value)
return JSONObject()
.put("type", this.javaClass.name)
.put("data", data)
.toString()
}
override fun fromJSON(data: String): Action {
val o = JSONObject(data)
text.value = JsonHelper.safeGetString(o, "text", "")
return this
}
override fun hasDialog(): Boolean = true
override fun generateDialog(root: LinearLayout) {
LayoutBuilder()
.add(LabelWithElement(injector, resourceHelper.gs(R.string.message_short), "", text))
.build(root)
}
} | agpl-3.0 | 849811d2e594990469ef31f3b8067816 | 41.709677 | 106 | 0.763128 | 4.803993 | false | false | false | false |
TeamNewPipe/NewPipe | app/src/main/java/org/schabi/newpipe/settings/NotificationsSettingsFragment.kt | 1 | 5222 | package org.schabi.newpipe.settings
import android.content.SharedPreferences
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import android.graphics.Color
import android.os.Bundle
import androidx.preference.Preference
import com.google.android.material.snackbar.Snackbar
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.Disposable
import org.schabi.newpipe.R
import org.schabi.newpipe.database.subscription.NotificationMode
import org.schabi.newpipe.database.subscription.SubscriptionEntity
import org.schabi.newpipe.error.ErrorInfo
import org.schabi.newpipe.error.ErrorUtil
import org.schabi.newpipe.error.UserAction
import org.schabi.newpipe.local.feed.notifications.NotificationHelper
import org.schabi.newpipe.local.feed.notifications.NotificationWorker
import org.schabi.newpipe.local.feed.notifications.ScheduleOptions
import org.schabi.newpipe.local.subscription.SubscriptionManager
class NotificationsSettingsFragment : BasePreferenceFragment(), OnSharedPreferenceChangeListener {
private var notificationWarningSnackbar: Snackbar? = null
private var loader: Disposable? = null
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.notifications_settings)
// main check is done in onResume, but also do it here to prevent flickering
preferenceScreen.isEnabled =
NotificationHelper.areNotificationsEnabledOnDevice(requireContext())
}
override fun onStart() {
super.onStart()
defaultPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onStop() {
defaultPreferences.unregisterOnSharedPreferenceChangeListener(this)
super.onStop()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
val context = context ?: return
if (key == getString(R.string.streams_notifications_interval_key) ||
key == getString(R.string.streams_notifications_network_key)
) {
// apply new configuration
NotificationWorker.schedule(context, ScheduleOptions.from(context), true)
} else if (key == getString(R.string.enable_streams_notifications)) {
if (NotificationHelper.areNewStreamsNotificationsEnabled(context)) {
// Start the worker, because notifications were disabled previously.
NotificationWorker.schedule(context)
} else {
// The user disabled the notifications. Cancel the worker to save energy.
// A new one will be created once the notifications are enabled again.
NotificationWorker.cancel(context)
}
}
}
override fun onResume() {
super.onResume()
// Check whether the notifications are disabled in the device's app settings.
// If they are disabled, show a snackbar informing the user about that
// while allowing them to open the device's app settings.
val enabled = NotificationHelper.areNotificationsEnabledOnDevice(requireContext())
preferenceScreen.isEnabled = enabled // it is disabled by default, see the xml
if (!enabled) {
if (notificationWarningSnackbar == null) {
notificationWarningSnackbar = Snackbar.make(
listView,
R.string.notifications_disabled,
Snackbar.LENGTH_INDEFINITE
).apply {
setAction(R.string.settings) {
NotificationHelper.openNewPipeSystemNotificationSettings(it.context)
}
setActionTextColor(Color.YELLOW)
addCallback(object : Snackbar.Callback() {
override fun onDismissed(transientBottomBar: Snackbar, event: Int) {
super.onDismissed(transientBottomBar, event)
notificationWarningSnackbar = null
}
})
show()
}
}
}
// (Re-)Create loader
loader?.dispose()
loader = SubscriptionManager(requireContext())
.subscriptions()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::updateSubscriptions, this::onError)
}
override fun onPause() {
loader?.dispose()
loader = null
notificationWarningSnackbar?.dismiss()
notificationWarningSnackbar = null
super.onPause()
}
private fun updateSubscriptions(subscriptions: List<SubscriptionEntity>) {
val notified = subscriptions.count { it.notificationMode != NotificationMode.DISABLED }
val preference = findPreference<Preference>(getString(R.string.streams_notifications_channels_key))
preference?.apply { summary = "$notified/${subscriptions.size}" }
}
private fun onError(e: Throwable) {
ErrorUtil.showSnackbar(
this,
ErrorInfo(e, UserAction.SUBSCRIPTION_GET, "Get subscriptions list")
)
}
}
| gpl-3.0 | d26b31c41191a1df11b3ebd6db0eaf40 | 41.112903 | 107 | 0.672539 | 5.682263 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/editor/quickDoc/Samples.kt | 4 | 1114 | package magic
object Samples {
fun sampleMagic() {
castTextSpell("[asd] [dse] [asz]")
}
}
fun sampleScroll() {
val reader = Scroll("[asd] [dse] [asz]").reader()
castTextSpell(reader.readAll())
}
/**
* @sample Samples.sampleMagic
* @sample sampleScroll
*/
fun <caret>castTextSpell(spell: String) {
throw SecurityException("Magic prohibited outside Hogwarts")
}
//INFO: <div class='definition'><pre><a href="psi_element://magic"><code>magic</code></a> <font color="808080"><i>Samples.kt</i></font><br>public fun <b>castTextSpell</b>(
//INFO: spell: String
//INFO: ): Unit</pre></div><div class='content'></div><table class='sections'><tr><td valign='top' class='section'><p>Samples:</td><td valign='top'><p><a href="psi_element://Samples.sampleMagic"><code>Samples.sampleMagic</code></a><pre><code>
//INFO: castTextSpell("[asd] [dse] [asz]")
//INFO: </code></pre><p><a href="psi_element://sampleScroll"><code>sampleScroll</code></a><pre><code>
//INFO: val reader = Scroll("[asd] [dse] [asz]").reader()
//INFO: castTextSpell(reader.readAll())
//INFO: </code></pre></td></table>
| apache-2.0 | f40eef019df32e9262a41671ca8a8041 | 37.413793 | 242 | 0.652603 | 3.191977 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionWithDemorgansLawIntention.kt | 1 | 7429 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.inspections.ReplaceNegatedIsEmptyWithIsNotEmptyInspection.Companion.invertSelectorFunction
import org.jetbrains.kotlin.idea.inspections.SimplifyNegatedBinaryExpressionInspection
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi2ir.deparenthesize
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isBoolean
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
sealed class ConvertFunctionWithDemorgansLawIntention(
intentionName: () -> String,
conversions: List<Conversion>,
) : SelfTargetingRangeIntention<KtCallExpression>(
KtCallExpression::class.java,
intentionName
) {
private val conversions = conversions.associateBy { it.fromFunctionName }
override fun applicabilityRange(element: KtCallExpression): TextRange? {
val callee = element.calleeExpression ?: return null
val (fromFunctionName, toFunctionName, _, _) = conversions[callee.text] ?: return null
val fqNames = functions[fromFunctionName] ?: return null
if (element.getQualifiedExpressionForSelector()?.getStrictParentOfType<KtDotQualifiedExpression>() != null) return null
val context = element.analyze(BodyResolveMode.PARTIAL)
if (element.getResolvedCall(context)?.resultingDescriptor?.fqNameOrNull() !in fqNames) return null
val lambda = element.singleLambdaArgumentExpression() ?: return null
val lambdaBody = lambda.bodyExpression ?: return null
if (lambdaBody.anyDescendantOfType<KtReturnExpression>()) return null
if (lambdaBody.statements.lastOrNull()?.getType(context)?.isBoolean() != true) return null
setTextGetter(KotlinBundle.lazyMessage("replace.0.with.1", fromFunctionName, toFunctionName))
return callee.textRange
}
override fun applyTo(element: KtCallExpression, editor: Editor?) {
val (_, toFunctionName, negateCall, negatePredicate) = conversions[element.calleeExpression?.text] ?: return
val lambda = element.singleLambdaArgumentExpression() ?: return
val lastExpression = lambda.bodyExpression?.statements?.lastOrNull() ?: return
val psiFactory = KtPsiFactory(element)
if (negatePredicate) {
val exclPrefixExpression = lastExpression.asExclPrefixExpression()
if (exclPrefixExpression == null) {
val replaced = lastExpression.replaced(psiFactory.createExpressionByPattern("!($0)", lastExpression)) as KtPrefixExpression
replaced.baseExpression.removeUnnecessaryParentheses()
when (val baseExpression = replaced.baseExpression?.deparenthesize()) {
is KtBinaryExpression -> {
val operationToken = baseExpression.operationToken
if (operationToken == KtTokens.ANDAND || operationToken == KtTokens.OROR) {
ConvertBinaryExpressionWithDemorgansLawIntention.convertIfPossible(baseExpression)
} else {
SimplifyNegatedBinaryExpressionInspection.simplifyNegatedBinaryExpressionIfNeeded(replaced)
}
}
is KtQualifiedExpression -> {
baseExpression.invertSelectorFunction()?.let { replaced.replace(it) }
}
}
} else {
val replaced = exclPrefixExpression.baseExpression?.let { lastExpression.replaced(it) }
replaced.removeUnnecessaryParentheses()
}
}
val callOrQualified = element.getQualifiedExpressionForSelector() ?: element
val parentExclPrefixExpression =
callOrQualified.parents.dropWhile { it is KtParenthesizedExpression }.firstOrNull()?.asExclPrefixExpression()
psiFactory.buildExpression {
appendFixedText(if (negateCall && parentExclPrefixExpression == null) "!" else "")
appendCallOrQualifiedExpression(element, toFunctionName)
}.let { (parentExclPrefixExpression ?: callOrQualified).replaced(it) }
}
private fun PsiElement.asExclPrefixExpression(): KtPrefixExpression? {
return safeAs<KtPrefixExpression>()?.takeIf { it.operationToken == KtTokens.EXCL && it.baseExpression != null }
}
private fun KtExpression?.removeUnnecessaryParentheses() {
if (this !is KtParenthesizedExpression) return
val innerExpression = this.expression ?: return
if (KtPsiUtil.areParenthesesUseless(this)) {
this.replace(innerExpression)
}
}
companion object {
private val collectionFunctions = listOf("all", "any", "none", "filter", "filterNot", "filterTo", "filterNotTo").associateWith {
listOf(FqName("kotlin.collections.$it"), FqName("kotlin.sequences.$it"))
}
private val standardFunctions = listOf("takeIf", "takeUnless").associateWith {
listOf(FqName("kotlin.$it"))
}
private val functions = collectionFunctions + standardFunctions
}
}
private data class Conversion(
val fromFunctionName: String,
val toFunctionName: String,
val negateCall: Boolean,
val negatePredicate: Boolean
)
class ConvertCallToOppositeIntention : ConvertFunctionWithDemorgansLawIntention(
KotlinBundle.lazyMessage("replace.function.call.with.the.opposite"),
listOf(
Conversion("all", "none", false, true),
Conversion("none", "all", false, true),
Conversion("filter", "filterNot", false, true),
Conversion("filterNot", "filter", false, true),
Conversion("filterTo", "filterNotTo", false, true),
Conversion("filterNotTo", "filterTo", false, true),
Conversion("takeIf", "takeUnless", false, true),
Conversion("takeUnless", "takeIf", false, true)
)
)
class ConvertAnyToAllAndViceVersaIntention : ConvertFunctionWithDemorgansLawIntention(
KotlinBundle.lazyMessage("replace.0.with.1.and.vice.versa", "any", "all"),
listOf(
Conversion("any", "all", true, true),
Conversion("all", "any", true, true)
)
)
class ConvertAnyToNoneAndViceVersaIntention : ConvertFunctionWithDemorgansLawIntention(
KotlinBundle.lazyMessage("replace.0.with.1.and.vice.versa", "any", "none"),
listOf(
Conversion("any", "none", true, false),
Conversion("none", "any", true, false)
)
)
| apache-2.0 | f5a6533e296bab3fb3294917d371bf8e | 47.555556 | 158 | 0.707632 | 5.302641 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionLiteralSignatureFix.kt | 1 | 3560 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.CollectingNameValidator
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.refactoring.changeSignature.*
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFunctionLiteral
import org.jetbrains.kotlin.types.KotlinType
class ChangeFunctionLiteralSignatureFix private constructor(
functionLiteral: KtFunctionLiteral,
functionDescriptor: FunctionDescriptor,
private val parameterTypes: List<KotlinType>
) : ChangeFunctionSignatureFix(functionLiteral, functionDescriptor) {
override fun getText() = KotlinBundle.message("fix.change.signature.lambda")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
runChangeSignature(
project,
editor,
functionDescriptor,
object : KotlinChangeSignatureConfiguration {
override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor {
return originalDescriptor.modify { descriptor ->
val validator = CollectingNameValidator()
descriptor.clearNonReceiverParameters()
for (type in parameterTypes) {
val name = KotlinNameSuggester.suggestNamesByType(type, validator, "param")[0]
descriptor.addParameter(KotlinParameterInfo(functionDescriptor, -1, name, KotlinTypeInfo(false, type)))
}
}
}
override fun performSilently(affectedFunctions: Collection<PsiElement>) = false
override fun forcePerformForSelectedFunctionOnly() = false
},
element,
text
)
}
companion object : KotlinSingleIntentionActionFactoryWithDelegate<KtFunctionLiteral, Companion.Data>() {
data class Data(val descriptor: FunctionDescriptor, val parameterTypes: List<KotlinType>)
override fun getElementOfInterest(diagnostic: Diagnostic): KtFunctionLiteral? {
val diagnosticWithParameters = Errors.EXPECTED_PARAMETERS_NUMBER_MISMATCH.cast(diagnostic)
return diagnosticWithParameters.psiElement as? KtFunctionLiteral
}
override fun extractFixData(element: KtFunctionLiteral, diagnostic: Diagnostic): Data? {
val descriptor = element.resolveToDescriptorIfAny() as? FunctionDescriptor ?: return null
val parameterTypes = Errors.EXPECTED_PARAMETERS_NUMBER_MISMATCH.cast(diagnostic).b
return Data(descriptor, parameterTypes)
}
override fun createFix(originalElement: KtFunctionLiteral, data: Data): IntentionAction? =
ChangeFunctionLiteralSignatureFix(originalElement, data.descriptor, data.parameterTypes)
}
}
| apache-2.0 | 20193873980ccaa81da82c1994f28010 | 48.444444 | 158 | 0.718258 | 5.884298 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/quickfix/TypeAccessibilityCheckerImpl.kt | 1 | 7338 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.idea.caches.project.isTestModule
import org.jetbrains.kotlin.idea.caches.project.toDescriptor
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtTypeParameter
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.isInlineClass
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeProjection
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isNullableAny
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class TypeAccessibilityCheckerImpl(
override val project: Project,
override val targetModule: Module,
override var existingTypeNames: Set<String> = emptySet()
) : TypeAccessibilityChecker {
private val scope by lazy { GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(targetModule, targetModule.isTestModule) }
private var builtInsModule: ModuleDescriptor? = targetModule.toDescriptor()
get() = if (field?.isValid != false) field
else {
field = targetModule.toDescriptor()
field
}
override fun incorrectTypes(declaration: KtNamedDeclaration): Collection<FqName?> = declaration.descriptor?.let {
incorrectTypesInDescriptor(it, false)
} ?: listOf(null)
override fun incorrectTypes(descriptor: DeclarationDescriptor): Collection<FqName?> = incorrectTypesInDescriptor(descriptor, false)
override fun incorrectTypes(type: KotlinType): Collection<FqName?> = incorrectTypesInSequence(type.collectAllTypes(), false)
override fun checkAccessibility(declaration: KtNamedDeclaration): Boolean =
declaration.descriptor?.let { checkAccessibility(it) } == true
override fun checkAccessibility(descriptor: DeclarationDescriptor): Boolean = incorrectTypesInDescriptor(descriptor, true).isEmpty()
override fun checkAccessibility(type: KotlinType): Boolean = incorrectTypesInSequence(type.collectAllTypes(), true).isEmpty()
override fun <R> runInContext(fqNames: Set<String>, block: TypeAccessibilityChecker.() -> R): R {
val oldValue = existingTypeNames
existingTypeNames = fqNames
return block().also { existingTypeNames = oldValue }
}
private fun incorrectTypesInSequence(
sequence: Sequence<FqName?>,
lazy: Boolean = true
): List<FqName?> {
val uniqueSequence = sequence.distinct().filter { !it.canFindClassInModule() }
return when {
uniqueSequence.none() -> emptyList()
lazy -> listOf(uniqueSequence.first())
else -> uniqueSequence.toList()
}
}
private fun incorrectTypesInDescriptor(descriptor: DeclarationDescriptor, lazy: Boolean) =
runInContext(descriptor.additionalClasses(existingTypeNames)) {
incorrectTypesInSequence(descriptor.collectAllTypes(), lazy)
}
private fun FqName?.canFindClassInModule(): Boolean {
val name = this?.asString() ?: return false
return name in existingTypeNames
|| KotlinFullClassNameIndex.get(name, project, scope).isNotEmpty()
|| builtInsModule?.resolveClassByFqName(this, NoLookupLocation.FROM_BUILTINS) != null
}
}
private tailrec fun DeclarationDescriptor.additionalClasses(existingClasses: Set<String> = emptySet()): Set<String> =
when (this) {
is ClassifierDescriptorWithTypeParameters -> {
val myParameters = existingClasses + declaredTypeParameters.map { it.fqNameOrNull()?.asString() ?: return emptySet() }
val containingDeclaration = containingDeclaration
if (isInner) containingDeclaration.additionalClasses(myParameters) else myParameters
}
is CallableDescriptor -> containingDeclaration.additionalClasses(
existingClasses = existingClasses + typeParameters.map { it.fqNameOrNull()?.asString() ?: return emptySet() }
)
else ->
existingClasses
}
private fun DeclarationDescriptor.collectAllTypes(): Sequence<FqName?> {
val annotations = annotations.asSequence().map(AnnotationDescriptor::type).flatMap(KotlinType::collectAllTypes)
return annotations + when (this) {
is ClassConstructorDescriptor -> valueParameters.asSequence().flatMap(DeclarationDescriptor::collectAllTypes)
is ClassDescriptor -> {
val primaryConstructorTypes = if (isInlineClass())
unsubstitutedPrimaryConstructor?.collectAllTypes().orEmpty()
else
emptySequence()
primaryConstructorTypes +
declaredTypeParameters.asSequence().flatMap(DeclarationDescriptor::collectAllTypes) +
sequenceOf(fqNameOrNull())
}
is CallableDescriptor -> {
val returnType = returnType ?: return sequenceOf(null)
returnType.collectAllTypes() +
explicitParameters.flatMap(DeclarationDescriptor::collectAllTypes) +
typeParameters.asSequence().flatMap(DeclarationDescriptor::collectAllTypes)
}
is TypeParameterDescriptor -> {
val upperBounds = upperBounds
val singleUpperBound = upperBounds.singleOrNull()
when {
// case for unresolved type
singleUpperBound?.isNullableAny() == true -> {
val extendBoundText = findPsi()?.safeAs<KtTypeParameter>()?.extendsBound?.text
if (extendBoundText == null || extendBoundText == "Any?") sequenceOf(singleUpperBound.fqName)
else sequenceOf(null)
}
upperBounds.isEmpty() -> sequenceOf(fqNameOrNull())
else -> upperBounds.asSequence().flatMap(KotlinType::collectAllTypes)
}
}
else -> emptySequence()
}
}
private fun KotlinType.collectAllTypes(): Sequence<FqName?> =
if (isError) {
sequenceOf(null)
} else {
sequenceOf(fqName) +
arguments.asSequence().map(TypeProjection::getType).flatMap(KotlinType::collectAllTypes) +
annotations.asSequence().map(AnnotationDescriptor::type).flatMap(KotlinType::collectAllTypes)
}
private val CallableDescriptor.explicitParameters: Sequence<ParameterDescriptor>
get() = valueParameters.asSequence() + dispatchReceiverParameter?.let {
sequenceOf(it)
}.orEmpty() + extensionReceiverParameter?.let {
sequenceOf(it)
}.orEmpty()
| apache-2.0 | 85a121e84145c7d9262472f15afd2557 | 45.443038 | 158 | 0.708776 | 5.559091 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceUtil.kt | 1 | 10515 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.introduce
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiRange
import org.jetbrains.kotlin.idea.core.surroundWith.KotlinSurrounderUtils
import org.jetbrains.kotlin.idea.util.ElementKind
import org.jetbrains.kotlin.idea.util.findElements
import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary
import org.jetbrains.kotlin.idea.refactoring.selectElement
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.utils.SmartList
fun showErrorHint(project: Project, editor: Editor, @NlsContexts.DialogMessage message: String, @NlsContexts.DialogTitle title: String) {
KotlinSurrounderUtils.showErrorHint(project, editor, message, title, null)
}
fun showErrorHintByKey(project: Project, editor: Editor, messageKey: String, @NlsContexts.DialogTitle title: String) {
showErrorHint(project, editor, KotlinBundle.message(messageKey), title)
}
fun selectElementsWithTargetSibling(
@NlsContexts.DialogTitle operationName: String,
editor: Editor,
file: KtFile,
@NlsContexts.DialogTitle title: String,
elementKinds: Collection<ElementKind>,
elementValidator: (List<PsiElement>) -> String?,
getContainers: (elements: List<PsiElement>, commonParent: PsiElement) -> List<PsiElement>,
continuation: (elements: List<PsiElement>, targetSibling: PsiElement) -> Unit
) {
fun onSelectionComplete(elements: List<PsiElement>, targetContainer: PsiElement) {
val physicalElements = elements.map { it.substringContextOrThis }
val parent = PsiTreeUtil.findCommonParent(physicalElements)
?: throw AssertionError("Should have at least one parent: ${physicalElements.joinToString("\n")}")
if (parent == targetContainer) {
continuation(elements, physicalElements.first())
return
}
val outermostParent = parent.getOutermostParentContainedIn(targetContainer)
if (outermostParent == null) {
showErrorHintByKey(file.project, editor, "cannot.refactor.no.container", operationName)
return
}
continuation(elements, outermostParent)
}
selectElementsWithTargetParent(operationName, editor, file, title, elementKinds, elementValidator, getContainers, ::onSelectionComplete)
}
fun selectElementsWithTargetParent(
@NlsContexts.DialogTitle operationName: String,
editor: Editor,
file: KtFile,
@NlsContexts.DialogTitle title: String,
elementKinds: Collection<ElementKind>,
elementValidator: (List<PsiElement>) -> String?,
getContainers: (elements: List<PsiElement>, commonParent: PsiElement) -> List<PsiElement>,
continuation: (elements: List<PsiElement>, targetParent: PsiElement) -> Unit
) {
fun showErrorHintByKey(key: String) {
showErrorHintByKey(file.project, editor, key, operationName)
}
fun selectTargetContainer(elements: List<PsiElement>) {
elementValidator(elements)?.let {
showErrorHint(file.project, editor, it, operationName)
return
}
val physicalElements = elements.map { it.substringContextOrThis }
val parent = PsiTreeUtil.findCommonParent(physicalElements)
?: throw AssertionError("Should have at least one parent: ${physicalElements.joinToString("\n")}")
val containers = getContainers(physicalElements, parent)
if (containers.isEmpty()) {
showErrorHintByKey("cannot.refactor.no.container")
return
}
chooseContainerElementIfNecessary(
containers,
editor,
title,
true
) {
continuation(elements, it)
}
}
fun selectMultipleElements() {
val startOffset = editor.selectionModel.selectionStart
val endOffset = editor.selectionModel.selectionEnd
val elements = elementKinds.flatMap { findElements(file, startOffset, endOffset, it).toList() }
if (elements.isEmpty()) {
return when (elementKinds.singleOrNull()) {
ElementKind.EXPRESSION -> showErrorHintByKey("cannot.refactor.no.expression")
ElementKind.TYPE_ELEMENT -> showErrorHintByKey("cannot.refactor.no.type")
else -> showErrorHint(
file.project,
editor,
KotlinBundle.message("text.refactoring.can.t.be.performed.on.the.selected.code.element"),
title
)
}
}
selectTargetContainer(elements)
}
fun selectSingleElement() {
selectElement(editor, file, false, elementKinds) { expr ->
if (expr != null) {
selectTargetContainer(listOf(expr))
} else {
if (!editor.selectionModel.hasSelection()) {
if (elementKinds.singleOrNull() == ElementKind.EXPRESSION) {
val elementAtCaret = file.findElementAt(editor.caretModel.offset)
elementAtCaret?.getParentOfTypeAndBranch<KtProperty> { nameIdentifier }?.let {
return@selectElement selectTargetContainer(listOf(it))
}
}
editor.selectionModel.selectLineAtCaret()
}
selectMultipleElements()
}
}
}
editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE)
selectSingleElement()
}
fun PsiElement.findExpressionByCopyableDataAndClearIt(key: Key<Boolean>): KtExpression? {
val result = findDescendantOfType<KtExpression> { it.getCopyableUserData(key) != null } ?: return null
result.putCopyableUserData(key, null)
return result
}
fun PsiElement.findElementByCopyableDataAndClearIt(key: Key<Boolean>): PsiElement? {
val result = findDescendantOfType<PsiElement> { it.getCopyableUserData(key) != null } ?: return null
result.putCopyableUserData(key, null)
return result
}
fun PsiElement.findExpressionsByCopyableDataAndClearIt(key: Key<Boolean>): List<KtExpression> {
val results = collectDescendantsOfType<KtExpression> { it.getCopyableUserData(key) != null }
results.forEach { it.putCopyableUserData(key, null) }
return results
}
fun findExpressionOrStringFragment(file: KtFile, startOffset: Int, endOffset: Int): KtExpression? {
val entry1 = file.findElementAt(startOffset)?.getNonStrictParentOfType<KtStringTemplateEntry>() ?: return null
val entry2 = file.findElementAt(endOffset - 1)?.getNonStrictParentOfType<KtStringTemplateEntry>() ?: return null
if (entry1 == entry2 && entry1 is KtStringTemplateEntryWithExpression) return entry1.expression
val stringTemplate = entry1.parent as? KtStringTemplateExpression ?: return null
if (entry2.parent != stringTemplate) return null
val templateOffset = stringTemplate.startOffset
if (stringTemplate.getContentRange().equalsToRange(startOffset - templateOffset, endOffset - templateOffset)) return stringTemplate
val prefixOffset = startOffset - entry1.startOffset
if (entry1 !is KtLiteralStringTemplateEntry && prefixOffset > 0) return null
val suffixOffset = endOffset - entry2.startOffset
if (entry2 !is KtLiteralStringTemplateEntry && suffixOffset < entry2.textLength) return null
val prefix = entry1.text.substring(0, prefixOffset)
val suffix = entry2.text.substring(suffixOffset)
return ExtractableSubstringInfo(entry1, entry2, prefix, suffix).createExpression()
}
fun KotlinPsiRange.getPhysicalTextRange(): TextRange {
return (elements.singleOrNull() as? KtExpression)?.extractableSubstringInfo?.contentRange ?: textRange
}
fun ExtractableSubstringInfo.replaceWith(replacement: KtExpression): KtExpression {
return with(this) {
val psiFactory = KtPsiFactory(replacement.project)
val parent = startEntry.parent
psiFactory.createStringTemplate(prefix).entries.singleOrNull()?.let { parent.addBefore(it, startEntry) }
val refEntry = psiFactory.createBlockStringTemplateEntry(replacement)
val addedRefEntry = parent.addBefore(refEntry, startEntry) as KtStringTemplateEntryWithExpression
psiFactory.createStringTemplate(suffix).entries.singleOrNull()?.let { parent.addAfter(it, endEntry) }
parent.deleteChildRange(startEntry, endEntry)
addedRefEntry.expression!!
}
}
fun KtExpression.mustBeParenthesizedInInitializerPosition(): Boolean {
if (this !is KtBinaryExpression) return false
if (left?.mustBeParenthesizedInInitializerPosition() == true) return true
return PsiChildRange(left, operationReference).any { (it is PsiWhiteSpace) && it.textContains('\n') }
}
fun isObjectOrNonInnerClass(e: PsiElement): Boolean = e is KtObjectDeclaration || (e is KtClass && !e.isInner())
fun <T : KtDeclaration> insertDeclaration(declaration: T, targetSibling: PsiElement): T {
val targetParent = targetSibling.parent
val anchorCandidates = SmartList<PsiElement>()
anchorCandidates.add(targetSibling)
if (targetSibling is KtEnumEntry) {
anchorCandidates.add(targetSibling.siblings().last { it is KtEnumEntry })
}
val anchor = anchorCandidates.minByOrNull { it.startOffset }!!.parentsWithSelf.first { it.parent == targetParent }
val targetContainer = anchor.parent!!
@Suppress("UNCHECKED_CAST")
return (targetContainer.addBefore(declaration, anchor) as T).apply {
targetContainer.addBefore(KtPsiFactory(declaration.project).createWhiteSpace("\n\n"), anchor)
}
}
internal fun validateExpressionElements(elements: List<PsiElement>): String? {
if (elements.any { it is KtConstructor<*> || it is KtParameter || it is KtTypeAlias || it is KtPropertyAccessor }) {
return KotlinBundle.message("text.refactoring.is.not.applicable.to.this.code.fragment")
}
return null
}
| apache-2.0 | 304617056b0eefabb2b4cc12b4ab082a | 41.743902 | 158 | 0.714218 | 5.177253 | false | false | false | false |
HITGIF/SchoolPower | app/src/main/java/kotterknife/ButterKnife.kt | 2 | 6844 | package kotterknife
import android.app.Activity
import android.app.Dialog
import android.app.DialogFragment
import android.app.Fragment
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.View
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
import android.support.v4.app.DialogFragment as SupportDialogFragment
import android.support.v4.app.Fragment as SupportFragment
public fun <V : View> View.bindView(id: Int)
: ReadOnlyProperty<View, V> = required(id, viewFinder)
public fun <V : View> Activity.bindView(id: Int)
: ReadOnlyProperty<Activity, V> = required(id, viewFinder)
public fun <V : View> Dialog.bindView(id: Int)
: ReadOnlyProperty<Dialog, V> = required(id, viewFinder)
public fun <V : View> DialogFragment.bindView(id: Int)
: ReadOnlyProperty<DialogFragment, V> = required(id, viewFinder)
public fun <V : View> SupportDialogFragment.bindView(id: Int)
: ReadOnlyProperty<SupportDialogFragment, V> = required(id, viewFinder)
public fun <V : View> Fragment.bindView(id: Int)
: ReadOnlyProperty<Fragment, V> = required(id, viewFinder)
public fun <V : View> SupportFragment.bindView(id: Int)
: ReadOnlyProperty<SupportFragment, V> = required(id, viewFinder)
public fun <V : View> ViewHolder.bindView(id: Int)
: ReadOnlyProperty<ViewHolder, V> = required(id, viewFinder)
public fun <V : View> View.bindOptionalView(id: Int)
: ReadOnlyProperty<View, V?> = optional(id, viewFinder)
public fun <V : View> Activity.bindOptionalView(id: Int)
: ReadOnlyProperty<Activity, V?> = optional(id, viewFinder)
public fun <V : View> Dialog.bindOptionalView(id: Int)
: ReadOnlyProperty<Dialog, V?> = optional(id, viewFinder)
public fun <V : View> DialogFragment.bindOptionalView(id: Int)
: ReadOnlyProperty<DialogFragment, V?> = optional(id, viewFinder)
public fun <V : View> SupportDialogFragment.bindOptionalView(id: Int)
: ReadOnlyProperty<SupportDialogFragment, V?> = optional(id, viewFinder)
public fun <V : View> Fragment.bindOptionalView(id: Int)
: ReadOnlyProperty<Fragment, V?> = optional(id, viewFinder)
public fun <V : View> SupportFragment.bindOptionalView(id: Int)
: ReadOnlyProperty<SupportFragment, V?> = optional(id, viewFinder)
public fun <V : View> ViewHolder.bindOptionalView(id: Int)
: ReadOnlyProperty<ViewHolder, V?> = optional(id, viewFinder)
public fun <V : View> View.bindViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = required(ids, viewFinder)
public fun <V : View> Activity.bindViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = required(ids, viewFinder)
public fun <V : View> Dialog.bindViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = required(ids, viewFinder)
public fun <V : View> DialogFragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<DialogFragment, List<V>> = required(ids, viewFinder)
public fun <V : View> SupportDialogFragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<SupportDialogFragment, List<V>> = required(ids, viewFinder)
public fun <V : View> Fragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<Fragment, List<V>> = required(ids, viewFinder)
public fun <V : View> SupportFragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<SupportFragment, List<V>> = required(ids, viewFinder)
public fun <V : View> ViewHolder.bindViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = required(ids, viewFinder)
public fun <V : View> View.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = optional(ids, viewFinder)
public fun <V : View> Activity.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = optional(ids, viewFinder)
public fun <V : View> Dialog.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = optional(ids, viewFinder)
public fun <V : View> DialogFragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<DialogFragment, List<V>> = optional(ids, viewFinder)
public fun <V : View> SupportDialogFragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<SupportDialogFragment, List<V>> = optional(ids, viewFinder)
public fun <V : View> Fragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Fragment, List<V>> = optional(ids, viewFinder)
public fun <V : View> SupportFragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<SupportFragment, List<V>> = optional(ids, viewFinder)
public fun <V : View> ViewHolder.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = optional(ids, viewFinder)
private val View.viewFinder: View.(Int) -> View?
get() = { findViewById(it) }
private val Activity.viewFinder: Activity.(Int) -> View?
get() = { findViewById(it) }
private val Dialog.viewFinder: Dialog.(Int) -> View?
get() = { findViewById(it) }
private val DialogFragment.viewFinder: DialogFragment.(Int) -> View?
get() = { dialog.findViewById(it) }
private val SupportDialogFragment.viewFinder: SupportDialogFragment.(Int) -> View?
get() = { dialog.findViewById(it) }
private val Fragment.viewFinder: Fragment.(Int) -> View?
get() = { view.findViewById(it) }
private val SupportFragment.viewFinder: SupportFragment.(Int) -> View?
get() = { view!!.findViewById(it) }
private val ViewHolder.viewFinder: ViewHolder.(Int) -> View?
get() = { itemView.findViewById(it) }
private fun viewNotFound(id:Int, desc: KProperty<*>): Nothing =
throw IllegalStateException("View ID $id for '${desc.name}' not found.")
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> required(id: Int, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> t.finder(id) as V? ?: viewNotFound(id, desc) }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> optional(id: Int, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> t.finder(id) as V? }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> required(ids: IntArray, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> ids.map { t.finder(it) as V? ?: viewNotFound(it, desc) } }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> optional(ids: IntArray, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> ids.map { t.finder(it) as V? }.filterNotNull() }
// Like Kotlin's lazy delegate but the initializer gets the target and metadata passed to it
private class Lazy<T, V>(private val initializer: (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> {
private object EMPTY
private var value: Any? = EMPTY
override fun getValue(thisRef: T, property: KProperty<*>): V {
if (value == EMPTY) {
value = initializer(thisRef, property)
}
@Suppress("UNCHECKED_CAST")
return value as V
}
} | apache-2.0 | 6a2e030df7a6eb6c9978e28c1fde55d3 | 51.653846 | 100 | 0.70339 | 3.958357 | false | false | false | false |
androidx/androidx | core/uwb/uwb/src/main/java/androidx/core/uwb/impl/UwbManagerImpl.kt | 3 | 6366 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.uwb.impl
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.util.Log
import androidx.core.uwb.RangingCapabilities
import androidx.core.uwb.UwbAddress
import androidx.core.uwb.UwbClientSessionScope
import androidx.core.uwb.UwbComplexChannel
import androidx.core.uwb.UwbControleeSessionScope
import androidx.core.uwb.UwbControllerSessionScope
import androidx.core.uwb.UwbManager
import androidx.core.uwb.backend.IUwb
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.nearby.Nearby
import kotlinx.coroutines.tasks.await
import androidx.core.uwb.helper.checkSystemFeature
import androidx.core.uwb.helper.handleApiException
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
internal class UwbManagerImpl(private val context: Context) : UwbManager {
companion object {
const val TAG = "UwbMangerImpl"
var iUwb: IUwb? = null
}
init {
val connection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
iUwb = IUwb.Stub.asInterface(service)
Log.i(TAG, "iUwb service created successfully.")
}
override fun onServiceDisconnected(p0: ComponentName?) {
iUwb = null
}
}
val intent = Intent("androidx.core.uwb.backend.service")
intent.setPackage("androidx.core.uwb.backend")
context.bindService(intent, connection, Context.BIND_AUTO_CREATE)
}
@Deprecated("Renamed to controleeSessionScope")
override suspend fun clientSessionScope(): UwbClientSessionScope {
return createClientSessionScope(false)
}
override suspend fun controleeSessionScope(): UwbControleeSessionScope {
return createClientSessionScope(false) as UwbControleeSessionScope
}
override suspend fun controllerSessionScope(): UwbControllerSessionScope {
return createClientSessionScope(true) as UwbControllerSessionScope
}
private suspend fun createClientSessionScope(isController: Boolean): UwbClientSessionScope {
checkSystemFeature(context)
val hasGmsCore = GoogleApiAvailability.getInstance()
.isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS
return if (hasGmsCore) createGmsClientSessionScope(isController)
else createAospClientSessionScope(isController)
}
private suspend fun createGmsClientSessionScope(isController: Boolean): UwbClientSessionScope {
Log.i(TAG, "Creating Gms Client session scope")
val uwbClient = if (isController)
Nearby.getUwbControllerClient(context) else Nearby.getUwbControleeClient(context)
try {
val nearbyLocalAddress = uwbClient.localAddress.await()
val nearbyRangingCapabilities = uwbClient.rangingCapabilities.await()
val localAddress = UwbAddress(nearbyLocalAddress.address)
val rangingCapabilities = RangingCapabilities(
nearbyRangingCapabilities.supportsDistance(),
nearbyRangingCapabilities.supportsAzimuthalAngle(),
nearbyRangingCapabilities.supportsElevationAngle())
return if (isController) {
val uwbComplexChannel = uwbClient.complexChannel.await()
UwbControllerSessionScopeImpl(
uwbClient,
rangingCapabilities,
localAddress,
UwbComplexChannel(uwbComplexChannel.channel, uwbComplexChannel.preambleIndex)
)
} else {
UwbControleeSessionScopeImpl(
uwbClient,
rangingCapabilities,
localAddress
)
}
} catch (e: ApiException) {
handleApiException(e)
throw RuntimeException("Unexpected error. This indicates that the library is not " +
"up-to-date with the service backend.")
}
}
private fun createAospClientSessionScope(isController: Boolean): UwbClientSessionScope {
Log.i(TAG, "Creating Aosp Client session scope")
val uwbClient = if (isController)
iUwb?.controllerClient else iUwb?.controleeClient
if (uwbClient == null) {
Log.e(TAG, "Failed to get UwbClient. AOSP backend is not available.")
}
try {
val aospLocalAddress = uwbClient!!.localAddress
val aospRangingCapabilities = uwbClient.rangingCapabilities
val localAddress = aospLocalAddress?.address?.let { UwbAddress(it) }
val rangingCapabilities = aospRangingCapabilities?.let {
RangingCapabilities(
it.supportsDistance,
it.supportsAzimuthalAngle,
it.supportsElevationAngle)
}
return if (isController) {
val uwbComplexChannel = uwbClient.complexChannel
UwbControllerSessionScopeAospImpl(
uwbClient,
rangingCapabilities!!,
localAddress!!,
UwbComplexChannel(uwbComplexChannel!!.channel, uwbComplexChannel.preambleIndex)
)
} else {
UwbControleeSessionScopeAospImpl(
uwbClient,
rangingCapabilities!!,
localAddress!!
)
}
} catch (e: Exception) {
throw e
}
}
} | apache-2.0 | 3c9a53c22ef532936d1abb8fd7de9af4 | 40.888158 | 99 | 0.665724 | 5.589113 | false | false | false | false |
androidx/androidx | benchmark/gradle-plugin/src/main/kotlin/androidx/benchmark/gradle/UnlockClocksTask.kt | 3 | 1507 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.benchmark.gradle
import org.gradle.api.DefaultTask
import org.gradle.api.logging.LogLevel
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.property
import org.gradle.work.DisableCachingByDefault
@Suppress("UnstableApiUsage")
@DisableCachingByDefault(
because = "UnlockClocks affects device state, and may be modified/reset outside of this task"
)
open class UnlockClocksTask : DefaultTask() {
init {
group = "Android"
description = "unlocks clocks of device by rebooting"
}
@Input
val adbPath: Property<String> = project.objects.property()
@TaskAction
fun exec() {
val adb = Adb(adbPath.get(), logger)
project.logger.log(LogLevel.LIFECYCLE, "Rebooting device to reset clocks")
adb.execSync("reboot")
}
}
| apache-2.0 | d4f5c77b3d1deceec7bc60beebfbdff9 | 31.76087 | 97 | 0.733245 | 4.128767 | false | false | false | false |
androidx/androidx | collection/collection/src/commonMain/kotlin/androidx/collection/SimpleArrayMap.kt | 3 | 25600 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.collection
import androidx.collection.internal.EMPTY_INTS
import androidx.collection.internal.EMPTY_OBJECTS
import androidx.collection.internal.binarySearch
import kotlin.jvm.JvmName
import kotlin.jvm.JvmOverloads
private const val DEBUG = false
private const val TAG = "ArrayMap"
/**
* Attempt to spot concurrent modifications to this data structure.
*
* It's best-effort, but any time we can throw something more diagnostic than an
* ArrayIndexOutOfBoundsException deep in the ArrayMap internals it's going to
* save a lot of development time.
*
* Good times to look for CME include after any allocArrays() call and at the end of
* functions that change mSize (put/remove/clear).
*/
private const val CONCURRENT_MODIFICATION_EXCEPTIONS = true
/**
* The minimum amount by which the capacity of a ArrayMap will increase.
* This is tuned to be relatively space-efficient.
*/
private const val BASE_SIZE = 4
/**
* Base implementation of [ArrayMap][androidx.collection.ArrayMap] that doesn't include any standard
* Java container API interoperability. These features are generally heavier-weight ways
* to interact with the container, so discouraged, but they can be useful to make it
* easier to use as a drop-in replacement for HashMap. If you don't need them, this
* class can be preferable since it doesn't bring in any of the implementation of those
* APIs, allowing that code to be stripped by ProGuard.
*
* @constructor Create a new [SimpleArrayMap] with a given initial capacity. The default capacity of
* an array map is 0, and will grow once items are added to it.
*/
public open class SimpleArrayMap<K, V> @JvmOverloads public constructor(capacity: Int = 0) {
private var hashes: IntArray = when (capacity) {
0 -> EMPTY_INTS
else -> IntArray(capacity)
}
private var array: Array<Any?> = when (capacity) {
0 -> EMPTY_OBJECTS
else -> arrayOfNulls<Any?>(capacity shl 1)
}
private var size: Int = 0
/**
* Create a new [SimpleArrayMap] with the mappings from the given [map].
*/
public constructor(map: SimpleArrayMap<out K, out V>?) : this() {
if (map != null) {
this.putAll(map)
}
}
/**
* Returns the index of a key in the set, given its [hashCode]. This is a helper for the
* non-null case of [indexOfKey].
*
* @param key The key to search for.
* @param hash Pre-computed [hashCode] of [key].
* @return Returns the index of the key if it exists, else a negative integer.
*/
private fun indexOf(key: K, hash: Int): Int {
val n = size
// Important fast case: if nothing is in here, nothing to look for.
if (n == 0) {
return 0.inv()
}
val index = binarySearch(hashes, n, hash)
// If the hash code wasn't found, then we have no entry for this key.
if (index < 0) {
return index
}
// If the key at the returned index matches, that's what we want.
if (key == array[index shl 1]) {
return index
}
// Search for a matching key after the index.
var end: Int = index + 1
while (end < n && hashes[end] == hash) {
if (key == array[end shl 1]) return end
end++
}
// Search for a matching key before the index.
var i = index - 1
while (i >= 0 && hashes[i] == hash) {
if (key == array[i shl 1]) {
return i
}
i--
}
// Key not found -- return negative value indicating where a
// new entry for this key should go. We use the end of the
// hash chain to reduce the number of array entries that will
// need to be copied when inserting.
return end.inv()
}
private fun indexOfNull(): Int {
val n = size
// Important fast case: if nothing is in here, nothing to look for.
if (n == 0) {
return 0.inv()
}
val index = binarySearch(hashes, n, 0)
// If the hash code wasn't found, then we have no entry for this key.
if (index < 0) {
return index
}
// If the key at the returned index matches, that's what we want.
if (null == array[index shl 1]) {
return index
}
// Search for a matching key after the index.
var end: Int = index + 1
while (end < n && hashes[end] == 0) {
if (null == array[end shl 1]) return end
end++
}
// Search for a matching key before the index.
var i = index - 1
while (i >= 0 && hashes[i] == 0) {
if (null == array[i shl 1]) return i
i--
}
// Key not found -- return negative value indicating where a
// new entry for this key should go. We use the end of the
// hash chain to reduce the number of array entries that will
// need to be copied when inserting.
return end.inv()
}
/**
* Make the array map empty. All storage is released.
*
* @throws ConcurrentModificationException if it was detected that this [SimpleArrayMap] was
* written to while this operation was running.
*/
public open fun clear() {
if (size > 0) {
hashes = EMPTY_INTS
array = EMPTY_OBJECTS
size = 0
}
@Suppress("KotlinConstantConditions")
if (CONCURRENT_MODIFICATION_EXCEPTIONS && size > 0) {
throw ConcurrentModificationException()
}
}
/**
* Ensure the array map can hold at least [minimumCapacity] items.
*
* @throws ConcurrentModificationException if it was detected that this [SimpleArrayMap] was
* written to while this operation was running.
*/
public open fun ensureCapacity(minimumCapacity: Int) {
val osize = size
if (hashes.size < minimumCapacity) {
hashes = hashes.copyOf(minimumCapacity)
array = array.copyOf(minimumCapacity * 2)
}
if (CONCURRENT_MODIFICATION_EXCEPTIONS && size != osize) {
throw ConcurrentModificationException()
}
}
/**
* Check whether a key exists in the array.
*
* @param key The key to search for.
* @return Returns `true` if the key exists, else `false`.
*/
public open fun containsKey(key: K): Boolean {
return indexOfKey(key) >= 0
}
/**
* Returns the index of a key in the set.
*
* @param key The key to search for.
* @return Returns the index of the key if it exists, else a negative integer.
*/
public open fun indexOfKey(key: K): Int = when (key) {
null -> indexOfNull()
else -> indexOf(key, key.hashCode())
}
// @RestrictTo is required since internal is implemented as public with name mangling in Java
// and we are overriding the name mangling to make it callable from a Java subclass in this
// package (ArrayMap).
@JvmName("__restricted\$indexOfValue")
internal fun indexOfValue(value: V): Int {
val n = size * 2
val array = array
if (value == null) {
var i = 1
while (i < n) {
if (array[i] == null) {
return i shr 1
}
i += 2
}
} else {
var i = 1
while (i < n) {
if (value == array[i]) {
return i shr 1
}
i += 2
}
}
return -1
}
/**
* Check whether a value exists in the array. This requires a linear search
* through the entire array.
*
* @param value The value to search for.
* @return Returns `true` if the value exists, else `false`.
*/
public open fun containsValue(value: V): Boolean {
return indexOfValue(value) >= 0
}
/**
* Retrieve a value from the array.
*
* @param key The key of the value to retrieve.
* @return Returns the value associated with the given key, or `null` if there is no such key.
*/
public open operator fun get(key: K): V? {
return getOrDefaultInternal(key, null)
}
/**
* Retrieve a value from the array, or [defaultValue] if there is no mapping for the key.
*
* @param key The key of the value to retrieve.
* @param defaultValue The default mapping of the key
* @return Returns the value associated with the given key, or [defaultValue] if there is no
* mapping for the key.
*/
// Unfortunately key must stay of type Any? otherwise it will not register as an override of
// Java's Map interface, which is necessary since ArrayMap is written in Java and implements
// both Map and SimpleArrayMap.
public open fun getOrDefault(key: Any?, defaultValue: V): V {
return getOrDefaultInternal(key, defaultValue)
}
@Suppress("NOTHING_TO_INLINE")
private inline fun <T : V?> getOrDefaultInternal(key: Any?, defaultValue: T): T {
@Suppress("UNCHECKED_CAST")
val index = indexOfKey(key as K)
@Suppress("UNCHECKED_CAST")
return when {
index >= 0 -> array[(index shl 1) + 1] as T
else -> defaultValue
}
}
/**
* Return the key at the given index in the array.
*
* @param index The desired index, must be between 0 and [size]-1 (inclusive).
* @return Returns the key stored at the given index.
* @throws IllegalArgumentException if [index] is not between 0 and [size]-1
*/
public open fun keyAt(index: Int): K {
require(index in 0 until size) {
"Expected index to be within 0..size()-1, but was $index"
}
@Suppress("UNCHECKED_CAST")
return array[index shl 1] as K
}
/**
* Return the value at the given index in the array.
*
* @param index The desired index, must be between 0 and [size]-1 (inclusive).
* @return Returns the value stored at the given index.
* @throws IllegalArgumentException if [index] is not between 0 and [size]-1
*/
public open fun valueAt(index: Int): V {
require(index in 0 until size) {
"Expected index to be within 0..size()-1, but was $index"
}
@Suppress("UNCHECKED_CAST")
return array[(index shl 1) + 1] as V
}
/**
* Set the value at a given index in the array.
*
* @param index The desired index, must be between 0 and [size]-1 (inclusive).
* @param value The new value to store at this index.
* @return Returns the previous value at the given index.
* @throws IllegalArgumentException if [index] is not between 0 and [size]-1
*/
public open fun setValueAt(index: Int, value: V): V {
require(index in 0 until size) {
"Expected index to be within 0..size()-1, but was $index"
}
val indexInArray = (index shl 1) + 1
@Suppress("UNCHECKED_CAST")
val old = array[indexInArray] as V
array[indexInArray] = value
return old
}
/**
* Return `true` if the array map contains no items.
*/
public open fun isEmpty(): Boolean = size <= 0
/**
* Add a new value to the array map.
*
* @param key The key under which to store the value. If this key already exists in the array,
* its value will be replaced.
* @param value The value to store for the given key.
* @return Returns the old value that was stored for the given key, or `null` if there
* was no such key.
* @throws ConcurrentModificationException if it was detected that this [SimpleArrayMap] was
* written to while this operation was running.
*/
public open fun put(key: K, value: V): V? {
val osize = size
val hash: Int = key?.hashCode() ?: 0
var index: Int = key?.let { indexOf(it, hash) } ?: indexOfNull()
if (index >= 0) {
index = (index shl 1) + 1
@Suppress("UNCHECKED_CAST")
val old = array[index] as V?
array[index] = value
return old
}
index = index.inv()
if (osize >= hashes.size) {
val n = when {
osize >= BASE_SIZE * 2 -> osize + (osize shr 1)
osize >= BASE_SIZE -> BASE_SIZE * 2
else -> BASE_SIZE
}
if (DEBUG) {
println("$TAG put: grow from ${hashes.size} to $n")
}
hashes = hashes.copyOf(n)
array = array.copyOf(n shl 1)
if (CONCURRENT_MODIFICATION_EXCEPTIONS && osize != size) {
throw ConcurrentModificationException()
}
}
if (index < osize) {
if (DEBUG) {
println("$TAG put: move $index-${osize - index} to ${index + 1}")
}
hashes.copyInto(hashes, index + 1, index, osize)
array.copyInto(array, (index + 1) shl 1, index shl 1, size shl 1)
}
if (CONCURRENT_MODIFICATION_EXCEPTIONS && (osize != size || index >= hashes.size)) {
throw ConcurrentModificationException()
}
hashes[index] = hash
array[index shl 1] = key
array[(index shl 1) + 1] = value
size++
return null
}
/**
* Perform a [put] of all key/value pairs in [map]
*
* @param map The array whose contents are to be retrieved.
*/
public open fun putAll(map: SimpleArrayMap<out K, out V>) {
val n = map.size
ensureCapacity(size + n)
if (size == 0) {
if (n > 0) {
map.hashes.copyInto(
destination = hashes,
destinationOffset = 0,
startIndex = 0,
endIndex = n
)
map.array.copyInto(
destination = array,
destinationOffset = 0,
startIndex = 0,
endIndex = n shl 1
)
size = n
}
} else {
for (i in 0 until n) {
put(map.keyAt(i), map.valueAt(i))
}
}
}
/**
* Add a new value to the array map only if the key does not already have a value or it is
* mapped to `null`.
*
* @param key The key under which to store the value.
* @param value The value to store for the given key.
* @return Returns the value that was stored for the given key, or `null` if there was no such
* key.
*/
public open fun putIfAbsent(key: K, value: V): V? {
var mapValue = get(key)
if (mapValue == null) {
mapValue = put(key, value)
}
return mapValue
}
/**
* Remove an existing key from the array map.
*
* @param key The key of the mapping to remove.
* @return Returns the value that was stored under the key, or `null` if there was no such key.
*/
public open fun remove(key: K): V? {
val index = indexOfKey(key)
return if (index >= 0) {
removeAt(index)
} else null
}
/**
* Remove an existing key from the array map only if it is currently mapped to [value].
*
* @param key The key of the mapping to remove.
* @param value The value expected to be mapped to the key.
* @return Returns `true` if the mapping was removed.
*/
public open fun remove(key: K, value: V): Boolean {
val index = indexOfKey(key)
if (index >= 0) {
val mapValue = valueAt(index)
if (value == mapValue) {
removeAt(index)
return true
}
}
return false
}
/**
* Remove the key/value mapping at the given index.
*
* @param index The desired index, must be between 0 and [size]-1 (inclusive).
* @return Returns the value that was stored at this index.
* @throws ConcurrentModificationException if it was detected that this [SimpleArrayMap] was
* written to while this operation was running.
* @throws IllegalArgumentException if [index] is not between 0 and [size]-1
*/
public open fun removeAt(index: Int): V {
require(index in 0 until size) {
"Expected index to be within 0..size()-1, but was $index"
}
val old = array[(index shl 1) + 1]
val osize = size
if (osize <= 1) {
// Now empty.
if (DEBUG) {
println("$TAG remove: shrink from ${hashes.size} to 0")
}
clear()
} else {
val nsize = osize - 1
if (hashes.size > (BASE_SIZE * 2) && osize < hashes.size / 3) {
// Shrunk enough to reduce size of arrays. We don't allow it to
// shrink smaller than (BASE_SIZE*2) to avoid flapping between
// that and BASE_SIZE.
val n = when {
osize > (BASE_SIZE * 2) -> osize + (osize shr 1)
else -> BASE_SIZE * 2
}
if (DEBUG) {
println("$TAG remove: shrink from ${hashes.size} to $n")
}
val ohashes = hashes
val oarray: Array<Any?> = array
hashes = hashes.copyOf(n)
array = array.copyOf(n shl 1)
if (CONCURRENT_MODIFICATION_EXCEPTIONS && osize != size) {
throw ConcurrentModificationException()
}
if (index > 0) {
if (DEBUG) {
println("$TAG remove: copy from 0-$index to 0")
}
ohashes.copyInto(
destination = hashes,
destinationOffset = 0,
startIndex = 0,
endIndex = index
)
oarray.copyInto(
destination = array,
destinationOffset = 0,
startIndex = 0,
endIndex = index shl 1
)
}
if (index < nsize) {
if (DEBUG) {
println("$TAG remove: copy from ${index + 1}-$nsize to $index")
}
ohashes.copyInto(
destination = hashes,
destinationOffset = index,
startIndex = index + 1,
endIndex = nsize + 1
)
oarray.copyInto(
destination = array,
destinationOffset = index shl 1,
startIndex = (index + 1) shl 1,
endIndex = (nsize + 1) shl 1
)
}
} else {
if (index < nsize) {
if (DEBUG) {
println("$TAG remove: move ${index + 1}-$nsize to $index")
}
hashes.copyInto(
destination = hashes,
destinationOffset = index,
startIndex = index + 1,
endIndex = nsize + 1
)
array.copyInto(
destination = array,
destinationOffset = index shl 1,
startIndex = (index + 1) shl 1,
endIndex = (nsize + 1) shl 1
)
}
array[nsize shl 1] = null
array[(nsize shl 1) + 1] = null
}
if (CONCURRENT_MODIFICATION_EXCEPTIONS && osize != size) {
throw ConcurrentModificationException()
}
size = nsize
}
@Suppress("UNCHECKED_CAST")
return old as V
}
/**
* Replace the mapping for [key] only if it is already mapped to a value.
*
* @param key The key of the mapping to replace.
* @param value The value to store for the given key.
* @return Returns the previous mapped value or `null`.
*/
public open fun replace(key: K, value: V): V? {
val index = indexOfKey(key)
return when {
index >= 0 -> setValueAt(index, value)
else -> null
}
}
/**
* Replace the mapping for [key] only if it is already mapped to [oldValue].
*
* @param key The key of the mapping to replace.
* @param oldValue The value expected to be mapped to the key.
* @param newValue The value to store for the given key.
* @return Returns `true` if the value was replaced.
*/
public open fun replace(key: K, oldValue: V, newValue: V): Boolean {
val index = indexOfKey(key)
if (index >= 0) {
val mapValue = valueAt(index)
if (oldValue == mapValue) {
setValueAt(index, newValue)
return true
}
}
return false
}
/**
* Return the number of items in this array map.
*/
public open fun size(): Int {
return size
}
/**
* This implementation returns `false` if the object is not a [Map] or
* [SimpleArrayMap], or if the maps have different sizes. Otherwise, for each
* key in this map, values of both maps are compared. If the values for any
* key are not equal, the method returns false, otherwise it returns `true`.
*/
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
try {
if (other is SimpleArrayMap<*, *>) {
if (size() != other.size()) {
return false
}
@Suppress("UNCHECKED_CAST")
val otherSimpleArrayMap = other as SimpleArrayMap<Any?, Any?>
for (i in 0 until size) {
val key = keyAt(i)
val mine = valueAt(i)
// TODO use index-based ops for this
val theirs = otherSimpleArrayMap[key]
if (mine == null) {
if (theirs != null || !otherSimpleArrayMap.containsKey(key)) {
return false
}
} else if (mine != theirs) {
return false
}
}
return true
} else if (other is Map<*, *>) {
if (size() != other.size) {
return false
}
for (i in 0 until size) {
val key = keyAt(i)
val mine = valueAt(i)
val theirs = other[key]
if (mine == null) {
if (theirs != null || !other.containsKey(key)) {
return false
}
} else if (mine != theirs) {
return false
}
}
return true
}
} catch (ignored: NullPointerException) {
} catch (ignored: ClassCastException) {
}
return false
}
override fun hashCode(): Int {
val hashes = hashes
val array = array
var result = 0
var i = 0
var v = 1
val s = size
while (i < s) {
val value = array[v]
result += hashes[i] xor (value?.hashCode() ?: 0)
i++
v += 2
}
return result
}
/**
* Returns a string representation of the object.
*
* This implementation composes a string by iterating over its mappings. If
* this map contains itself as a key or a value, the string "(this Map)"
* will appear in its place.
*/
override fun toString(): String {
if (isEmpty()) {
return "{}"
}
return buildString(size * 28) {
append('{')
for (i in 0 until size) {
if (i > 0) {
append(", ")
}
val key = keyAt(i)
if (key !== this) {
append(key)
} else {
append("(this Map)")
}
append('=')
val value = valueAt(i)
if (value !== this) {
append(value)
} else {
append("(this Map)")
}
}
append('}')
}
}
}
| apache-2.0 | 5f06aa805c8355f1379825483c144eb2 | 32.595801 | 100 | 0.522422 | 4.660477 | false | false | false | false |
androidx/androidx | compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/BoundsAssertions.kt | 3 | 9983 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.test
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.layout.AlignmentLine
import androidx.compose.ui.semantics.SemanticsNode
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpRect
import androidx.compose.ui.unit.height
import androidx.compose.ui.unit.isUnspecified
import androidx.compose.ui.unit.toSize
import androidx.compose.ui.unit.width
import kotlin.math.abs
/**
* Asserts that the layout of this node has width equal to [expectedWidth].
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertWidthIsEqualTo(expectedWidth: Dp): SemanticsNodeInteraction {
return withUnclippedBoundsInRoot {
it.width.assertIsEqualTo(expectedWidth, "width")
}
}
/**
* Asserts that the layout of this node has height equal to [expectedHeight].
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertHeightIsEqualTo(expectedHeight: Dp): SemanticsNodeInteraction {
return withUnclippedBoundsInRoot {
it.height.assertIsEqualTo(expectedHeight, "height")
}
}
/**
* Asserts that the touch bounds of this node has width equal to [expectedWidth].
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertTouchWidthIsEqualTo(
expectedWidth: Dp
): SemanticsNodeInteraction {
return withTouchBoundsInRoot {
it.width.assertIsEqualTo(expectedWidth, "width")
}
}
/**
* Asserts that the touch bounds of this node has height equal to [expectedHeight].
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertTouchHeightIsEqualTo(
expectedHeight: Dp
): SemanticsNodeInteraction {
return withTouchBoundsInRoot {
it.height.assertIsEqualTo(expectedHeight, "height")
}
}
/**
* Asserts that the layout of this node has width that is greater than or equal to
* [expectedMinWidth].
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertWidthIsAtLeast(expectedMinWidth: Dp): SemanticsNodeInteraction {
return withUnclippedBoundsInRoot {
it.width.assertIsAtLeast(expectedMinWidth, "width")
}
}
/**
* Asserts that the layout of this node has height that is greater than or equal to
* [expectedMinHeight].
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertHeightIsAtLeast(
expectedMinHeight: Dp
): SemanticsNodeInteraction {
return withUnclippedBoundsInRoot {
it.height.assertIsAtLeast(expectedMinHeight, "height")
}
}
/**
* Asserts that the layout of this node has position in the root composable that is equal to the
* given position.
*
* @param expectedLeft The left (x) position to assert.
* @param expectedTop The top (y) position to assert.
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertPositionInRootIsEqualTo(
expectedLeft: Dp,
expectedTop: Dp
): SemanticsNodeInteraction {
return withUnclippedBoundsInRoot {
it.left.assertIsEqualTo(expectedLeft, "left")
it.top.assertIsEqualTo(expectedTop, "top")
}
}
/**
* Asserts that the layout of this node has the top position in the root composable that is equal to
* the given position.
*
* @param expectedTop The top (y) position to assert.
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertTopPositionInRootIsEqualTo(
expectedTop: Dp
): SemanticsNodeInteraction {
return withUnclippedBoundsInRoot {
it.top.assertIsEqualTo(expectedTop, "top")
}
}
/**
* Asserts that the layout of this node has the left position in the root composable that is
* equal to the given position.
*
* @param expectedLeft The left (x) position to assert.
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertLeftPositionInRootIsEqualTo(
expectedLeft: Dp
): SemanticsNodeInteraction {
return withUnclippedBoundsInRoot {
it.left.assertIsEqualTo(expectedLeft, "left")
}
}
/**
* Returns the bounds of the layout of this node. The bounds are relative to the root composable.
*/
fun SemanticsNodeInteraction.getUnclippedBoundsInRoot(): DpRect {
lateinit var bounds: DpRect
withUnclippedBoundsInRoot {
bounds = it
}
return bounds
}
/**
* Returns the bounds of the layout of this node as clipped to the root. The bounds are relative to
* the root composable.
*/
fun SemanticsNodeInteraction.getBoundsInRoot(): DpRect {
val node = fetchSemanticsNode("Failed to retrieve bounds of the node.")
return with(node.layoutInfo.density) {
node.boundsInRoot.let {
DpRect(it.left.toDp(), it.top.toDp(), it.right.toDp(), it.bottom.toDp())
}
}
}
/**
* Returns the position of an [alignment line][AlignmentLine], or [Dp.Unspecified] if the line is
* not provided.
*/
fun SemanticsNodeInteraction.getAlignmentLinePosition(alignmentLine: AlignmentLine): Dp {
return withDensity {
val pos = it.getAlignmentLinePosition(alignmentLine)
if (pos == AlignmentLine.Unspecified) {
Dp.Unspecified
} else {
pos.toDp()
}
}
}
private fun <R> SemanticsNodeInteraction.withDensity(
operation: Density.(SemanticsNode) -> R
): R {
val node = fetchSemanticsNode("Failed to retrieve density for the node.")
val density = node.layoutInfo.density
return operation.invoke(density, node)
}
private fun SemanticsNodeInteraction.withUnclippedBoundsInRoot(
assertion: (DpRect) -> Unit
): SemanticsNodeInteraction {
val node = fetchSemanticsNode("Failed to retrieve bounds of the node.")
val bounds = with(node.layoutInfo.density) {
node.unclippedBoundsInRoot.let {
DpRect(it.left.toDp(), it.top.toDp(), it.right.toDp(), it.bottom.toDp())
}
}
assertion.invoke(bounds)
return this
}
private fun SemanticsNodeInteraction.withTouchBoundsInRoot(
assertion: (DpRect) -> Unit
): SemanticsNodeInteraction {
val node = fetchSemanticsNode("Failed to retrieve bounds of the node.")
val bounds = with(node.layoutInfo.density) {
node.touchBoundsInRoot.let {
DpRect(it.left.toDp(), it.top.toDp(), it.right.toDp(), it.bottom.toDp())
}
}
assertion.invoke(bounds)
return this
}
private val SemanticsNode.unclippedBoundsInRoot: Rect
get() {
return if (layoutInfo.isPlaced) {
Rect(positionInRoot, size.toSize())
} else {
Dp.Unspecified.value.let { Rect(it, it, it, it) }
}
}
/**
* Returns if this value is equal to the [reference], within a given [tolerance]. If the
* reference value is [Float.NaN], [Float.POSITIVE_INFINITY] or [Float.NEGATIVE_INFINITY], this
* only returns true if this value is exactly the same (tolerance is disregarded).
*/
private fun Dp.isWithinTolerance(reference: Dp, tolerance: Dp): Boolean {
return when {
reference.isUnspecified -> this.isUnspecified
reference.value.isInfinite() -> this.value == reference.value
else -> abs(this.value - reference.value) <= tolerance.value
}
}
/**
* Asserts that this value is equal to the given [expected] value.
*
* Performs the comparison with the given [tolerance] or the default one if none is provided. It is
* recommended to use tolerance when comparing positions and size coming from the framework as there
* can be rounding operation performed by individual layouts so the values can be slightly off from
* the expected ones.
*
* @param expected The expected value to which this one should be equal to.
* @param subject Used in the error message to identify which item this assertion failed on.
* @param tolerance The tolerance within which the values should be treated as equal.
*
* @throws AssertionError if comparison fails.
*/
fun Dp.assertIsEqualTo(expected: Dp, subject: String, tolerance: Dp = Dp(.5f)) {
if (!isWithinTolerance(expected, tolerance)) {
// Comparison failed, report the error in DPs
throw AssertionError(
"Actual $subject is $this, expected $expected (tolerance: $tolerance)"
)
}
}
/**
* Asserts that this value is greater than or equal to the given [expected] value.
*
* Performs the comparison with the given [tolerance] or the default one if none is provided. It is
* recommended to use tolerance when comparing positions and size coming from the framework as there
* can be rounding operation performed by individual layouts so the values can be slightly off from
* the expected ones.
*
* @param expected The expected value to which this one should be greater than or equal to.
* @param subject Used in the error message to identify which item this assertion failed on.
* @param tolerance The tolerance within which the values should be treated as equal.
*
* @throws AssertionError if comparison fails.
*/
private fun Dp.assertIsAtLeast(expected: Dp, subject: String, tolerance: Dp = Dp(.5f)) {
if (!(isWithinTolerance(expected, tolerance) || (!isUnspecified && this > expected))) {
// Comparison failed, report the error in DPs
throw AssertionError(
"Actual $subject is $this, expected at least $expected (tolerance: $tolerance)"
)
}
}
| apache-2.0 | 5906f006a0db0d3bfc73e072312fd626 | 32.955782 | 100 | 0.721527 | 4.527438 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInspection/incorrectFormatting/IncorrectFormattingInspectionHelper.kt | 2 | 5971 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInspection.incorrectFormatting
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.lang.LangBundle
import com.intellij.openapi.editor.Document
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.Nls
import kotlin.math.abs
internal class IncorrectFormattingInspectionHelper(
private val formattingChanges: FormattingChanges,
val file: PsiFile,
val document: Document,
val manager: InspectionManager,
val isOnTheFly: Boolean) {
fun createAllReports(): Array<ProblemDescriptor>? {
val mismatches = formattingChanges.mismatches
if (mismatches.isEmpty()) return null
val result = arrayListOf<ProblemDescriptor>()
val (indentMismatches, inLineMismatches) = classifyMismatches(mismatches)
result += indentMismatchDescriptors(indentMismatches)
result += inLineMismatchDescriptors(inLineMismatches)
return result
.takeIf { it.isNotEmpty() }
?.toTypedArray()
}
fun createGlobalReport() =
manager.createProblemDescriptor(
file,
LangBundle.message("inspection.incorrect.formatting.global.problem.descriptor", file.name),
arrayOf(ReformatQuickFix, ShowDetailedReportIntention),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly,
false
)
private fun isIndentMismatch(mismatch: FormattingChanges.WhitespaceMismatch): Boolean =
mismatch.preFormatRange.startOffset.let {
it == 0 || document.text[it] == '\n'
}
// Distinguish between indent mismatches and others (aka in-line)
private fun classifyMismatches(mismatches: List<FormattingChanges.WhitespaceMismatch>)
: Pair<List<FormattingChanges.WhitespaceMismatch>, List<FormattingChanges.WhitespaceMismatch>> {
val indentMismatch = mismatches.groupBy { isIndentMismatch(it) }
return Pair(
indentMismatch[true] ?: emptyList(),
indentMismatch[false] ?: emptyList()
)
}
// Start line mismatches, "indents", grouped by consequent lines
private fun indentMismatchDescriptors(indentMismatches: List<FormattingChanges.WhitespaceMismatch>) =
sequence {
val currentBlock = arrayListOf<FormattingChanges.WhitespaceMismatch>()
indentMismatches.forEach { mismatch ->
currentBlock.lastOrNull()?.let { prev ->
if (!document.areRangesAdjacent(prev.preFormatRange, mismatch.preFormatRange)) {
yieldAll(createIndentProblemDescriptors(currentBlock))
currentBlock.clear()
}
}
currentBlock.add(mismatch)
}
yieldAll(createIndentProblemDescriptors(currentBlock))
}
private fun createReplacementString(mismatch: FormattingChanges.WhitespaceMismatch): String =
mismatch.postFormatRange.let {
formattingChanges.postFormatText.substring(it.startOffset, it.endOffset)
}
private fun TextRange.excludeLeadingLinefeed(): TextRange =
if (!isEmpty && document.text[startOffset] == '\n') TextRange(startOffset + 1, endOffset) else this
private fun createMessage(mismatch: FormattingChanges.WhitespaceMismatch) =
if (mismatch.preFormatRange.isEmpty) {
LangBundle.message("inspection.incorrect.formatting.wrong.whitespace.problem.descriptor.missing.whitespace")
}
else {
LangBundle.message("inspection.incorrect.formatting.wrong.whitespace.problem.descriptor.incorrect.whitespace")
}
private fun createIndentProblemDescriptors(mismatches: ArrayList<FormattingChanges.WhitespaceMismatch>) =
sequence {
val blockFix = ReplaceQuickFix(mismatches.map { document.createRangeMarker(it.preFormatRange) to createReplacementString(it) })
mismatches.forEach {
yield(
createProblemDescriptor(
it.preFormatRange.excludeLeadingLinefeed(),
createMessage(it),
blockFix, ReformatQuickFix, HideDetailedReportIntention
)
)
}
}
// In-line mismatches, grouped by line
private fun inLineMismatchDescriptors(inLineMismatches: List<FormattingChanges.WhitespaceMismatch>) =
sequence {
yieldAll(
inLineMismatches
.groupBy { document.getLineNumber(it.preFormatRange.startOffset) }
.flatMap { (_, mismatches) ->
val commonFix = ReplaceQuickFix(mismatches.map { document.createRangeMarker(it.preFormatRange) to createReplacementString(it) })
mismatches.map {
createProblemDescriptor(
it.preFormatRange,
createMessage(it),
commonFix, ReformatQuickFix, HideDetailedReportIntention
)
}
}
)
}
private fun createProblemDescriptor(range: TextRange, @Nls message: String, vararg fixes: LocalQuickFix): ProblemDescriptor {
val element = file.findElementAt(range.startOffset)
val targetElement = element ?: file
val targetRange = element
?.textRange
?.intersection(range)
?.shiftLeft(element.textRange.startOffset) // relative range
?: range // original range if no element
return manager.createProblemDescriptor(
targetElement,
targetRange,
message,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly,
*fixes
)
}
}
private fun Document.areRangesAdjacent(first: TextRange, second: TextRange): Boolean {
if (abs(getLineNumber(first.startOffset) - getLineNumber(second.endOffset - 1)) < 2) return true
if (abs(getLineNumber(second.startOffset) - getLineNumber(first.endOffset - 1)) < 2) return true
return false
} | apache-2.0 | cf800084cddac62280e885210a8f166d | 37.529032 | 140 | 0.712611 | 5.29344 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/customize/transferSettings/providers/vsmac/VSMacTransferSettingsProvider.kt | 2 | 2605 | package com.intellij.ide.customize.transferSettings.providers.vsmac
import com.intellij.icons.AllIcons
import com.intellij.ide.customize.transferSettings.models.IdeVersion
import com.intellij.ide.customize.transferSettings.providers.DefaultImportPerformer
import com.intellij.ide.customize.transferSettings.providers.TransferSettingsProvider
import com.intellij.ide.customize.transferSettings.providers.vsmac.VSMacSettingsProcessor.Companion.getGeneralSettingsFile
import com.intellij.ide.customize.transferSettings.providers.vsmac.VSMacSettingsProcessor.Companion.vsPreferences
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.util.SmartList
import com.jetbrains.rd.util.Date
import java.nio.file.Files
import java.nio.file.Paths
private val logger = logger<VSMacTransferSettingsProvider>()
class VSMacTransferSettingsProvider : TransferSettingsProvider {
override val name = "Visual Studio for Mac"
override fun isAvailable() = SystemInfoRt.isMac
override fun getIdeVersions(skipIds: List<String>) = when (val version = detectVSForMacVersion()) {
null -> SmartList()
else -> SmartList(getIdeVersion(version))
}
override fun getImportPerformer(ideVersion: IdeVersion) = DefaultImportPerformer()
private fun getIdeVersion(version: String) = IdeVersion(
name = "Visual Studio for Mac",
id = "VSMAC",
icon = AllIcons.Idea_logo_welcome,
lastUsed = getLastUsed(version),
settings = VSMacSettingsProcessor().getProcessedSettings(version),
provider = this
)
private fun detectVSForMacVersion(): String? {
val pathToDir = Paths.get(vsPreferences)
if (!Files.isDirectory(pathToDir)) {
return null
}
var max = 0L
var lastUsedVersion: String? = null
Files.list(pathToDir).use { files ->
for (path in files) {
if (!Files.isDirectory(path) && Files.isHidden(path)) continue
val maybeVersion = path.fileName.toString()
val recentlyUsedFile = getGeneralSettingsFile(maybeVersion)
if (recentlyUsedFile.exists()) {
val lastModificationTime = recentlyUsedFile.lastModified()
if (max < lastModificationTime) {
max = lastModificationTime
lastUsedVersion = maybeVersion
}
}
}
}
return lastUsedVersion
}
private fun getLastUsed(version: String): Date? {
val recentlyUsedFile = getGeneralSettingsFile(version)
return try {
Date(recentlyUsedFile.lastModified())
}
catch (t: Throwable) {
logger.warn(t)
null
}
}
}
| apache-2.0 | 5298228e0a28011aa1b06e0c63b9a6fa | 31.5625 | 122 | 0.737044 | 4.430272 | false | false | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHCloneDialogRepositoryListModel.kt | 5 | 4133 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.github.ui.cloneDialog
import org.jetbrains.plugins.github.api.data.GithubAuthenticatedUser
import org.jetbrains.plugins.github.api.data.GithubRepo
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import javax.swing.AbstractListModel
internal class GHCloneDialogRepositoryListModel : AbstractListModel<GHRepositoryListItem>() {
private val itemsByAccount = LinkedHashMap<GithubAccount, MutableList<GHRepositoryListItem>>()
private val repositoriesByAccount = hashMapOf<GithubAccount, MutableSet<GithubRepo>>()
override fun getSize(): Int = itemsByAccount.values.sumOf { it.size }
override fun getElementAt(index: Int): GHRepositoryListItem {
var offset = 0
for ((_, items) in itemsByAccount) {
if (index >= offset + items.size) {
offset += items.size
continue
}
return items[index - offset]
}
throw IndexOutOfBoundsException(index)
}
fun getItemAt(index: Int): Pair<GithubAccount, GHRepositoryListItem> {
var offset = 0
for ((account, items) in itemsByAccount) {
if (index >= offset + items.size) {
offset += items.size
continue
}
return account to items[index - offset]
}
throw IndexOutOfBoundsException(index)
}
fun indexOf(account: GithubAccount, item: GHRepositoryListItem): Int {
if (!itemsByAccount.containsKey(account)) return -1
var startOffset = 0
for ((_account, items) in itemsByAccount) {
if (_account == account) {
val idx = items.indexOf(item)
if (idx < 0) return -1
return startOffset + idx
}
else {
startOffset += items.size
}
}
return -1
}
fun clear(account: GithubAccount) {
repositoriesByAccount.remove(account)
val (startOffset, endOffset) = findAccountOffsets(account) ?: return
itemsByAccount.remove(account)
fireIntervalRemoved(this, startOffset, endOffset)
}
fun setError(account: GithubAccount, error: Throwable) {
val accountItems = itemsByAccount.getOrPut(account) { mutableListOf() }
val (startOffset, endOffset) = findAccountOffsets(account) ?: return
val errorItem = GHRepositoryListItem.Error(account, error)
accountItems.add(0, errorItem)
fireIntervalAdded(this, endOffset, endOffset + 1)
fireContentsChanged(this, startOffset, endOffset + 1)
}
/**
* Since each repository can be in several states at the same time (shared access for a collaborator and shared access for org member) and
* repositories for collaborators are loaded in separate request before repositories for org members, we need to update order of re-added
* repo in order to place it close to other organization repos
*/
fun addRepositories(account: GithubAccount, details: GithubAuthenticatedUser, repos: List<GithubRepo>) {
val repoSet = repositoriesByAccount.getOrPut(account) { mutableSetOf() }
val items = itemsByAccount.getOrPut(account) { mutableListOf() }
var (startOffset, endOffset) = findAccountOffsets(account) ?: return
val toAdd = mutableListOf<GHRepositoryListItem.Repo>()
for (repo in repos) {
val item = GHRepositoryListItem.Repo(account, details, repo)
val isNew = repoSet.add(repo)
if (isNew) {
toAdd.add(item)
}
else {
val idx = items.indexOf(item)
items.removeAt(idx)
fireIntervalRemoved(this, startOffset + idx, startOffset + idx)
endOffset--
}
}
items.addAll(toAdd)
fireIntervalAdded(this, endOffset, endOffset + toAdd.size)
}
private fun findAccountOffsets(account: GithubAccount): Pair<Int, Int>? {
if (!itemsByAccount.containsKey(account)) return null
var startOffset = 0
var endOffset = 0
for ((_account, items) in itemsByAccount) {
endOffset = startOffset + items.size
if (_account == account) {
break
}
else {
startOffset += items.size
}
}
return startOffset to endOffset
}
} | apache-2.0 | 126210d3e8dc2877d755a4a012783757 | 34.947826 | 140 | 0.695621 | 4.723429 | false | false | false | false |
stefanmedack/cccTV | app/src/main/java/de/stefanmedack/ccctv/persistence/C3TypeConverters.kt | 1 | 4780 | package de.stefanmedack.ccctv.persistence
import android.arch.persistence.room.TypeConverter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import de.stefanmedack.ccctv.model.ConferenceGroup
import de.stefanmedack.ccctv.persistence.entities.LanguageList
import de.stefanmedack.ccctv.util.EMPTY_STRING
import info.metadude.kotlin.library.c3media.models.AspectRatio
import info.metadude.kotlin.library.c3media.models.RelatedEvent
import org.threeten.bp.DateTimeException
import org.threeten.bp.LocalDate
import org.threeten.bp.OffsetDateTime
import org.threeten.bp.format.DateTimeFormatter
import org.threeten.bp.format.DateTimeParseException
class C3TypeConverters {
private val gson = Gson()
private val offsetDateTimeFormatter = DateTimeFormatter.ISO_DATE_TIME
private val localDateFormatter = DateTimeFormatter.ISO_DATE
// *********************************************************
// *** List<String> ****************************************
// *********************************************************
@TypeConverter
fun fromStringList(listString: String?): List<String> =
if (listString.isNullOrEmpty()) {
listOf()
} else {
gson.fromJson(listString, object : TypeToken<ArrayList<String>>() {}.type)
}
@TypeConverter
fun toStringList(list: List<String>?): String? = gson.toJson(list)
// *********************************************************
// *** List<Language> **************************************
// *********************************************************
@TypeConverter
fun fromLanguageList(listString: String?): LanguageList =
if (listString.isNullOrEmpty()) {
LanguageList()
} else {
gson.fromJson(listString, object : TypeToken<LanguageList>() {}.type)
}
@TypeConverter
fun toLanguageList(languageList: LanguageList): String? = gson.toJson(languageList)
// *********************************************************
// *** Metadata ********************************************
// *********************************************************
@TypeConverter
fun fromRelatedEventsString(metadataString: String?): List<RelatedEvent>? = gson
.fromJson(metadataString, object : TypeToken<List<RelatedEvent>>() {}.type)
@TypeConverter
fun toRelatedEventsString(metadata: List<RelatedEvent>?) = metadata?.let { gson.toJson(it) }
// *********************************************************
// *** AspectRatio *****************************************
// *********************************************************
@TypeConverter
fun fromAspectRatioString(aspectRatioString: String?) = AspectRatio.toAspectRatio(aspectRatioString)
@TypeConverter
fun toAspectRatioString(aspectRatio: AspectRatio) = AspectRatio.toText(aspectRatio) ?: EMPTY_STRING
// *********************************************************
// *** OffsetDateTime **************************************
// *********************************************************
@TypeConverter
fun fromOffsetDateTimeString(dateTimeString: String?): OffsetDateTime? = dateTimeString?.let {
try {
OffsetDateTime.parse(dateTimeString, offsetDateTimeFormatter)
} catch (e: DateTimeParseException) {
null
}
}
@TypeConverter
fun toOffsetDateTimeString(offsetDateTime: OffsetDateTime?) = offsetDateTime?.let {
try {
it.format(offsetDateTimeFormatter)
} catch (e: DateTimeException) {
null
}
}
// *********************************************************
// *** LocalDate *******************************************
// *********************************************************
@TypeConverter
fun fromLocalDateString(text: String?): LocalDate? = text?.let {
try {
LocalDate.parse(text, localDateFormatter)
} catch (e: DateTimeParseException) {
null
}
}
@TypeConverter
fun toLocalDateString(localDate: LocalDate?) = localDate?.let {
try {
it.format(localDateFormatter)
} catch (e: DateTimeException) {
null
}
}
// *********************************************************
// *** ConferenceGroup *******************************************
// *********************************************************
@TypeConverter
fun fromConferenceGroupString(text: String?): ConferenceGroup? = text?.let { ConferenceGroup.valueOf(it) }
@TypeConverter
fun toConferenceGroupString(conferenceGroup: ConferenceGroup?) = conferenceGroup?.name
} | apache-2.0 | 3f20d088cfa0d5a9f5e5d69f460b22f5 | 36.062016 | 110 | 0.508996 | 6.073698 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/CollapsibleRowImpl.kt | 1 | 3446 | // 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.ui.dsl.builder.impl
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.UiSwitcher
import com.intellij.openapi.ui.getUserData
import com.intellij.openapi.ui.putUserData
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.Expandable
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import org.jetbrains.annotations.ApiStatus
import java.awt.Component
import javax.swing.JComponent
import javax.swing.border.EmptyBorder
@ApiStatus.Internal
internal class CollapsibleRowImpl(dialogPanelConfig: DialogPanelConfig,
panelContext: PanelContext,
parent: PanelImpl,
@NlsContexts.BorderTitle title: String,
init: Panel.() -> Unit) :
RowImpl(dialogPanelConfig, panelContext, parent, RowLayout.INDEPENDENT), CollapsibleRow {
private val collapsibleTitledSeparator = CollapsibleTitledSeparator(title)
override var expanded by collapsibleTitledSeparator::expanded
override fun setText(@NlsContexts.Separator text: String) {
collapsibleTitledSeparator.text = text
}
override fun addExpandedListener(action: (Boolean) -> Unit) {
collapsibleTitledSeparator.expandedProperty.afterChange { action(it) }
}
init {
collapsibleTitledSeparator.setLabelFocusable(true)
(collapsibleTitledSeparator.label.border as? EmptyBorder)?.borderInsets?.let {
collapsibleTitledSeparator.putClientProperty(DslComponentProperty.VISUAL_PADDINGS,
Gaps(top = it.top, left = it.left, bottom = it.bottom))
}
val expandable = ExpandableImpl(collapsibleTitledSeparator)
collapsibleTitledSeparator.label.putClientProperty(Expandable::class.java, expandable)
val action = DumbAwareAction.create { expanded = !expanded }
action.registerCustomShortcutSet(ActionUtil.getShortcutSet("CollapsiblePanel-toggle"), collapsibleTitledSeparator.label)
val collapsibleTitledSeparator = this.collapsibleTitledSeparator
panel {
row {
cell(collapsibleTitledSeparator)
.horizontalAlign(HorizontalAlign.FILL)
}
val expandablePanel = panel(init)
collapsibleTitledSeparator.onAction(expandablePanel::visible)
collapsibleTitledSeparator.putUserData(UiSwitcher.UI_SWITCHER, UiSwitcherImpl(expandable, expandablePanel))
}
}
private class ExpandableImpl(private val separator: CollapsibleTitledSeparator) : Expandable {
override fun expand() {
separator.expanded = true
}
override fun collapse() {
separator.expanded = false
}
override fun isExpanded(): Boolean {
return separator.expanded
}
}
private class UiSwitcherImpl(
private val expandable: Expandable,
private val panel: Panel
) : UiSwitcher {
override fun show(component: Component) {
if (component is JComponent) {
val hierarchy = component.getUserData(DSL_PANEL_HIERARCHY)
if (hierarchy != null && panel in hierarchy) {
expandable.expand()
}
}
}
}
}
| apache-2.0 | 27949f7b35dafc815e4fbe23c0ba7f69 | 36.868132 | 158 | 0.721706 | 5.127976 | false | false | false | false |
jwren/intellij-community | platform/lang-api/src/com/intellij/codeInsight/hints/InlayHintsProvider.kt | 1 | 8859 | // 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.codeInsight.hints
import com.intellij.lang.Language
import com.intellij.lang.LanguageExtension
import com.intellij.lang.LanguageExtensionPoint
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileFactory
import com.intellij.util.xmlb.annotations.Property
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import javax.swing.JComponent
import kotlin.reflect.KMutableProperty0
private const val EXTENSION_POINT_NAME = "com.intellij.codeInsight.inlayProvider"
enum class InlayGroup(val key: String, @Nls val description: String? = null) {
CODE_VISION_GROUP_NEW("settings.hints.new.group.code.vision", ApplicationBundle.message("settings.hints.new.group.code.vision.description")),
CODE_VISION_GROUP("settings.hints.group.code.vision", ApplicationBundle.message("settings.hints.new.group.code.vision.description")),
PARAMETERS_GROUP("settings.hints.group.parameters", ApplicationBundle.message("settings.hints.group.parameters.description")),
TYPES_GROUP("settings.hints.group.types", ApplicationBundle.message("settings.hints.group.types.description")),
VALUES_GROUP("settings.hints.group.values", ApplicationBundle.message("settings.hints.group.values.description")),
ANNOTATIONS_GROUP("settings.hints.group.annotations", ApplicationBundle.message("settings.hints.group.annotations.description")),
METHOD_CHAINS_GROUP("settings.hints.group.method.chains"),
LAMBDAS_GROUP("settings.hints.group.lambdas", ApplicationBundle.message("settings.hints.group.lambdas.description")),
CODE_AUTHOR_GROUP("settings.hints.group.code.author", ApplicationBundle.message("settings.hints.group.code.author.description")),
URL_PATH_GROUP("settings.hints.group.url.path", ApplicationBundle.message("settings.hints.group.url.path.description")),
OTHER_GROUP("settings.hints.group.other");
override fun toString(): @Nls String {
return ApplicationBundle.message(key)
}}
object InlayHintsProviderExtension : LanguageExtension<InlayHintsProvider<*>>(EXTENSION_POINT_NAME) {
private fun findLanguagesWithHintsSupport(): List<Language> {
val extensionPointName = inlayProviderName
return extensionPointName.extensionList.map { it.language }
.toSet()
.mapNotNull { Language.findLanguageByID(it) }
}
fun findProviders() : List<ProviderInfo<*>> {
return findLanguagesWithHintsSupport().flatMap { language ->
InlayHintsProviderExtension.allForLanguage(language).map { ProviderInfo(language, it) }
}
}
val inlayProviderName = ExtensionPointName<LanguageExtensionPoint<InlayHintsProvider<*>>>(EXTENSION_POINT_NAME)
}
/**
* Provider of inlay hints for single language. If you need to create hints for multiple languages, please use [InlayHintsProviderFactory].
* Both block and inline hints collection are supported.
* Block hints draws between lines of code text. Inline ones are placed on the code text line (like parameter hints)
* @param T settings type of this provider, if no settings required, please, use [NoSettings]
* @see com.intellij.openapi.editor.InlayModel.addInlineElement
* @see com.intellij.openapi.editor.InlayModel.addBlockElement
*
* To test it you may use InlayHintsProviderTestCase.
* Mark as [com.intellij.openapi.project.DumbAware] to enable it in dumb mode.
*/
interface InlayHintsProvider<T : Any> {
/**
* If this method is called, provider is enabled for this file
* Warning! Your collector should not use any settings besides [settings]
*/
fun getCollectorFor(file: PsiFile, editor: Editor, settings: T, sink: InlayHintsSink): InlayHintsCollector?
/**
* Returns quick collector of placeholders.
* Placeholders are shown on editor opening and stay until [getCollectorFor] collector hints are calculated.
*/
@ApiStatus.Experimental
@JvmDefault
fun getPlaceholdersCollectorFor(file: PsiFile, editor: Editor, settings: T, sink: InlayHintsSink): InlayHintsCollector? = null
/**
* Settings must be plain java object, fields of these settings will be copied via serialization.
* Must implement `equals` method, otherwise settings won't be able to track modification.
* Returned object will be used to create configurable and collector.
* It persists automatically.
*/
fun createSettings(): T
@get:Nls(capitalization = Nls.Capitalization.Sentence)
/**
* Name of this kind of hints. It will be used in settings and in context menu.
* Please, do not use word "hints" to avoid duplication
*/
val name: String
@JvmDefault
val group: InlayGroup get() = InlayGroup.OTHER_GROUP
/**
* Used for persisting settings.
*/
val key: SettingsKey<T>
@JvmDefault
val description: String?
@Nls
get() {
return getProperty("inlay." + key.id + ".description")
}
/**
* Text, that will be used in the settings as a preview.
*/
val previewText: String?
/**
* Creates configurable, that immediately applies changes from UI to [settings].
*/
fun createConfigurable(settings: T): ImmediateConfigurable
/**
* Checks whether the language is accepted by the provider.
*/
fun isLanguageSupported(language: Language): Boolean = true
@JvmDefault
fun createFile(project: Project, fileType: FileType, document: Document): PsiFile {
val factory = PsiFileFactory.getInstance(project)
return factory.createFileFromText("dummy", fileType, document.text)
}
@Nls
@JvmDefault
fun getProperty(key: String): String? = null
@JvmDefault
fun preparePreview(editor: Editor, file: PsiFile, settings: T) {
}
@Nls
@JvmDefault
fun getCaseDescription(case: ImmediateConfigurable.Case): String? {
return getProperty("inlay." + this.key.id + "." + case.id)
}
val isVisibleInSettings: Boolean
get() = true
}
/**
* The same as [UnnamedConfigurable], but not waiting for apply() to save settings.
*/
interface ImmediateConfigurable {
/**
* Creates component, which listen to its components and immediately updates state of settings object
* This is required to make preview in settings works instantly
* Note, that if you need to express only cases of this provider, you should use [cases] instead
*/
fun createComponent(listener: ChangeListener): JComponent
/**
* Loads state from its configurable.
*/
@JvmDefault
fun reset() {}
/**
* Text, that will be used in settings for checkbox to enable/disable hints.
*/
@JvmDefault
val mainCheckboxText: String
get() = "Show hints"
@JvmDefault
val cases : List<Case>
get() = emptyList()
class Case(
@Nls val name: String,
val id: String,
private val loadFromSettings: () -> Boolean,
private val onUserChanged: (Boolean) -> Unit,
@NlsContexts.DetailedDescription
val extendedDescription: String? = null
) {
var value: Boolean
get() = loadFromSettings()
set(value) = onUserChanged(value)
constructor(@Nls name: String, id: String, property: KMutableProperty0<Boolean>, @NlsContexts.DetailedDescription extendedDescription: String? = null) : this(
name,
id,
{ property.get() },
{property.set(it)},
extendedDescription
)
}
}
interface ChangeListener {
/**
* This method should be called on any change of corresponding settings.
*/
fun settingsChanged()
}
/**
* This class should be used if provider should not have settings. If you use e.g. [Unit] you will have annoying warning in logs.
*/
@Property(assertIfNoBindings = false)
class NoSettings {
override fun equals(other: Any?): Boolean = other is NoSettings
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
/**
* Similar to [com.intellij.openapi.util.Key], but it also requires language to be unique.
* Allows type-safe access to settings of provider.
*/
@Suppress("unused")
data class SettingsKey<T>(val id: String) {
fun getFullId(language: Language): String = language.id + "." + id
}
interface AbstractSettingsKey<T: Any> {
fun getFullId(language: Language): String
}
data class InlayKey<T: Any, C: Any>(val id: String) : AbstractSettingsKey<T>, ContentKey<C> {
override fun getFullId(language: Language): String = language.id + "." + id
}
/**
* Allows type-safe access to content of the root presentation.
*/
interface ContentKey<C: Any> | apache-2.0 | b81d18a0fb286d3083025b7a56bcfd24 | 35.01626 | 162 | 0.742183 | 4.351179 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/configuration/listener/ScriptChangesNotifier.kt | 4 | 4697 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core.script.configuration.listener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.FileEditorManagerEvent
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Alarm
import com.intellij.util.concurrency.AppExecutorUtil
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.configuration.listener.ScriptChangeListener.Companion.LISTENER
import org.jetbrains.kotlin.idea.core.script.isScriptChangesNotifierDisabled
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
internal class ScriptChangesNotifier(private val project: Project) {
private val scriptsQueue: Alarm
private val scriptChangesListenerDelayMillis = 1400
init {
val parentDisposable = KotlinPluginDisposable.getInstance(project)
scriptsQueue = Alarm(Alarm.ThreadToUse.POOLED_THREAD, parentDisposable)
project.messageBus.connect(parentDisposable).subscribe(
FileEditorManagerListener.FILE_EDITOR_MANAGER,
object : FileEditorManagerListener {
override fun fileOpened(source: FileEditorManager, file: VirtualFile) {
runScriptDependenciesUpdateIfNeeded(file)
}
override fun selectionChanged(event: FileEditorManagerEvent) {
event.newFile?.let { runScriptDependenciesUpdateIfNeeded(it) }
}
private fun runScriptDependenciesUpdateIfNeeded(file: VirtualFile) {
if (isUnitTestMode()) {
updateScriptDependenciesIfNeeded(file)
} else {
AppExecutorUtil.getAppExecutorService().submit {
updateScriptDependenciesIfNeeded(file)
}
}
}
},
)
EditorFactory.getInstance().eventMulticaster.addDocumentListener(
object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
val document = event.document
val file = FileDocumentManager.getInstance().getFile(document)?.takeIf { it.isInLocalFileSystem } ?: return
// Do not listen for changes in files that are not open
val editorManager = FileEditorManager.getInstance(project) ?: return
if (file !in editorManager.openFiles) {
return
}
if (isUnitTestMode()) {
getListener(project, file)?.documentChanged(file)
} else {
scriptsQueue.cancelAllRequests()
if (!project.isDisposed) {
scriptsQueue.addRequest(
{ getListener(project, file)?.documentChanged(file) },
scriptChangesListenerDelayMillis,
true,
)
}
}
}
},
parentDisposable
)
// Init project scripting idea EP listeners
LISTENER.getExtensions(project)
}
private val defaultListener = DefaultScriptChangeListener(project)
private val listeners: Collection<ScriptChangeListener>
get() = mutableListOf<ScriptChangeListener>().apply {
addAll(LISTENER.getExtensions(project))
add(defaultListener)
}
internal fun updateScriptDependenciesIfNeeded(file: VirtualFile) {
getListener(project, file)?.editorActivated(file)
}
private fun getListener(project: Project, file: VirtualFile): ScriptChangeListener? {
if (project.isDisposed || areListenersDisabled()) return null
return listeners.firstOrNull { it.isApplicable(file) }
}
private fun areListenersDisabled(): Boolean {
return isUnitTestMode() && ApplicationManager.getApplication().isScriptChangesNotifierDisabled == true
}
}
| apache-2.0 | 8e3d42c3c48457ff4a5fbc8b61ab64ea | 43.311321 | 158 | 0.647222 | 6.068475 | false | false | false | false |
kpi-ua/ecampus-client-android | app/src/main/java/com/goldenpiedevs/schedule/app/ui/widget/WidgetDataProvider.kt | 1 | 2954 | package com.goldenpiedevs.schedule.app.ui.widget
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import androidx.core.content.ContextCompat
import com.goldenpiedevs.schedule.app.R
import com.goldenpiedevs.schedule.app.core.dao.timetable.*
import com.goldenpiedevs.schedule.app.core.ext.currentWeek
import com.goldenpiedevs.schedule.app.core.ext.todayNumberInWeek
import com.goldenpiedevs.schedule.app.core.utils.preference.AppPreference
import java.util.*
/**
* WidgetDataProvider acts as the adapter for the collection view widget,
* providing RemoteViews to the widget in the getViewAt method.
*/
class WidgetDataProvider(val context: Context) : RemoteViewsService.RemoteViewsFactory {
private var mCollection: MutableList<DaoLessonModel> = ArrayList()
override fun onCreate() {
initData()
}
override fun onDataSetChanged() {
initData()
}
override fun onDestroy() {
mCollection.clear()
}
override fun getCount(): Int {
return mCollection.size
}
override fun getViewAt(position: Int): RemoteViews {
val model = mCollection[position]
val view = RemoteViews(context.packageName,
R.layout.widget_item_view)
view.setViewVisibility(R.id.widget_lesson_has_note, if (model.haveNote) View.VISIBLE else View.INVISIBLE)
view.setTextViewText(R.id.widget_lesson_title, model.lessonName)
view.setTextColor(R.id.widget_lesson_number,
if (model.haveNote) Color.WHITE else ContextCompat.getColor(context, R.color.secondary_text))
view.setTextViewText(R.id.widget_lesson_number, model.lessonNumber.toString())
view.setTextViewText(R.id.widget_lesson_time, model.getTime())
view.setTextViewText(R.id.widget_lesson_location, "${model.lessonRoom} ${model.lessonType}")
val extras = Bundle()
extras.putString(ScheduleWidgetProvider.LESSON_ID, model.id)
val fillInIntent = Intent()
fillInIntent.putExtras(extras)
view.setOnClickFillInIntent(R.id.widget_item_row_view, fillInIntent)
return view
}
override fun getLoadingView(): RemoteViews? {
return null
}
override fun getViewTypeCount(): Int {
return 1
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun hasStableIds(): Boolean {
return true
}
private fun initData() {
mCollection.clear()
val data = DaoDayModel.getLessons()
.forGroupWithName(AppPreference.groupName)
.forWeek(currentWeek + 1)
.firstOrNull { it.dayNumber == todayNumberInWeek }
?.lessons
data?.let {
mCollection.addAll(it)
}
}
}
| apache-2.0 | 8ebd03d920e2d78101b5b460963169b8 | 30.094737 | 113 | 0.690251 | 4.509924 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/test-framework/test/org/jetbrains/kotlin/idea/test/DirectiveBasedActionUtils.kt | 1 | 7130 | // 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.test
import com.intellij.codeInsight.daemon.impl.DaemonProgressIndicator
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiFile
import com.intellij.testFramework.UsefulTestCase
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.test.InTextDirectivesUtils
object DirectiveBasedActionUtils {
const val DISABLE_ERRORS_DIRECTIVE = "// DISABLE-ERRORS"
const val DISABLE_WARNINGS_DIRECTIVE = "// DISABLE-WARNINGS"
const val ENABLE_WARNINGS_DIRECTIVE = "// ENABLE-WARNINGS"
const val ACTION_DIRECTIVE = "// ACTION:"
fun checkForUnexpectedErrors(file: KtFile, diagnosticsProvider: (KtFile) -> Diagnostics = { it.analyzeWithContent().diagnostics }) {
if (InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, DISABLE_ERRORS_DIRECTIVE).isNotEmpty()) {
return
}
checkForUnexpected(file, diagnosticsProvider, "// ERROR:", "errors", Severity.ERROR)
}
fun checkForUnexpectedWarnings(
file: KtFile,
disabledByDefault: Boolean = true,
directiveName: String = Severity.WARNING.name,
diagnosticsProvider: (KtFile) -> Diagnostics = { it.analyzeWithContent().diagnostics }
) {
if (disabledByDefault && InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, ENABLE_WARNINGS_DIRECTIVE).isEmpty() ||
!disabledByDefault && InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, DISABLE_WARNINGS_DIRECTIVE).isNotEmpty()) {
return
}
checkForUnexpected(file, diagnosticsProvider, "// $directiveName:", "warnings", Severity.WARNING)
}
private fun checkForUnexpected(
file: KtFile,
diagnosticsProvider: (KtFile) -> Diagnostics,
directive: String,
name: String,
severity: Severity
) {
val expected = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, directive)
.sorted()
.map { "$directive $it" }
val diagnostics = diagnosticsProvider(file)
val actual = diagnostics
.filter { it.severity == severity }
.map { "$directive ${DefaultErrorMessages.render(it).replace("\n", "<br>")}" }
.sorted()
if (actual.isEmpty() && expected.isEmpty()) return
UsefulTestCase.assertOrderedEquals(
"All actual $name should be mentioned in test data with '$directive' directive. " +
"But no unnecessary $name should be me mentioned, file:\n${file.text}",
actual,
expected
)
}
fun inspectionChecks(name: String, file: PsiFile) {
InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, "// INSPECTION-CLASS:").takeIf { it.isNotEmpty() }?.let { inspectionNames ->
val inspectionManager = InspectionManager.getInstance(file.project)
val inspections = inspectionNames.map { Class.forName(it).getDeclaredConstructor().newInstance() as AbstractKotlinInspection }
val problems = mutableListOf<ProblemDescriptor>()
ProgressManager.getInstance().executeProcessUnderProgress(
{
for (inspection in inspections) {
problems += inspection.processFile(
file,
inspectionManager
)
}
}, DaemonProgressIndicator()
)
val directive = "// INSPECTION:"
val expected = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, directive)
.sorted()
.map { "$directive $it" }
val actual = problems
// lineNumber is 0-based
.map { "$directive [${it.highlightType.name}:${it.lineNumber + 1}] $it" }
.sorted()
if (actual.isEmpty() && expected.isEmpty()) return
KotlinLightCodeInsightFixtureTestCaseBase.assertOrderedEquals(
"All actual $name should be mentioned in test data with '$directive' directive. " +
"But no unnecessary $name should be me mentioned, file:\n${file.text}",
actual,
expected
)
}
}
fun checkAvailableActionsAreExpected(file: PsiFile, availableActions: Collection<IntentionAction>) {
val expectedActions = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, ACTION_DIRECTIVE).sorted()
UsefulTestCase.assertEmpty("Irrelevant actions should not be specified in $ACTION_DIRECTIVE directive for they are not checked anyway",
expectedActions.filter { isIrrelevantAction(it) })
if (InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, "// IGNORE_IRRELEVANT_ACTIONS").isNotEmpty()) {
return
}
val actualActions = availableActions.map { it.text }.sorted()
UsefulTestCase.assertOrderedEquals(
"Some unexpected actions available at current position. Use '$ACTION_DIRECTIVE' directive",
filterOutIrrelevantActions(actualActions).map { "$ACTION_DIRECTIVE $it" },
expectedActions.map { "$ACTION_DIRECTIVE $it" }
)
}
//TODO: hack, implemented because irrelevant actions behave in different ways on build server and locally
// this behaviour should be investigated and hack can be removed
private fun filterOutIrrelevantActions(actions: Collection<String>): Collection<String> {
return actions.filter { !isIrrelevantAction(it) }
}
private fun isIrrelevantAction(action: String) = action.isEmpty() || IRRELEVANT_ACTION_PREFIXES.any { action.startsWith(it) }
private val IRRELEVANT_ACTION_PREFIXES = listOf(
"Disable ",
"Edit intention settings",
"Edit inspection profile setting",
"Inject language or reference",
"Suppress '",
"Run inspection on",
"Inspection '",
"Suppress for ",
"Suppress all ",
"Edit cleanup profile settings",
"Fix all '",
"Cleanup code",
"Go to ",
"Show local variable type hints",
"Show function return type hints",
"Show property type hints",
"Show parameter type hints",
"Show argument name hints",
"Show hints for suspending calls",
"Add 'JUnit",
"Add 'testng"
)
}
| apache-2.0 | 8f4ff67669672ff057cdb3517d5b4557 | 42.47561 | 158 | 0.655961 | 5.368976 | false | true | false | false |
kmikusek/light-sensor | app/src/main/java/pl/pw/mgr/lightsensor/calibrations/CalibrationsActivity.kt | 1 | 4784 | package pl.pw.mgr.lightsensor.calibrations
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import kotlinx.android.synthetic.main.activity_calibration.*
import pl.pw.mgr.lightsensor.App
import pl.pw.mgr.lightsensor.R
import pl.pw.mgr.lightsensor.common.C
import pl.pw.mgr.lightsensor.common.C.Companion.NO_RES_ID
import pl.pw.mgr.lightsensor.common.ConfirmationListener
import pl.pw.mgr.lightsensor.data.model.Calibration
import pl.pw.mgr.lightsensor.points.PointsActivity
import javax.inject.Inject
class CalibrationsActivity : AppCompatActivity(), CalibrationsContract.View {
@Inject internal lateinit var presenter: CalibrationsPresenter
private lateinit var adapter: CalibrationsAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_calibration)
DaggerCalibrationsComponent.builder()
.repositoryComponent((application as App).repositoryComponent)
.calibrationsPresenterModule(CalibrationsPresenterModule(this))
.build()
.inject(this)
adapter = CalibrationsAdapter(this)
recycler_view.setHasFixedSize(true)
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.adapter = adapter
recycler_view.addItemDecoration(
DividerItemDecoration(applicationContext, DividerItemDecoration.VERTICAL).also {
it.setDrawable(ContextCompat.getDrawable(this, R.drawable.divider))
}
)
add_btn.setOnClickListener { presenter.onAddCalibrationClicked() }
edit_btn.setOnClickListener { presenter.onEditCalibrationClicked(adapter.getSelectedCalibration()) }
delete_btn.setOnClickListener { presenter.onDeleteCalibrationClicked(adapter.getSelectedCalibration()) }
}
override fun onStart() {
super.onStart()
presenter.start()
}
override fun showCalibrations(items: List<Calibration>) = adapter.setItems(items)
override fun showAdditionalCalibration(calibration: Calibration) = adapter.addItem(calibration)
override fun removeFromUI(calibration: Calibration) = adapter.removeItem(calibration)
override fun showEmptyCalibrationsInfo() {
TODO("Not implemented yet")
}
override fun showAddConfirmationDialog() {
MaterialDialog.Builder(this)
.title(R.string.activity_calibration_dialog_add_title)
.positiveText(R.string.activity_calibration_dialog_positive_btn)
.negativeText(R.string.activity_calibration_dialog_negative_btn)
.alwaysCallInputCallback()
.input(R.string.activity_calibration_dialog_add_input_hint,
NO_RES_ID,
false,
{ dialog, input -> dialog.getActionButton(DialogAction.POSITIVE).isEnabled = !input.isBlank() })
.onPositive { dialog, _ -> presenter.addCalibration(dialog.inputEditText?.text.toString()) }
.show()
}
override fun showDeleteConfirmationDialog(listener: ConfirmationListener) {
MaterialDialog.Builder(this)
.title(R.string.activity_calibration_dialog_delete_title)
.positiveText(R.string.activity_calibration_dialog_positive_btn)
.negativeText(R.string.activity_calibration_dialog_negative_btn)
.onPositive { _, _ -> listener.onConfirm() }
.onNegative { _, _ -> listener.onDecline() }
.show()
}
override fun showChoseCalibrationInfo() = Snackbar.make(activity_calibration_root, R.string.activity_calibration_chose_calibration_err, Snackbar.LENGTH_SHORT).show()
override fun showEditCalibrationUI(calibration: Calibration) = startActivity(Intent(this, PointsActivity::class.java).apply {
putExtra(C.Calibrations.ID, calibration.id)
})
override fun isActive() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
!isDestroyed
} else {
!isFinishing
}
override fun onBackPressed() {
adapter.getSelectedCalibration()?.let {
setResult(Activity.RESULT_OK, Intent().putExtra(C.Calibrations.ID, it.id))
} ?: setResult(Activity.RESULT_CANCELED)
super.onBackPressed()
}
}
| mit | 4205ec9ea16c63812fa16610dccc9fa1 | 41.714286 | 169 | 0.703804 | 4.793587 | false | false | false | false |
paul58914080/ff4j-spring-boot-starter-parent | ff4j-spring-boot-web-api/src/main/kotlin/org/ff4j/spring/boot/web/api/resources/MonitoringResource.kt | 1 | 2615 | /*-
* #%L
* ff4j-spring-boot-web-api
* %%
* Copyright (C) 2013 - 2019 FF4J
* %%
* 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.
* #L%
*/
package org.ff4j.spring.boot.web.api.resources
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiResponse
import io.swagger.annotations.ApiResponses
import org.ff4j.services.MonitoringServices
import org.ff4j.services.constants.FeatureConstants.RESOURCE_FF4J_MONITORING
import org.ff4j.services.domain.EventRepositoryApiBean
import org.ff4j.web.FF4jWebConstants.PARAM_END
import org.ff4j.web.FF4jWebConstants.PARAM_START
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType.APPLICATION_JSON_VALUE
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
/**
* Created by Paul
*
* @author [Paul Williams](mailto:[email protected])
*/
@Api(tags = ["Monitoring"], description = "The API for monitoring related operations")
@RestController
@RequestMapping(value = [RESOURCE_FF4J_MONITORING])
class MonitoringResource(@Autowired val monitoringServices: MonitoringServices) {
@ApiOperation(value = "Display Monitoring information for all features", notes = "The EventRepository handle to store audit events is not required", response = EventRepositoryApiBean::class)
@ApiResponses(
ApiResponse(code = 200, message = "Status of event repository bean", response = EventRepositoryApiBean::class),
ApiResponse(code = 404, message = "No event repository defined", response = String::class))
@GetMapping(produces = [APPLICATION_JSON_VALUE])
fun getMonitoringStatus(@RequestParam(value = PARAM_START, required = false, defaultValue = "0") start: Long, @RequestParam(value = PARAM_END, required = false, defaultValue = "0") end: Long): EventRepositoryApiBean =
monitoringServices.getMonitoringStatus(start, end)
}
| apache-2.0 | 450a98c571e2b9cfc9e9f91798662583 | 45.696429 | 221 | 0.772467 | 4.079563 | false | false | false | false |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/petal/Module/Follow/PetalFollowBoardFragment.kt | 1 | 4275 | package stan.androiddemo.project.petal.Module.Follow
import android.content.Context
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.widget.TextView
import com.chad.library.adapter.base.BaseViewHolder
import com.facebook.drawee.view.SimpleDraweeView
import rx.Subscriber
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import stan.androiddemo.R
import stan.androiddemo.UI.BasePetalRecyclerFragment
import stan.androiddemo.project.petal.API.FollowAPI
import stan.androiddemo.project.petal.Config.Config
import stan.androiddemo.project.petal.Event.OnBoardFragmentInteractionListener
import stan.androiddemo.project.petal.HttpUtiles.RetrofitClient
import stan.androiddemo.project.petal.Model.BoardPinsInfo
import stan.androiddemo.tool.ImageLoad.ImageLoadBuilder
class PetalFollowBoardFragment : BasePetalRecyclerFragment<BoardPinsInfo>() {
var mLimit = Config.LIMIT
lateinit var mAttentionFormat: String
lateinit var mGatherFormat: String
lateinit var mUsernameFormat: String
private var mListener: OnBoardFragmentInteractionListener<BoardPinsInfo>? = null
companion object {
fun newInstance():PetalFollowBoardFragment{
return PetalFollowBoardFragment()
}
}
override fun getTheTAG(): String {
return this.toString()
}
override fun initView() {
super.initView()
mAttentionFormat = resources.getString(R.string.text_gather_number)
mGatherFormat = resources.getString(R.string.text_attention_number)
mUsernameFormat = resources.getString(R.string.text_by_username)
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is OnBoardFragmentInteractionListener<*>){
mListener = context as OnBoardFragmentInteractionListener<BoardPinsInfo>
}
}
override fun getLayoutManager(): RecyclerView.LayoutManager {
return GridLayoutManager(context,2)
}
override fun getItemLayoutId(): Int {
return R.layout.petal_cardview_board_item
}
override fun itemLayoutConvert(helper: BaseViewHolder, t: BoardPinsInfo) {
val img = helper.getView<SimpleDraweeView>(R.id.img_card_board)
helper.getView<TextView>(R.id.txt_board_title).text = t.title
helper.getView<TextView>(R.id.txt_board_gather).text = String.format(mGatherFormat,t.pin_count)
helper.getView<TextView>(R.id.txt_board_attention).text = String.format(mAttentionFormat,t.follow_count)
helper.getView<TextView>(R.id.txt_board_username).text = String.format(mUsernameFormat,t.user?.username)
img.setOnClickListener {
mListener?.onClickBoardItemImage(t,it)
}
helper.getView<TextView>(R.id.txt_board_username).setOnClickListener {
mListener?.onClickBoardItemImage(t,it)
}
var url = ""
if (t.pins!= null && t.pins!!.size > 0){
if (t.pins!!.first().file?.key != null){
url = t.pins!!.first().file!!.key!!
}
}
url = String.format(mUrlGeneralFormat,url)
img.aspectRatio = 1F
ImageLoadBuilder.Start(context,img,url).setProgressBarImage(progressLoading).build()
}
override fun requestListData(page: Int): Subscription {
return RetrofitClient.createService(FollowAPI::class.java).httpsMyFollowingBoardRx(mAuthorization!!,page,mLimit)
.map { it.boards }.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object: Subscriber<List<BoardPinsInfo>>(){
override fun onCompleted() {
}
override fun onError(e: Throwable?) {
e?.printStackTrace()
loadError()
checkException(e)
}
override fun onNext(t: List<BoardPinsInfo>?) {
if (t == null){
loadError()
return
}
loadSuccess(t!!)
}
})
}
}
| mit | 9fc28de5dc6eaa6e25235858f70d0f17 | 35.228814 | 122 | 0.658947 | 4.713341 | false | false | false | false |
sksamuel/ktest | kotest-assertions/kotest-assertions-json/src/commonMain/kotlin/io/kotest/assertions/json/wrappers.kt | 1 | 1276 | package io.kotest.assertions.json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.floatOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.longOrNull
fun JsonElement.toJsonNode(): JsonNode = when (this) {
JsonNull -> JsonNode.NullNode
is JsonObject -> JsonNode.ObjectNode(entries.map { it.key to it.value.toJsonNode() }.toMap())
is JsonArray -> JsonNode.ArrayNode(map { it.toJsonNode() })
is JsonPrimitive -> when {
intOrNull != null -> JsonNode.IntNode(intOrNull!!)
longOrNull != null -> JsonNode.LongNode(longOrNull!!)
doubleOrNull != null -> JsonNode.DoubleNode(doubleOrNull!!)
floatOrNull != null -> JsonNode.FloatNode(floatOrNull!!)
booleanOrNull != null -> JsonNode.BooleanNode(booleanOrNull!!)
contentOrNull != null -> JsonNode.StringNode(contentOrNull!!)
else -> error("Unsupported kotlinx-serialization type $this")
}
}
| mit | 25d96671ecce1990d0a44e3e32fdbe3a | 44.571429 | 96 | 0.77116 | 4.725926 | false | false | false | false |
byoutline/SecretSauce | SecretSauce/src/main/java/com/byoutline/secretsauce/lifecycle/SingleActivityLifecycleCallbacks.kt | 1 | 4709 | package com.byoutline.secretsauce.lifecycle
import android.app.Activity
import android.app.Application
import android.os.Bundle
/**
* Wraps given [Application.ActivityLifecycleCallbacks], so only lifecycle of [this] [Activity]
* are forwarded. Calling this method will immediately register wrapped callback and it will be
* automatically unregistered when activity is destroyed.
*
* This is supposed to help avoid boilerplate in [Application.ActivityLifecycleCallbacks].
* For example instead of:
* ```kotlin
* class ExampleActivity: AppCompatActivity {
* override fun onCreate(savedInstanceState: Bundle?) {
* super.onCreate(savedInstanceState)
* application.registerActivityLifecycleCallbacks(LifecycleListener(this))
* }
* }
*
* class LifecycleListener(val view: Activity): ActivityLifecycleCallbacksAdapter() {
* override fun onActivityResumed(a: Activity?) {
* if(view === a) doSomething()
* }
* override fun onActivityDestroyed(a: Activity?) {
* if (a === view) view.application.unregisterActivityLifecycleCallbacks(this)
* }
* }
* ```
* you can write:
* ```kotlin
* class ExampleActivity: AppCompatActivity {
* override fun onCreate(savedInstanceState: Bundle?) {
* super.onCreate(savedInstanceState)
* registerLifecycleCallbacksForThisActivityOnly(LifecycleListener())
* }
* }
*
* class LifecycleListener(): ActivityLifecycleCallbacksAdapter() {
* override fun onActivityResumed(a: Activity?) {
* doSomething()
* }
* }
* ```
*/
fun Activity.registerLifecycleCallbacksForThisActivityOnly(callbacksToWrap: Application.ActivityLifecycleCallbacks) {
val wrapped = SingleActivityLifecycleCallbacks(this, callbacksToWrap)
application.registerActivityLifecycleCallbacks(wrapped)
}
/**
* Wrapper for regular [Application.ActivityLifecycleCallbacks] that passes lifecycle callbacks
* only if they concern declared activity. Also it automatically unregister itself from application.
* This is supposed to help avoid boilerplate in lifecycle callback.
*/
private class SingleActivityLifecycleCallbacks(
private val view: Activity,
private val delegate: Application.ActivityLifecycleCallbacks
) : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(a: Activity?, savedInstanceState: Bundle?) {
if (a === view) delegate.onActivityCreated(a, savedInstanceState)
}
override fun onActivityStarted(a: Activity?) {
if (a === view) delegate.onActivityStarted(a)
}
override fun onActivityResumed(a: Activity?) {
if (a === view) delegate.onActivityResumed(a)
}
override fun onActivityPaused(a: Activity?) {
if (a === view) delegate.onActivityPaused(a)
}
override fun onActivityStopped(a: Activity?) {
if (a === view) delegate.onActivityStopped(a)
}
override fun onActivitySaveInstanceState(a: Activity?, outState: Bundle?) {
if (a === view) delegate.onActivitySaveInstanceState(a, outState)
}
override fun onActivityDestroyed(a: Activity?) {
if (a === view) {
delegate.onActivityDestroyed(a)
view.application.unregisterActivityLifecycleCallbacks(this)
}
}
}
/**
* Adapter for [Application.ActivityLifecycleCallbacks] for cases where you want to
* override just one of the callbacks.
*
* Example (before and after):
*
* ```kotlin
* class LifecycleListenerBefore: Application.ActivityLifecycleCallbacks {
* override fun onActivityCreated(a: Activity?, savedInstanceState: Bundle?) {}
* override fun onActivityStarted(a: Activity?) {}
* override fun onActivityResumed(a: Activity?) {
* doSomething()
* }
* override fun onActivityPaused(a: Activity?) {}
* override fun onActivityStopped(a: Activity?) {}
* override fun onActivitySaveInstanceState(a: Activity?, outState: Bundle?) {}
* override fun onActivityDestroyed(a: Activity?) {}
* }
*
* class LifecycleListenerAfter: ActivityLifecycleCallbacksAdapter() {
* override fun onActivityResumed(a: Activity?) {
* doSomething()
* }
* }
* ```
*/
abstract class ActivityLifecycleCallbacksAdapter : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(a: Activity?, savedInstanceState: Bundle?) {}
override fun onActivityStarted(a: Activity?) {}
override fun onActivityResumed(a: Activity?) {}
override fun onActivityPaused(a: Activity?) {}
override fun onActivityStopped(a: Activity?) {}
override fun onActivitySaveInstanceState(a: Activity?, outState: Bundle?) {}
override fun onActivityDestroyed(a: Activity?) {}
}
| apache-2.0 | 77c342661a1b0b85683bcbc4d14d69ab | 34.406015 | 117 | 0.710767 | 5.009574 | false | false | false | false |
Bambooin/trime | app/src/main/java/com/osfans/trime/util/ViewUtils.kt | 2 | 2195 | package com.osfans.trime.util
import android.view.View
import android.view.Window
import android.widget.FrameLayout
import android.widget.LinearLayout
/** (This Kotlin file has been taken from florisboard project)
* This file has been taken from the Android LatinIME project. Following modifications were done by
* florisboard to the original source code:
* - Convert the code from Java to Kotlin
* - Change package name to match the current project's one
* - Remove method newLayoutParam()
* - Remove method placeViewAt()
* - Remove unnecessary variable params in updateLayoutGravityOf(), lp can directly be used due to
* Kotlin's smart cast feature
* - Remove unused imports
*
* The original source code can be found at the following location:
* https://android.googlesource.com/platform/packages/inputmethods/LatinIME/+/refs/heads/master/java/src/com/android/inputmethod/latin/utils/ViewLayoutUtils.java
*/
object ViewUtils {
@JvmStatic
fun updateLayoutHeightOf(window: Window, layoutHeight: Int) {
val params = window.attributes
if (params != null && params.height != layoutHeight) {
params.height = layoutHeight
window.attributes = params
}
}
@JvmStatic
fun updateLayoutHeightOf(view: View, layoutHeight: Int) {
val params = view.layoutParams
if (params != null && params.height != layoutHeight) {
params.height = layoutHeight
view.layoutParams = params
}
}
@JvmStatic
fun updateLayoutGravityOf(view: View, layoutGravity: Int) {
val lp = view.layoutParams
if (lp is LinearLayout.LayoutParams) {
if (lp.gravity != layoutGravity) {
lp.gravity = layoutGravity
view.layoutParams = lp
}
} else if (lp is FrameLayout.LayoutParams) {
if (lp.gravity != layoutGravity) {
lp.gravity = layoutGravity
view.layoutParams = lp
}
} else {
throw IllegalArgumentException(
"Layout parameter doesn't have gravity: " +
lp.javaClass.name
)
}
}
}
| gpl-3.0 | 7e4962b80c7c30087a85452f5a02b793 | 34.983607 | 162 | 0.645558 | 4.740821 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-economy-bukkit/src/main/kotlin/com/rpkit/economy/bukkit/command/currency/CurrencyCommand.kt | 1 | 2203 | /*
* Copyright 2016 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.economy.bukkit.command.currency
import com.rpkit.economy.bukkit.RPKEconomyBukkit
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
/**
* Currency command.
* Parent command for all currency management commands.
*/
class CurrencyCommand(private val plugin: RPKEconomyBukkit): CommandExecutor {
private val currencyAddCommand = CurrencyAddCommand(plugin)
private val currencyRemoveCommand = CurrencyRemoveCommand(plugin)
private val currencyListCommand = CurrencyListCommand(plugin)
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
if (args.isNotEmpty()) {
val newArgs = args.drop(1).toTypedArray()
if (args[0].equals("add", ignoreCase = true) || args[0].equals("create", ignoreCase = true) || args[0].equals("new", ignoreCase = true)) {
return currencyAddCommand.onCommand(sender, command, label, newArgs)
} else if (args[0].equals("remove", ignoreCase = true) || args[0].equals("delete", ignoreCase = true)) {
return currencyRemoveCommand.onCommand(sender, command, label, newArgs)
} else if (args[0].equals("list", ignoreCase = true)) {
return currencyListCommand.onCommand(sender, command, label, newArgs)
} else {
sender.sendMessage(plugin.messages["currency-usage"])
}
} else {
sender.sendMessage(plugin.messages["currency-usage"])
}
return true
}
}
| apache-2.0 | 55a057305393b1a767b9183b496dcf83 | 41.365385 | 150 | 0.692692 | 4.46856 | false | false | false | false |
square/sqldelight | extensions/coroutines-extensions/src/commonMain/kotlin/com/squareup/sqldelight/runtime/coroutines/FlowExtensions.kt | 1 | 2619 | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("FlowQuery")
package com.squareup.sqldelight.runtime.coroutines
import com.squareup.sqldelight.Query
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.Channel.Factory.CONFLATED
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
import kotlin.jvm.JvmName
import kotlin.jvm.JvmOverloads
/** Turns this [Query] into a [Flow] which emits whenever the underlying result set changes. */
@JvmName("toFlow")
fun <T : Any> Query<T>.asFlow(): Flow<Query<T>> = flow {
val channel = Channel<Unit>(CONFLATED)
channel.trySend(Unit)
val listener = object : Query.Listener {
override fun queryResultsChanged() {
channel.trySend(Unit)
}
}
addListener(listener)
try {
for (item in channel) {
emit(this@asFlow)
}
} finally {
removeListener(listener)
}
}
@JvmOverloads
fun <T : Any> Flow<Query<T>>.mapToOne(
context: CoroutineContext = Dispatchers.Default
): Flow<T> = map {
withContext(context) {
it.executeAsOne()
}
}
@JvmOverloads
fun <T : Any> Flow<Query<T>>.mapToOneOrDefault(
defaultValue: T,
context: CoroutineContext = Dispatchers.Default
): Flow<T> = map {
withContext(context) {
it.executeAsOneOrNull() ?: defaultValue
}
}
@JvmOverloads
fun <T : Any> Flow<Query<T>>.mapToOneOrNull(
context: CoroutineContext = Dispatchers.Default
): Flow<T?> = map {
withContext(context) {
it.executeAsOneOrNull()
}
}
@JvmOverloads
fun <T : Any> Flow<Query<T>>.mapToOneNotNull(
context: CoroutineContext = Dispatchers.Default
): Flow<T> = mapNotNull {
withContext(context) {
it.executeAsOneOrNull()
}
}
@JvmOverloads
fun <T : Any> Flow<Query<T>>.mapToList(
context: CoroutineContext = Dispatchers.Default
): Flow<List<T>> = map {
withContext(context) {
it.executeAsList()
}
}
| apache-2.0 | 7ac4e3b7bfcb3163b86d35c89c9ed244 | 25.19 | 95 | 0.726613 | 3.908955 | false | false | false | false |
AdamMc331/CashCaretaker | app/src/main/java/com/androidessence/cashcaretaker/ui/transaction/TransactionViewModel.kt | 1 | 1167 | package com.androidessence.cashcaretaker.ui.transaction
import androidx.databinding.BaseObservable
import com.androidessence.cashcaretaker.R
import com.androidessence.cashcaretaker.core.models.Transaction
import com.androidessence.cashcaretaker.util.asCurrency
import com.androidessence.cashcaretaker.util.asUIString
class TransactionViewModel : BaseObservable() {
var transaction: Transaction? = null
set(value) {
field = value
notifyChange()
}
val description: String
get() {
val description = transaction?.description.orEmpty()
return when {
description.isEmpty() -> NO_DESCRIPTION
else -> description
}
}
val dateString: String
get() = transaction?.date?.asUIString().orEmpty()
val amount: String
get() = transaction?.amount?.asCurrency().orEmpty()
val indicatorColorResource: Int
get() = when {
transaction?.withdrawal == true -> R.color.mds_red_500
else -> R.color.mds_green_500
}
companion object {
const val NO_DESCRIPTION = "N/A"
}
}
| mit | 4d1bbe7c430f90a40865f813a1eb9de9 | 27.463415 | 66 | 0.636675 | 4.8625 | false | false | false | false |
Nice3point/ScheduleMVP | app/src/main/java/nice3point/by/schedule/Adapters/RVAdapter.kt | 1 | 5675 | package nice3point.by.schedule.Adapters
import android.app.FragmentManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import io.realm.Realm
import io.realm.RealmResults
import nice3point.by.schedule.Database.TableObject
import nice3point.by.schedule.Database.TeachersObject
import nice3point.by.schedule.R
import nice3point.by.schedule.ScheduleDialogChanger.VScheduleChanger
import nice3point.by.schedule.TeachersInfoActivity.TeacherInfo
import nice3point.by.schedule.TechnicalModule
class RVAdapter(private val realmResults: RealmResults<TableObject>, private val manager: FragmentManager) : RecyclerView.Adapter<RVAdapter.PersonViewHolder>() {
private lateinit var context: Context
override fun onAttachedToRecyclerView(recyclerView: RecyclerView?) {
super.onAttachedToRecyclerView(recyclerView)
}
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): PersonViewHolder {
context = viewGroup.context
val v = LayoutInflater.from(context).inflate(R.layout.card_view_global, viewGroup, false)
return PersonViewHolder(v)
}
override fun onBindViewHolder(personViewHolder: PersonViewHolder, i: Int) {
val teacher = realmResults[i].teacher
val subject = realmResults[i].subject
val type = realmResults[i].type
val time = realmResults[i].time
val cabinet = realmResults[i].cabinet
val day = realmResults[i].table_name
personViewHolder.Card_subject.text = subject
personViewHolder.Card_teacher.text = teacher
personViewHolder.Card_time.text = time
personViewHolder.Card_cabinet.text = cabinet
// if (i == 0) {
// personViewHolder.relativeLayout.setPadding(30, 30, 30, 0);
// personViewHolder.separator.setPadding(30, 30,30,0);
// } else if (i == (getItemCount() - 1)) {
// personViewHolder.relativeLayout.setPadding(30, 30, 30, 30);
// personViewHolder.separator.setVisibility(View.INVISIBLE);
//
// } else {
// personViewHolder.relativeLayout.setPadding(30, 30, 30, 0);
// personViewHolder.separator.setPadding(30, 30,30,0);
// }
if (type.length >= 4) {
if ("Лаб".equals(type.substring(0, 3), ignoreCase = true)) {
if (!type.contains(" ")) {
personViewHolder.Card_type.text = type
personViewHolder.Card_type.setBackgroundColor(Color.parseColor("#9900AA"))
} else {
personViewHolder.Card_type.text = type.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
personViewHolder.Card_type.setBackgroundColor(Color.parseColor("#9900AA"))
personViewHolder.Card_typeRight.text = type.substring(type.indexOf(" "))
}
} else if ("Практика".equals(type, ignoreCase = true)) {
personViewHolder.Card_type.text = type
personViewHolder.Card_type.setBackgroundColor(Color.parseColor("#00ba00"))
} else
personViewHolder.Card_type.text = type
} else {
personViewHolder.Card_type.text = type
}
personViewHolder.relativeLayout.setOnClickListener {
if (!teacher.isEmpty()) {
val realm = Realm.getInstance(TechnicalModule.getTeacheInfoRealmConfig())
val results = realm.where(TeachersObject::class.java).equalTo("suname", teacher).findFirst()
if (results != null) {
val intent = Intent(context, TeacherInfo::class.java)
intent.putExtra(TeacherInfo.INTENT_SUBJ_KEY, results.subject)
intent.putExtra(TeacherInfo.INTENT_TEL_KEY, results.tel)
intent.putExtra(TeacherInfo.INTENT_SUNAME_KEY, results.suname)
intent.putExtra(TeacherInfo.INTENT_NAME_KEY, results.name)
intent.putExtra(TeacherInfo.INTENT_PHOTO_KEY, results.photo)
context.startActivity(intent)
}
realm.close()
}
}
personViewHolder.relativeLayout.setOnLongClickListener {
val dialog = VScheduleChanger.newInstance(day, teacher, cabinet, type, time, subject)
dialog.show(manager, "Изменение раписания")
true
}
}
override fun getItemCount(): Int {
return realmResults.size
}
inner class PersonViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var Card_subject: TextView
var Card_teacher: TextView
var Card_time: TextView
var Card_type: TextView
var Card_cabinet: TextView
var Card_typeRight: TextView
var relativeLayout: RelativeLayout
init {
Card_subject = itemView.findViewById(R.id.Card_subject)
Card_teacher = itemView.findViewById(R.id.Card_teacher)
Card_time = itemView.findViewById(R.id.Card_time)
Card_type = itemView.findViewById(R.id.Card_type)
Card_typeRight = itemView.findViewById(R.id.Card_typeRight)
Card_cabinet = itemView.findViewById(R.id.Card_cabinet)
relativeLayout = itemView.findViewById(R.id.rv_card)
}
}
}
| apache-2.0 | 36c77eebf975fa0f7089f6c25f1f7521 | 42.767442 | 161 | 0.643464 | 4.697171 | false | false | false | false |
benz2012/FlyCast | Android/src/org/droidplanner/android/fragments/actionbar/FlightModeAdapter.kt | 1 | 3936 | package org.droidplanner.android.fragments.actionbar
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.RadioButton
import android.widget.TextView
import com.google.android.gms.analytics.HitBuilders
import com.o3dr.android.client.Drone
import com.o3dr.android.client.apis.VehicleApi
import com.o3dr.services.android.lib.drone.attribute.AttributeType
import com.o3dr.services.android.lib.drone.property.State
import com.o3dr.services.android.lib.drone.property.Type
import com.o3dr.services.android.lib.drone.property.VehicleMode
import org.droidplanner.android.R
import org.droidplanner.android.utils.analytics.GAUtils
/**
* Created by Fredia Huya-Kouadio on 9/25/15.
*/
public class FlightModeAdapter(context: Context, val drone: Drone) : SelectionListAdapter<VehicleMode>(context) {
private var selectedMode: VehicleMode
private val flightModes : List<VehicleMode>
init {
val state: State = drone.getAttribute(AttributeType.STATE)
selectedMode = state.vehicleMode
val type: Type = drone.getAttribute(AttributeType.TYPE);
flightModes = VehicleMode.getVehicleModePerDroneType(type.droneType)
// BRZ 05/12/2016
// Removing unwanted flight modes
flightModes.remove(VehicleMode.COPTER_ACRO)
flightModes.remove(VehicleMode.COPTER_ALT_HOLD)
flightModes.remove(VehicleMode.COPTER_AUTO)
flightModes.remove(VehicleMode.COPTER_AUTOTUNE)
flightModes.remove(VehicleMode.COPTER_BRAKE) // Bring back later
flightModes.remove(VehicleMode.COPTER_CIRCLE)
flightModes.remove(VehicleMode.COPTER_DRIFT)
flightModes.remove(VehicleMode.COPTER_FLIP)
//flightModes.remove(VehicleMode.COPTER_GUIDED)
flightModes.remove(VehicleMode.COPTER_LOITER)
flightModes.remove(VehicleMode.COPTER_LAND) // Bring Back Later
flightModes.remove(VehicleMode.COPTER_POSHOLD)
flightModes.remove(VehicleMode.COPTER_RTL)
flightModes.remove(VehicleMode.COPTER_SPORT)
flightModes.remove(VehicleMode.COPTER_STABILIZE)
}
override fun getCount() = flightModes.size
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View{
val vehicleMode = flightModes[position]
val containerView = convertView ?: LayoutInflater.from(parent.context).inflate(R.layout.item_selection, parent, false)
val holder = (containerView.tag as ViewHolder?) ?: ViewHolder(containerView.findViewById(R.id.item_selectable_option) as TextView,
containerView.findViewById(R.id.item_selectable_check) as RadioButton)
val clickListener = object : View.OnClickListener {
override fun onClick(v: View?) {
if (drone.isConnected) {
selectedMode = vehicleMode
holder.checkView.isChecked = true
VehicleApi.getApi(drone).setVehicleMode(vehicleMode)
//Record the attempt to change flight modes
val eventBuilder = HitBuilders.EventBuilder().setCategory(GAUtils.Category.FLIGHT).setAction("Flight mode changed").setLabel(vehicleMode.label)
GAUtils.sendEvent(eventBuilder)
listener?.onSelection()
}
}
}
holder.checkView.isChecked = vehicleMode === selectedMode
holder.checkView.setOnClickListener(clickListener)
holder.labelView.text = vehicleMode.label
holder.labelView.setOnClickListener(clickListener)
containerView.setOnClickListener(clickListener)
containerView.tag = holder
return containerView
}
override fun getSelection() = flightModes.indexOf(selectedMode)
public class ViewHolder(val labelView: TextView, val checkView: RadioButton)
} | gpl-3.0 | b3fb8b000ee54caaeba3e68672ed1d34 | 39.587629 | 163 | 0.719512 | 4.619718 | false | false | false | false |
yrsegal/CommandControl | src/main/java/wiresegal/cmdctrl/common/commands/control/CommandProbeNBT.kt | 1 | 2385 | package wiresegal.cmdctrl.common.commands.control
import net.minecraft.command.CommandBase
import net.minecraft.command.CommandException
import net.minecraft.command.CommandResultStats
import net.minecraft.command.ICommandSender
import net.minecraft.nbt.NBTPrimitive
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.server.MinecraftServer
import net.minecraft.util.text.TextComponentTranslation
import wiresegal.cmdctrl.common.CommandControl
import wiresegal.cmdctrl.common.commands.data.TileSelector
import wiresegal.cmdctrl.common.core.CTRLException
import wiresegal.cmdctrl.common.core.CTRLUsageException
import wiresegal.cmdctrl.common.core.getObject
import wiresegal.cmdctrl.common.core.notifyCTRLListener
/**
* @author WireSegal
* Created at 9:19 AM on 12/14/16.
*/
object CommandProbeNBT : CommandBase() {
@Throws(CommandException::class)
override fun execute(server: MinecraftServer, sender: ICommandSender, args: Array<out String>) {
if (args.isEmpty())
throw CTRLUsageException(getCommandUsage(sender))
val selector = args[0]
val key = if (args.size > 1) args[1] else ""
val displayKey = if (key.isBlank()) "commandcontrol.probenbt.blank" else key
val compound: NBTTagCompound
if (TileSelector.isTileSelector(selector)) {
val tile = TileSelector.matchOne(server, sender, selector) ?: throw CTRLException("commandcontrol.probenbt.notile")
compound = tile.writeToNBT(NBTTagCompound())
} else {
val entity = getEntity(server, sender, selector) ?: throw CTRLException("commandcontrol.probenbt.noentity")
compound = entityToNBT(entity)
}
val obj = if (key.isNotBlank())
compound.getObject(key) ?: throw CTRLException("commandcontrol.probenbt.notag", key)
else compound
if (obj is NBTPrimitive) sender.setCommandStat(CommandResultStats.Type.QUERY_RESULT, obj.int)
notifyCTRLListener(sender, this, "commandcontrol.probenbt.success", TextComponentTranslation(displayKey), obj)
}
override fun getRequiredPermissionLevel() = 2
override fun getCommandName() = "probenbt"
override fun getCommandUsage(sender: ICommandSender?) = CommandControl.translate("commandcontrol.probenbt.usage")
override fun isUsernameIndex(args: Array<out String>?, index: Int) = index == 0
}
| mit | ef1e7078021f23536b3df4e0b85b6d20 | 43.166667 | 127 | 0.743816 | 4.457944 | false | false | false | false |
Esri/arcgis-runtime-samples-android | kotlin/viewshed-geoprocessing/src/main/java/com/esri/arcgisruntime/sample/viewshedgeoprocessing/MainActivity.kt | 1 | 9987 | /* Copyright 2020 Esri
*
* 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.esri.arcgisruntime.sample.viewshedgeoprocessing
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.concurrent.Job
import com.esri.arcgisruntime.concurrent.ListenableFuture
import com.esri.arcgisruntime.data.FeatureCollectionTable
import com.esri.arcgisruntime.data.Field
import com.esri.arcgisruntime.geometry.GeometryType
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.viewshedgeoprocessing.databinding.ActivityMainBinding
import com.esri.arcgisruntime.symbology.SimpleFillSymbol
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol
import com.esri.arcgisruntime.symbology.SimpleRenderer
import com.esri.arcgisruntime.tasks.geoprocessing.GeoprocessingFeatures
import com.esri.arcgisruntime.tasks.geoprocessing.GeoprocessingJob
import com.esri.arcgisruntime.tasks.geoprocessing.GeoprocessingParameters
import com.esri.arcgisruntime.tasks.geoprocessing.GeoprocessingTask
import java.util.concurrent.ExecutionException
import kotlin.math.roundToInt
class MainActivity : AppCompatActivity() {
private val TAG: String = this::class.java.simpleName
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
private val loadingView: View by lazy {
activityMainBinding.loadingView
}
private val geoprocessingTask: GeoprocessingTask by lazy { GeoprocessingTask(getString(R.string.viewshed_service)) }
private var geoprocessingJob: GeoprocessingJob? = null
private val inputGraphicsOverlay: GraphicsOverlay by lazy { GraphicsOverlay() }
private val resultGraphicsOverlay: GraphicsOverlay by lazy { GraphicsOverlay() }
// objects that implement Loadable must be class fields to prevent being garbage collected before loading
private lateinit var featureCollectionTable: FeatureCollectionTable
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// authentication with an API key or named user is required to access basemaps and other
// location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
// create renderers for graphics overlays
val fillColor = Color.argb(120, 226, 119, 40)
val fillSymbol = SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, fillColor, null)
resultGraphicsOverlay.renderer = SimpleRenderer(fillSymbol)
val pointSymbol = SimpleMarkerSymbol(
SimpleMarkerSymbol.Style.CIRCLE,
Color.RED,
10F
)
inputGraphicsOverlay.renderer = SimpleRenderer(pointSymbol)
mapView.apply {
// create a map with the Basemap type topographic
map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
// set the viewpoint
setViewpoint(Viewpoint(45.3790, 6.8490, 100000.0))
// add graphics overlays to the map view
graphicsOverlays.addAll(listOf(resultGraphicsOverlay, inputGraphicsOverlay))
// add onTouchListener for calculating the new viewshed
onTouchListener = object : DefaultMapViewOnTouchListener(
applicationContext,
mapView
) {
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
val screenPoint = android.graphics.Point(
e.x.roundToInt(),
e.y.roundToInt()
)
val mapPoint = mMapView.screenToLocation(screenPoint)
addGraphicForPoint(mapPoint)
calculateViewshedFrom(mapPoint)
return super.onSingleTapConfirmed(e)
}
}
}
}
/**
* Adds a graphic at the chosen mapPoint.
*
* @param point in MapView coordinates.
*/
private fun addGraphicForPoint(point: Point) {
// remove existing graphics
inputGraphicsOverlay.graphics.clear()
// add new graphic to the graphics overlay
inputGraphicsOverlay.graphics.add(Graphic(point))
}
/**
* Uses the given point to create a FeatureCollectionTable which is passed to performGeoprocessing.
*
* @param point in MapView coordinates.
*/
private fun calculateViewshedFrom(point: Point) {
// display the LoadingView while calculating the Viewshed
loadingView.visibility = View.VISIBLE
// remove previous graphics
resultGraphicsOverlay.graphics.clear()
// cancel any previous job
geoprocessingJob?.cancelAsync()
// create field with same alias as name
val field = Field.createString("observer", "", 8)
// create feature collection table for point geometry
featureCollectionTable =
FeatureCollectionTable(listOf(field), GeometryType.POINT, point.spatialReference)
featureCollectionTable.loadAsync()
// create a new feature and assign the geometry
val newFeature = featureCollectionTable.createFeature().apply {
geometry = point
}
// add newFeature and call perform Geoprocessing on done loading
featureCollectionTable.addFeatureAsync(newFeature)
featureCollectionTable.addDoneLoadingListener {
if (featureCollectionTable.loadStatus == LoadStatus.LOADED) {
performGeoprocessing(featureCollectionTable)
}
}
}
/**
* Creates a GeoprocessingJob from the GeoprocessingTask. Displays the resulting viewshed on the map.
*
* @param featureCollectionTable the feature collection table containing the observation point.
*/
private fun performGeoprocessing(featureCollectionTable: FeatureCollectionTable) {
// geoprocessing parameters
val parameterFuture: ListenableFuture<GeoprocessingParameters> =
geoprocessingTask.createDefaultParametersAsync()
parameterFuture.addDoneListener {
try {
val parameters = parameterFuture.get().apply {
processSpatialReference = featureCollectionTable.spatialReference
outputSpatialReference = featureCollectionTable.spatialReference
// use the feature collection table to create the required GeoprocessingFeatures input
inputs["Input_Observation_Point"] =
GeoprocessingFeatures(featureCollectionTable)
}
// initialize job from geoprocessingTask
geoprocessingJob = geoprocessingTask.createJob(parameters)
// start the job
geoprocessingJob?.start()
// listen for job success
geoprocessingJob?.addJobDoneListener {
// hide the LoadingView when job is done loading
loadingView.visibility = View.GONE
if (geoprocessingJob?.status == Job.Status.SUCCEEDED) {
// get the viewshed from geoprocessingResult
(geoprocessingJob?.result?.outputs?.get("Viewshed_Result") as? GeoprocessingFeatures)?.let { viewshedResult ->
// for each feature in the result
for (feature in viewshedResult.features) {
// add the feature as a graphic
resultGraphicsOverlay.graphics.add(Graphic(feature.geometry))
}
}
} else {
Toast.makeText(
applicationContext,
"Geoprocessing result failed!",
Toast.LENGTH_LONG
).show()
Log.e(TAG, geoprocessingJob?.error?.cause.toString())
}
}
} catch (e: Exception) {
when (e) {
is InterruptedException, is ExecutionException -> ("Error getting geoprocessing result: " + e.message).also {
Toast.makeText(this, it, Toast.LENGTH_LONG).show()
Log.e(TAG, it)
}
else -> throw e
}
}
}
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
| apache-2.0 | c1ba1465fdb06adfdd5f6080e0816643 | 39.108434 | 134 | 0.658156 | 5.636005 | false | false | false | false |
google/private-compute-libraries | java/com/google/android/libraries/pcc/chronicle/tools/ledger/DtdJson.kt | 1 | 8711 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.tools.ledger
import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptor
import com.google.android.libraries.pcc.chronicle.api.FieldType
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
object DtdJson {
/**
* Serializes/deserializes [DataTypeDescriptor] objects. NOTE: the [DataTypeDescriptor.cls] value
* is not serialized, and is always deserialized to [Any.javaClass]. This is because it is not
* useful for ledger comparison and would be error-prone when using [Class.forName] for builds
* where the type is not included.
*/
object DataTypeDescriptorTypeAdapter : TypeAdapter<DataTypeDescriptor>() {
private const val NAME_FIELD = "name"
private const val FIELDS_FIELD = "fields"
private const val INNER_TYPES_FIELD = "innerTypes"
override fun write(out: JsonWriter, value: DataTypeDescriptor) {
out.makeObject {
writeNamedField(DataHubLedger.gson, NAME_FIELD, value.name)
writeNamedMap(DataHubLedger.gson, FIELDS_FIELD, value.fields)
writeNamedArray(DataHubLedger.gson, INNER_TYPES_FIELD, value.innerTypes) { it.name }
}
}
override fun read(reader: JsonReader): DataTypeDescriptor {
var name = ""
var fields = mapOf<String, FieldType>()
var innerTypes = setOf<DataTypeDescriptor>()
reader.readObject {
when (it) {
NAME_FIELD -> name = nextString()
FIELDS_FIELD -> fields = readMap(DataHubLedger.gson)
INNER_TYPES_FIELD -> innerTypes = readSet(DataHubLedger.gson)
else ->
throw IllegalArgumentException("Unexpected key in DataTypeDescriptor: \"$it\" at $path")
}
}
return DataTypeDescriptor(name, fields, innerTypes, Any::class)
}
}
/** Serializes/deserializes [FieldType] instances to JSON. */
object FieldTypeTypeAdapter : TypeAdapter<FieldType>() {
private const val ARRAY = "Array"
private const val BOOLEAN = "Boolean"
private const val BYTE = "Byte"
private const val BYTE_ARRAY = "ByteArray"
private const val CHAR = "Char"
private const val DOUBLE = "Double"
private const val DURATION = "Duration"
private const val ENUM = "Enum"
private const val FLOAT = "Float"
private const val INSTANT = "Instant"
private const val INTEGER = "Int"
private const val LIST = "List"
private const val LONG = "Long"
private const val NESTED = "Nested"
private const val NULLABLE = "Nullable"
private const val OPAQUE = "Opaque"
private const val REFERENCE = "Reference"
private const val SHORT = "Short"
private const val STRING = "String"
private const val TUPLE = "Tuple"
private const val NAME_FIELD = "name"
private const val TYPE_FIELD = "type"
private const val TYPE_PARAMETER_FIELD = "parameter"
private const val TYPE_PARAMETERS_FIELD = "parameters"
private const val VALUES_FIELD = "values"
private val STRING_TO_FIELDTYPE =
mapOf(
BOOLEAN to FieldType.Boolean,
BYTE to FieldType.Byte,
BYTE_ARRAY to FieldType.ByteArray,
CHAR to FieldType.Char,
DOUBLE to FieldType.Double,
DURATION to FieldType.Duration,
FLOAT to FieldType.Float,
INSTANT to FieldType.Instant,
INTEGER to FieldType.Integer,
LONG to FieldType.Long,
SHORT to FieldType.Short,
STRING to FieldType.String
)
override fun write(out: JsonWriter, value: FieldType) {
when (value) {
FieldType.Boolean -> out.value(BOOLEAN)
FieldType.Byte -> out.value(BYTE)
FieldType.ByteArray -> out.value(BYTE_ARRAY)
FieldType.Char -> out.value(CHAR)
FieldType.Double -> out.value(DOUBLE)
FieldType.Duration -> out.value(DURATION)
FieldType.Float -> out.value(FLOAT)
FieldType.Instant -> out.value(INSTANT)
FieldType.Integer -> out.value(INTEGER)
FieldType.Long -> out.value(LONG)
FieldType.Short -> out.value(SHORT)
FieldType.String -> out.value(STRING)
is FieldType.Array -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, ARRAY)
out.writeNamedField(DataHubLedger.gson, TYPE_PARAMETER_FIELD, value.itemFieldType)
}
}
is FieldType.Enum -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, ENUM)
out.writeNamedField(DataHubLedger.gson, NAME_FIELD, value.name)
out.writeNamedStringArray(DataHubLedger.gson, VALUES_FIELD, value.possibleValues)
}
}
is FieldType.List -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, LIST)
out.writeNamedField(DataHubLedger.gson, TYPE_PARAMETER_FIELD, value.itemFieldType)
}
}
is FieldType.Nested -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, NESTED)
out.writeNamedField(DataHubLedger.gson, NAME_FIELD, value.name)
}
}
is FieldType.Nullable -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, NULLABLE)
out.writeNamedField(DataHubLedger.gson, TYPE_PARAMETER_FIELD, value.itemFieldType)
}
}
is FieldType.Opaque -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, OPAQUE)
out.writeNamedField(DataHubLedger.gson, NAME_FIELD, value.name)
}
}
is FieldType.Reference -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, REFERENCE)
out.writeNamedField(DataHubLedger.gson, NAME_FIELD, value.name)
}
}
is FieldType.Tuple -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, TUPLE)
out.writeNamedArray(DataHubLedger.gson, TYPE_PARAMETERS_FIELD, value.itemFieldTypes) {
it.javaClass.toGenericString()
}
}
}
}
}
override fun read(reader: JsonReader): FieldType {
if (reader.peek() == JsonToken.STRING) {
val typeName = reader.nextString()
return requireNotNull(STRING_TO_FIELDTYPE[typeName]) {
"Unrecognized field type: $typeName"
}
}
var type = ""
var name: String? = null
var typeParameter: FieldType? = null
var typeParameters = emptyList<FieldType>()
var possibleValues = emptyList<String>()
reader.readObject {
when (it) {
NAME_FIELD -> name = nextString()
TYPE_FIELD -> type = nextString()
TYPE_PARAMETER_FIELD -> typeParameter = read(reader)
TYPE_PARAMETERS_FIELD -> typeParameters = readList(DataHubLedger.gson)
VALUES_FIELD -> possibleValues = readStringList()
else -> throw IllegalArgumentException("Unexpected key FieldType: \"$it\" at $path")
}
}
return when (type) {
ARRAY ->
FieldType.Array(requireNotNull(typeParameter) { "Expected type parameter for Array" })
ENUM -> FieldType.Enum(requireNotNull(name) { "Expected name for Enum" }, possibleValues)
LIST -> FieldType.List(requireNotNull(typeParameter) { "Expected type parameter for List" })
NESTED -> FieldType.Nested(requireNotNull(name) { "Expected name for Nested" })
NULLABLE ->
FieldType.Nullable(
requireNotNull(typeParameter) { "Expected type parameter for Nullable" }
)
OPAQUE -> FieldType.Opaque(requireNotNull(name) { "Expected name for Opaque" })
REFERENCE -> FieldType.Reference(requireNotNull(name) { "Expected name for Reference" })
TUPLE -> FieldType.Tuple(typeParameters)
else -> throw IllegalArgumentException("Unexpected FieldType type: \"$type\"")
}
}
}
}
| apache-2.0 | 6ae980f7652280baf79b5c86930cf9a6 | 38.958716 | 100 | 0.652623 | 4.631047 | false | false | false | false |
johnperry-math/Chinese-Remainder-Clock | app/src/main/java/name/cantanima/chineseremainderclock/FlexibleNumberPicker.kt | 1 | 9861 | package name.cantanima.chineseremainderclock
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color.*
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.util.TypedValue.COMPLEX_UNIT_SP
import android.view.MotionEvent
import android.view.MotionEvent.*
import android.view.View
import kotlin.math.max
class FlexibleNumberPicker(context: Context, attrs: AttributeSet)
: View(context, attrs), View.OnTouchListener
{
val tag = "FlexibleNumberPicker"
var min : Int = 0
set(new_min) {
field = new_min
value = (min + max) / 2
}
var max : Int = 10
set(new_max) {
field = new_max
value = (min + max) / 2
}
var skip : Int = 1
var value : Int = ( max + min ) / 2
var text_size = 12f
var high_size = 14f
var typeface = if (Typeface.DEFAULT != null) Typeface.DEFAULT else null
var back_color = BLACK
var text_color = WHITE
var high_color = YELLOW
var horizontal = true
var text_paint = Paint()
var high_paint = Paint()
var back_paint = Paint()
val bounds = Rect()
var single_width = 0
var view_width = 0
var view_height = 0
var draw_offset = 0f
var padding_above = 5
var padding_below = 5
var padding_left = 5
var padding_right = 5
var padding_between = 5
var moving = false
var xprev = 0f
init {
val resources = context.resources
val choices = context.obtainStyledAttributes(attrs, R.styleable.FlexibleNumberPicker)
min = choices.getInt(R.styleable.FlexibleNumberPicker_min, min)
max = choices.getInt(R.styleable.FlexibleNumberPicker_max, max)
skip = choices.getInt(R.styleable.FlexibleNumberPicker_skip, skip)
value = choices.getInt(R.styleable.FlexibleNumberPicker_initial, value)
// TODO: typeface
text_size = choices.getFloat(R.styleable.FlexibleNumberPicker_text_size, text_size)
high_size = choices.getFloat(R.styleable.FlexibleNumberPicker_high_size, high_size)
back_color = choices.getColor(R.styleable.FlexibleNumberPicker_back_color, back_color)
high_color = choices.getColor(R.styleable.FlexibleNumberPicker_high_color, high_color)
text_color = choices.getColor(R.styleable.FlexibleNumberPicker_text_color, text_color)
horizontal = choices.getBoolean(R.styleable.FlexibleNumberPicker_horizontal, horizontal)
choices.recycle()
text_size = TypedValue.applyDimension(COMPLEX_UNIT_SP, text_size, resources.displayMetrics)
high_size = TypedValue.applyDimension(COMPLEX_UNIT_SP, high_size, resources.displayMetrics)
text_paint.typeface = typeface
text_paint.textSize = text_size
text_paint.color = text_color
text_paint.isAntiAlias = true
high_paint.typeface = typeface
high_paint.textSize = high_size
high_paint.color = high_color
high_paint.isAntiAlias = true
back_paint.color = back_color
back_paint.style = Paint.Style.FILL
setOnTouchListener(this)
}
/**
* Implement this to do your drawing.
*
* @param canvas the canvas on which the background will be drawn
*/
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas!!.drawRect(
0f, 0f,
view_width.toFloat(),
view_height.toFloat(),
back_paint
)
canvas.drawText(
value.toString(),
view_width / 2f - single_width / 2 + draw_offset,
(view_height.toFloat() - high_paint.descent() - high_paint.ascent()) / 2,
high_paint
)
if (value > min)
canvas.drawText(
(value - skip).toString(),
view_width / 2f - single_width * 3 / 2 + draw_offset,
(view_height.toFloat() - text_paint.descent() - text_paint.ascent()) / 2,
text_paint
)
if (value > min + skip)
canvas.drawText(
(value - 2 * skip).toString(),
view_width / 2f - single_width * 5 / 2 + draw_offset,
(view_height.toFloat() - text_paint.descent() - text_paint.ascent()) / 2,
text_paint
)
if (value < max)
canvas.drawText(
" " + (value + skip).toString(),
view_width / 2f + single_width / 2 + draw_offset,
(view_height.toFloat() - text_paint.descent() - text_paint.ascent()) / 2,
text_paint
)
if (value < max - skip)
canvas.drawText(
" " + (value + 2 * skip).toString(),
view_width / 2f + 3 * single_width / 2 + draw_offset,
(view_height.toFloat() - text_paint.descent() - text_paint.ascent()) / 2,
text_paint
)
}
/**
*
*
* Measure the view and its content to determine the measured width and the
* measured height. This method is invoked by [.measure] and
* should be overridden by subclasses to provide accurate and efficient
* measurement of their contents.
*
*
*
*
* **CONTRACT:** When overriding this method, you
* *must* call [.setMeasuredDimension] to store the
* measured width and height of this view. Failure to do so will trigger an
* `IllegalStateException`, thrown by
* [.measure]. Calling the superclass'
* [.onMeasure] is a valid use.
*
*
*
*
* The base class implementation of measure defaults to the background size,
* unless a larger size is allowed by the MeasureSpec. Subclasses should
* override [.onMeasure] to provide better measurements of
* their content.
*
*
*
*
* If this method is overridden, it is the subclass's responsibility to make
* sure the measured height and width are at least the view's minimum height
* and width ([.getSuggestedMinimumHeight] and
* [.getSuggestedMinimumWidth]).
*
*
* @param widthMeasureSpec horizontal space requirements as imposed by the parent.
* The requirements are encoded with
* [android.view.View.MeasureSpec].
* @param heightMeasureSpec vertical space requirements as imposed by the parent.
* The requirements are encoded with
* [android.view.View.MeasureSpec].
*
* @see .getMeasuredWidth
* @see .getMeasuredHeight
* @see .setMeasuredDimension
* @see .getSuggestedMinimumHeight
* @see .getSuggestedMinimumWidth
* @see android.view.View.MeasureSpec.getMode
* @see android.view.View.MeasureSpec.getSize
*/
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
high_paint.getTextBounds((min * 10).toString(), 0, (min * 10).toString().length, bounds)
val min_width = bounds.width()
high_paint.getTextBounds((max * 10).toString(), 0, (max * 10).toString().length, bounds)
val max_width = bounds.width()
single_width = max(min_width, max_width)
view_width = single_width * 3 + padding_between * 2 + padding_left + padding_right
view_height = bounds.height() + padding_above + padding_below
setMeasuredDimension(view_width, view_height)
}
/**
* Called when a touch event is dispatched to a view. This allows listeners to
* get a chance to respond before the target view.
*
* @param v The view the touch event has been dispatched to.
* @param event The MotionEvent object containing full information about
* the event.
* @return True if the listener has consumed the event, false otherwise.
*/
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
// let's get some information on where the touch occurred
val x = event!!.rawX
val y = event.rawY
val my_loc = intArrayOf(0, 0)
getLocationOnScreen(my_loc)
if (event.action == ACTION_UP) { // released
moving = false
} else if (event.action == ACTION_MOVE) { // moved/dragged
if (moving) {
var redraw = true
draw_offset += x - xprev
if (draw_offset <= -single_width) {
if (value < max)
value += skip
else
redraw = false
draw_offset = 0f
} else if (draw_offset >= single_width) {
if (value > min)
value -= skip
else
redraw = false
draw_offset = 0f
}
xprev = x
if (redraw) invalidate()
}
} else if (event.action == ACTION_DOWN) { // pressed down
Log.d(tag, "down at $x , $y")
Log.d(tag, "checking within " +
my_loc[0].toString() + "-" + (my_loc[0] + view_width).toString() + " , " +
my_loc[1].toString() + "-" + (my_loc[1] + view_height).toString()
)
if (
(x > my_loc[0]) and (y > my_loc[1]) and
(x < my_loc[0] + view_width) and (y < my_loc[1] + view_height)
) {
moving = true
xprev = x
}
}
return true
}
} | gpl-3.0 | d9f3accfa6b634d493035cc7d88a7a70 | 34.221429 | 99 | 0.572559 | 4.35749 | false | false | false | false |
Fondesa/RecyclerViewDivider | sample/src/main/kotlin/com/fondesa/recyclerviewdivider/sample/StringAdapter.kt | 1 | 2690 | /*
* Copyright (c) 2020 Giorgio Antonioli
*
* 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.fondesa.recyclerviewdivider.sample
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
internal class StringAdapter(
private val isRecyclerViewVertical: Boolean,
private val fullSpanPositions: List<Int> = emptyList()
) : ListAdapter<String, StringAdapter.ViewHolder>(StringDiffUtil) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder(parent, isRecyclerViewVertical)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position), position in fullSpanPositions)
}
private object StringDiffUtil : DiffUtil.ItemCallback<String>() {
override fun areItemsTheSame(oldItem: String, newItem: String): Boolean = oldItem.hashCode() == newItem.hashCode()
override fun areContentsTheSame(oldItem: String, newItem: String): Boolean = oldItem == newItem
}
class ViewHolder private constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(item: String, isFullSpan: Boolean) {
(itemView.layoutParams as? StaggeredGridLayoutManager.LayoutParams)?.isFullSpan = isFullSpan
(itemView as TextView).text = item
}
companion object {
operator fun invoke(parent: ViewGroup, isRecyclerViewVertical: Boolean): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
@LayoutRes val layoutRes = if (isRecyclerViewVertical) {
R.layout.cell_vertical_recycler
} else {
R.layout.cell_horizontal_recycler
}
val inflatedView = inflater.inflate(layoutRes, parent, false)
return ViewHolder(inflatedView)
}
}
}
}
| apache-2.0 | 969bb124f99bd5570913f7ed8668e7c9 | 40.384615 | 126 | 0.715985 | 4.972274 | false | false | false | false |
carmenlau/chat-SDK-Android | chat/src/main/java/io/skygear/plugins/chat/ui/IncomingVoiceMessageView.kt | 1 | 1550 | package io.skygear.plugins.chat.ui
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.stfalcon.chatkit.messages.MessageHolders
import com.stfalcon.chatkit.utils.DateFormatter
import io.skygear.plugins.chat.R
import io.skygear.plugins.chat.ui.model.VoiceMessage
class IncomingVoiceMessageView(view: View):
MessageHolders.IncomingTextMessageViewHolder<VoiceMessage>(view)
{
var actionButton: ImageView? = null
var durationTextView: TextView? = null
var timeTextView: TextView? = null
init {
this.actionButton = view.findViewById<ImageView>(R.id.action_button)
this.durationTextView = view.findViewById<TextView>(R.id.duration)
this.timeTextView = view.findViewById<TextView>(R.id.time)
}
override fun onBind(message: VoiceMessage?) {
super.onBind(message)
message?.let { msg ->
val durationInSecond = msg.duration / 1000
[email protected]?.text =
String.format("%02d:%02d", durationInSecond / 60, durationInSecond % 60)
[email protected]?.text =
DateFormatter.format(msg.createdAt, DateFormatter.Template.TIME)
val actionButtonIcon = when(msg.state) {
VoiceMessage.State.PLAYING -> R.drawable.ic_pause
else -> R.drawable.ic_play
}
[email protected]?.setImageResource(actionButtonIcon)
}
}
}
| apache-2.0 | 79a74e1d6ff00c839abe63dff2e56960 | 36.804878 | 92 | 0.692903 | 4.441261 | false | false | false | false |
azizbekian/Spyur | app/src/main/kotlin/com/incentive/yellowpages/misc/converter/ListingConverter.kt | 1 | 7629 | package com.incentive.yellowpages.misc.converter
import android.content.Context
import com.incentive.yellowpages.data.model.LegendEnum
import com.incentive.yellowpages.data.model.ListingResponse
import com.incentive.yellowpages.data.model.MhdEnum
import com.incentive.yellowpages.data.model.WeekDayEnum
import com.incentive.yellowpages.data.remote.ApiContract
import com.incentive.yellowpages.injection.ApplicationContext
import com.incentive.yellowpages.ui.base.BaseApplication
import okhttp3.ResponseBody
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
import retrofit2.Converter
import retrofit2.Retrofit
import timber.log.Timber
import java.io.IOException
import java.lang.reflect.Type
class ListingConverter : Converter<ResponseBody, ListingResponse> {
companion object {
private val PREFIX_PHONE_NUMBER = "•"
private val PREFIX_DISTRICT = "("
internal val INSTANCE = ListingConverter()
}
@ApplicationContext val context: Context = BaseApplication.appComponent.context()
class Factory : Converter.Factory() {
override fun responseBodyConverter(type: Type?, annotations: Array<Annotation>?,
retrofit: Retrofit?): Converter<ResponseBody, *> {
return INSTANCE
}
}
@Throws(IOException::class)
override fun convert(value: ResponseBody): ListingResponse? {
val builder = ListingResponse.Builder()
val document = Jsoup.parse(value.string(), ApiContract.BASE)
val fieldSets = document.select("fieldset") ?: return null
for (fieldSet in fieldSets) {
val legendEnum = LegendEnum.fromString(context, fieldSet.select("legend").text()) ?: continue
when (legendEnum) {
LegendEnum.CONTACT_INFORMATION -> parseContactInformation(fieldSet, builder)
}
}
return builder.build()
}
private fun parseContactInformation(fieldSet: Element, builder: ListingResponse.Builder) {
val ulClassContactInfo = fieldSet.select("ul[class=contactInfo]").first()
if (null != ulClassContactInfo) {
val mhds = ulClassContactInfo.select("li[class=mhd]") ?: return
for (e in mhds) {
val mhdEnum = MhdEnum.fromString(context, e.text()) ?: continue
when (mhdEnum) {
MhdEnum.EXECUTIVE -> parseExecutives(e.nextElementSibling(), builder)
MhdEnum.ADDRESS_TELEPHONE -> parseAddressTelephone(e.nextElementSibling(), builder)
MhdEnum.WEBSITE -> parseWebsite(e.nextElementSibling(), builder)
MhdEnum.LISTING_IN_SPYUR -> parseListingInSpyur(e.nextElementSibling(), builder)
}
}
val images = fieldSet.select("div[class=div-img]")
if (!images.isEmpty()) {
parseImages(images, builder)
}
val videos = fieldSet.select("div#Slide_video")
if (!videos.isEmpty()) {
parseVideos(videos, builder)
}
}
}
private fun parseVideos(videos: Elements, builder: ListingResponse.Builder) {
builder.setVideoUrl(videos.select("a[class=fl curimg]").first().attr("id"))
}
private fun parseImages(images: Elements, builder: ListingResponse.Builder) {
for (imageDiv in images) {
builder.addImage(imageDiv.select("a").first().attr("abs:href"))
}
}
private fun parseListingInSpyur(element: Element?, builder: ListingResponse.Builder) {
if (null == element) return
builder.setListingInSpyur(element.text())
}
private fun parseWebsite(element: Element?, builder: ListingResponse.Builder) {
if (null == element) return
val websiteDivs = element.select("div > div") ?: return
for (div in websiteDivs) {
builder.addWebsite(div.text())
}
}
private fun parseAddressTelephone(address: Element?, builder: ListingResponse.Builder) {
if (null == address) return
val divs = address.select("li > div") ?: return
var contactInfoBuilder: ListingResponse.ContactInfo.Builder
for (div in divs) {
contactInfoBuilder = ListingResponse.ContactInfo.Builder()
val a = div.select("div > a").first()
if (null != a) {
try {
val lat = java.lang.Double.parseDouble(a.attr("lat"))
val lon = java.lang.Double.parseDouble(a.attr("lon"))
contactInfoBuilder.setLocation(lat, lon)
} catch (ignored: NumberFormatException) {
}
}
contactInfoBuilder.setAddress(div.ownText())
// Region information
val childDivs = div.select("div > div")
if (null != childDivs && childDivs.size > 0) {
var e: Element? = childDivs.first()
do {
val text = e!!.text()
if (text.startsWith(PREFIX_DISTRICT)) {
contactInfoBuilder.setRegion(text.substring(1, text.length - 1))
} else if (text.startsWith(PREFIX_PHONE_NUMBER)) {
try {
contactInfoBuilder.addPhoneNumber(text
.substring(1)
.trim { it <= ' ' }
.replace("-", ""))
} catch (ignored: IndexOutOfBoundsException) {
Timber.e(ignored.message)
}
} else {
parseWorkingDays(e, builder)
}
e = e.nextElementSibling()
} while (e != null)
}
builder.addContactInfo(contactInfoBuilder.build())
}
}
private fun parseWorkingDays(element: Element?, builder: ListingResponse.Builder) {
if (null == element) return
val splittedWorkDays = element.text().split("\\s+".toRegex())
val workingDaysBuilder = ListingResponse.WorkingDays.Builder()
for (workingDay in splittedWorkDays) {
if (workingDay.length > 3) continue
val weekDayEnum = WeekDayEnum.fromString(context, workingDay)
when (weekDayEnum) {
WeekDayEnum.MON -> workingDaysBuilder.setWorkingDay(ListingResponse.WorkingDays.Day.MON)
WeekDayEnum.TUE -> workingDaysBuilder.setWorkingDay(ListingResponse.WorkingDays.Day.TUE)
WeekDayEnum.WED -> workingDaysBuilder.setWorkingDay(ListingResponse.WorkingDays.Day.WED)
WeekDayEnum.THU -> workingDaysBuilder.setWorkingDay(ListingResponse.WorkingDays.Day.THU)
WeekDayEnum.FRI -> workingDaysBuilder.setWorkingDay(ListingResponse.WorkingDays.Day.FRI)
WeekDayEnum.SAT -> workingDaysBuilder.setWorkingDay(ListingResponse.WorkingDays.Day.SAT)
WeekDayEnum.SUN -> workingDaysBuilder.setWorkingDay(ListingResponse.WorkingDays.Day.SUN)
}
}
builder.setWorkingDays(workingDaysBuilder.build())
}
private fun parseExecutives(executives: Element?, builder: ListingResponse.Builder) {
if (null == executives) return
val li = executives.select("li").first()
if (null != li) {
val divs = li.select("div") ?: return
for (e in divs) {
builder.addExecutive(e.text())
}
}
}
}
| gpl-2.0 | 79d48a6a74b65ba5cce5dd48c453890f | 37.715736 | 105 | 0.602334 | 4.959038 | false | false | false | false |
luxons/seven-wonders | sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/cards/Requirements.kt | 1 | 3290 | package org.luxons.sevenwonders.engine.cards
import org.luxons.sevenwonders.engine.Player
import org.luxons.sevenwonders.engine.boards.Board
import org.luxons.sevenwonders.engine.resources.*
import org.luxons.sevenwonders.model.resources.ResourceTransactions
import org.luxons.sevenwonders.model.resources.bestPrice
data class Requirements internal constructor(
val gold: Int = 0,
val resources: Resources = emptyResources(),
) {
/**
* Returns information about the extent to which the given [player] meets these requirements, either on its own or
* by buying resources to neighbours.
*/
internal fun assess(player: Player): RequirementsSatisfaction {
if (player.board.gold < gold) {
return RequirementsSatisfaction.missingRequiredGold(gold)
}
if (resources.isEmpty()) {
if (gold > 0) {
return RequirementsSatisfaction.enoughGold(gold)
}
return RequirementsSatisfaction.noRequirements()
}
if (producesRequiredResources(player.board)) {
if (gold > 0) {
return RequirementsSatisfaction.enoughResourcesAndGold(gold)
}
return RequirementsSatisfaction.enoughResources()
}
return satisfactionWithPotentialHelp(player)
}
private fun satisfactionWithPotentialHelp(player: Player): RequirementsSatisfaction {
val options = transactionOptions(resources, player)
val minPrice = options.bestPrice + gold
if (options.isEmpty()) {
return RequirementsSatisfaction.unavailableResources()
}
if (player.board.gold < minPrice) {
return RequirementsSatisfaction.missingGoldForResources(minPrice, options)
}
return RequirementsSatisfaction.metWithHelp(minPrice, options)
}
/**
* Returns whether the given board meets these requirements, if the specified resources are bought from neighbours.
*
* @param board the board to check
* @param boughtResources the resources the player intends to buy
*
* @return true if the given board meets these requirements
*/
internal fun areMetWithHelpBy(board: Board, boughtResources: ResourceTransactions): Boolean {
if (!hasRequiredGold(board, boughtResources)) {
return false
}
return producesRequiredResources(board) || producesRequiredResourcesWithHelp(board, boughtResources)
}
private fun hasRequiredGold(board: Board, resourceTransactions: ResourceTransactions): Boolean {
val resourcesPrice = board.tradingRules.computeCost(resourceTransactions)
return board.gold >= gold + resourcesPrice
}
private fun producesRequiredResources(board: Board): Boolean = board.production.contains(resources)
private fun producesRequiredResourcesWithHelp(board: Board, transactions: ResourceTransactions): Boolean {
val totalBoughtResources = transactions.asResources()
val remainingResources = resources - totalBoughtResources
return board.production.contains(remainingResources)
}
internal fun pay(player: Player, transactions: ResourceTransactions) {
player.board.removeGold(gold)
transactions.execute(player)
}
}
| mit | bdedd799bd08a95620a29c231273ca42 | 40.125 | 119 | 0.703647 | 5.092879 | false | false | false | false |
LorittaBot/Loritta | buildSrc/src/main/kotlin/SimpleImageInfo.kt | 1 | 5345 | /*
* SimpleImageInfo.java
*
* @version 0.1
* @author Jaimon Mathew <http://www.jaimon.co.uk>
*
* A Java class to determine image width, height and MIME types for a number of image file formats without loading the whole image data.
*
* Revision history
* 0.1 - 29/Jan/2011 - Initial version created
*
* -------------------------------------------------------------------------------
This code is 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.
* -------------------------------------------------------------------------------
*/
import java.io.ByteArrayInputStream
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream
class SimpleImageInfo {
var height: Int = 0
var width: Int = 0
var mimeType: String? = null
private constructor()
@Throws(IOException::class)
constructor(file: File) {
val `is` = FileInputStream(file)
try {
processStream(`is`)
} finally {
`is`.close()
}
}
@Throws(IOException::class)
constructor(`is`: InputStream) {
processStream(`is`)
}
@Throws(IOException::class)
constructor(bytes: ByteArray) {
val `is` = ByteArrayInputStream(bytes)
try {
processStream(`is`)
} finally {
`is`.close()
}
}
@Throws(IOException::class)
private fun processStream(`is`: InputStream) {
val c1 = `is`.read()
val c2 = `is`.read()
var c3 = `is`.read()
mimeType = null
height = -1
width = height
if (c1 == 'G'.toInt() && c2 == 'I'.toInt() && c3 == 'F'.toInt()) { // GIF
`is`.skip(3)
width = readInt(`is`, 2, false)
height = readInt(`is`, 2, false)
mimeType = "image/gif"
} else if (c1 == 0xFF && c2 == 0xD8) { // JPG
while (c3 == 255) {
val marker = `is`.read()
val len = readInt(`is`, 2, true)
if (marker == 192 || marker == 193 || marker == 194) {
`is`.skip(1)
height = readInt(`is`, 2, true)
width = readInt(`is`, 2, true)
mimeType = "image/jpeg"
break
}
`is`.skip((len - 2).toLong())
c3 = `is`.read()
}
} else if (c1 == 137 && c2 == 80 && c3 == 78) { // PNG
`is`.skip(15)
width = readInt(`is`, 2, true)
`is`.skip(2)
height = readInt(`is`, 2, true)
mimeType = "image/png"
} else if (c1 == 66 && c2 == 77) { // BMP
`is`.skip(15)
width = readInt(`is`, 2, false)
`is`.skip(2)
height = readInt(`is`, 2, false)
mimeType = "image/bmp"
} else {
val c4 = `is`.read()
if (c1 == 'M'.toInt() && c2 == 'M'.toInt() && c3 == 0 && c4 == 42 || c1 == 'I'.toInt() && c2 == 'I'.toInt() && c3 == 42 && c4 == 0) { //TIFF
val bigEndian = c1 == 'M'.toInt()
var ifd = 0
val entries: Int
ifd = readInt(`is`, 4, bigEndian)
`is`.skip((ifd - 8).toLong())
entries = readInt(`is`, 2, bigEndian)
for (i in 1..entries) {
val tag = readInt(`is`, 2, bigEndian)
val fieldType = readInt(`is`, 2, bigEndian)
val count = readInt(`is`, 4, bigEndian).toLong()
val valOffset: Int
if (fieldType == 3 || fieldType == 8) {
valOffset = readInt(`is`, 2, bigEndian)
`is`.skip(2)
} else {
valOffset = readInt(`is`, 4, bigEndian)
}
if (tag == 256) {
width = valOffset
} else if (tag == 257) {
height = valOffset
}
if (width != -1 && height != -1) {
mimeType = "image/tiff"
break
}
}
}
}
if (mimeType == null) {
throw IOException("Unsupported image type")
}
}
@Throws(IOException::class)
private fun readInt(`is`: InputStream, noOfBytes: Int, bigEndian: Boolean): Int {
var ret = 0
var sv = if (bigEndian) (noOfBytes - 1) * 8 else 0
val cnt = if (bigEndian) -8 else 8
for (i in 0 until noOfBytes) {
ret = ret or (`is`.read() shl sv)
sv += cnt
}
return ret
}
override fun toString(): String {
return "MIME Type : $mimeType\t Width : $width\t Height : $height"
}
} | agpl-3.0 | 5fdd2d9d69610ccebb0746f656c8e637 | 32.204969 | 152 | 0.464359 | 4.185591 | false | false | false | false |
darakeon/dfm | android/App/src/main/kotlin/com/darakeon/dfm/moves/MovesActivity.kt | 1 | 10844 | package com.darakeon.dfm.moves
import android.graphics.Paint
import android.os.Bundle
import android.view.View
import android.view.View.FOCUS_DOWN
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.darakeon.dfm.R
import com.darakeon.dfm.base.BaseActivity
import com.darakeon.dfm.dialogs.alertError
import com.darakeon.dfm.dialogs.getDateDialog
import com.darakeon.dfm.extensions.ON_CLICK
import com.darakeon.dfm.extensions.addMask
import com.darakeon.dfm.extensions.backWithExtras
import com.darakeon.dfm.extensions.getFromJson
import com.darakeon.dfm.extensions.putJson
import com.darakeon.dfm.lib.api.entities.Date
import com.darakeon.dfm.lib.api.entities.moves.Move
import com.darakeon.dfm.lib.api.entities.moves.MoveCreation
import com.darakeon.dfm.lib.api.entities.moves.Nature
import com.darakeon.dfm.lib.api.entities.setCombo
import com.darakeon.dfm.lib.extensions.applyGlyphicon
import com.darakeon.dfm.lib.extensions.changeColSpan
import com.darakeon.dfm.lib.extensions.onChange
import com.darakeon.dfm.lib.extensions.showChangeList
import com.darakeon.dfm.lib.extensions.toDoubleByCulture
import kotlinx.android.synthetic.main.moves.account_in
import kotlinx.android.synthetic.main.moves.account_in_picker
import kotlinx.android.synthetic.main.moves.account_out
import kotlinx.android.synthetic.main.moves.account_out_picker
import kotlinx.android.synthetic.main.moves.category
import kotlinx.android.synthetic.main.moves.category_picker
import kotlinx.android.synthetic.main.moves.date
import kotlinx.android.synthetic.main.moves.date_picker
import kotlinx.android.synthetic.main.moves.description
import kotlinx.android.synthetic.main.moves.detail_amount
import kotlinx.android.synthetic.main.moves.detail_description
import kotlinx.android.synthetic.main.moves.detail_value
import kotlinx.android.synthetic.main.moves.detailed_value
import kotlinx.android.synthetic.main.moves.details
import kotlinx.android.synthetic.main.moves.form
import kotlinx.android.synthetic.main.moves.main
import kotlinx.android.synthetic.main.moves.nature_in
import kotlinx.android.synthetic.main.moves.nature_out
import kotlinx.android.synthetic.main.moves.nature_transfer
import kotlinx.android.synthetic.main.moves.no_accounts
import kotlinx.android.synthetic.main.moves.no_categories
import kotlinx.android.synthetic.main.moves.remove_check
import kotlinx.android.synthetic.main.moves.simple_value
import kotlinx.android.synthetic.main.moves.value
import kotlinx.android.synthetic.main.moves.warnings
import java.util.UUID
class MovesActivity : BaseActivity() {
override val contentView = R.layout.moves
override val title = R.string.title_activity_move
private var move = Move()
private val moveKey = "move"
private var moveForm = MoveCreation()
private val moveFormKey = "moveForm"
private var offlineHash = 0
private val offlineHashKey = "offlineHash"
private var accountUrl = ""
private var id: UUID? = null
private val amountDefault
get() = resources.getInteger(
R.integer.amount_default
).toString()
override val refresh: SwipeRefreshLayout?
get() = main
private var loadedScreen = false
private val fallbackManager = MovesService.manager(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arrayOf(
date_picker,
category_picker,
account_out_picker,
account_in_picker
).forEach { it.applyGlyphicon() }
accountUrl = getExtraOrUrl("accountUrl") ?: ""
val id = getExtraOrUrl("id")
if (id != null)
this.id = tryGetGuid(id)
detail_amount.setText(amountDefault)
if (savedInstanceState == null) {
if (this.id != null) {
callApi { it.getMove(this.id, this::populateScreen) }
} else {
move.date = Date()
populateResponse()
}
} else {
move = savedInstanceState.getFromJson(moveKey, Move())
moveForm = savedInstanceState.getFromJson(moveFormKey, MoveCreation())
offlineHash = savedInstanceState.getInt(offlineHashKey, 0)
populateResponse()
}
}
private fun tryGetGuid(id: String?) =
try {
UUID.fromString(id)
} catch (e: IllegalArgumentException) {
null
}
private fun populateScreen(data: MoveCreation) {
moveForm = data
val move = data.move
var error = ""
if (move != null) {
this.move = move
} else {
fallbackManager.printCounting()
val previousError = fallbackManager.error
if (previousError == null) {
this.move.date = Date()
} else {
this.move = previousError.obj
error = previousError.error
offlineHash = previousError.hashCode()
}
}
populateResponse()
if (error != "") {
val tried = getString(R.string.background_move_error)
alertError("$tried: $error")
}
}
private fun populateResponse() {
move.setDefaultData(accountUrl, isUsingCategories)
if (!isMoveAllowed())
return
main.scrollChild = form
if (move.checked)
remove_check.visibility = VISIBLE
description.setText(move.description)
description.onChange { move.description = it }
populateDate()
populateCategory()
populateAccounts()
setNatureFromAccounts()
populateValue()
loadedScreen = true
}
private fun isMoveAllowed(): Boolean {
var canMove = true
if (blockedByAccounts()) {
canMove = false
no_accounts.visibility = VISIBLE
}
if (blockedByCategories()) {
canMove = false
no_categories.visibility = VISIBLE
}
if (!canMove) {
form.visibility = GONE
warnings.visibility = VISIBLE
}
return canMove
}
private fun blockedByAccounts() =
accountCombo.isEmpty()
private fun blockedByCategories() =
isUsingCategories && categoryCombo.isEmpty()
private fun populateDate() {
date.addMask("####-##-##")
date.setText(move.date.format())
date.onChange { move.date = Date(it) }
date_picker.setOnClickListener { showDatePicker() }
}
fun showDatePicker() {
with(move.date) {
getDateDialog(year, javaMonth, day) { y, m, d ->
date.setText(Date(y, m+1, d).format())
}.show()
}
}
private fun populateCategory() {
when {
isUsingCategories -> {
populateCategoryCombo()
}
move.warnCategory -> {
setupWarnLoseCategory()
}
else -> {
hideCategory()
}
}
}
private fun populateCategoryCombo() {
categoryCombo.setCombo(
category,
category_picker,
move::categoryName,
this::changeCategory
)
}
fun changeCategory() {
showChangeList(categoryCombo, R.string.category) {
text, _ -> category.setText(text)
}
}
private fun setupWarnLoseCategory() {
category.visibility = GONE
category.changeColSpan(0)
category_picker.changeColSpan(4)
category_picker.text = move.categoryName
category_picker.paintFlags += Paint.STRIKE_THRU_TEXT_FLAG
category_picker.setOnClickListener {
this.alertError(R.string.losingCategory)
}
}
private fun hideCategory() {
category.visibility = GONE
category_picker.visibility = GONE
date.changeColSpan(7)
category.changeColSpan(0)
category_picker.changeColSpan(0)
}
private fun populateAccounts() {
accountCombo.setCombo(
account_out,
account_out_picker,
move::outUrl,
this::changeAccountOut
)
account_out.onChange {
setNatureFromAccounts()
}
accountCombo.setCombo(
account_in,
account_in_picker,
move::inUrl,
this::changeAccountIn
)
account_in.onChange {
setNatureFromAccounts()
}
}
fun changeAccountOut() {
showChangeList(accountCombo, R.string.account) { text, _ ->
account_out.setText(text)
}
}
fun changeAccountIn() {
showChangeList(accountCombo, R.string.account) { text, _ ->
account_in.setText(text)
}
}
private fun setNatureFromAccounts() {
val hasOut = !move.outUrl.isNullOrBlank()
val hasIn = !move.inUrl.isNullOrBlank()
when {
hasOut && hasIn -> move.natureEnum = Nature.Transfer
hasOut -> move.natureEnum = Nature.Out
hasIn -> move.natureEnum = Nature.In
else -> move.natureEnum = null
}
runOnUiThread {
nature_out.isChecked = false
nature_transfer.isChecked = false
nature_in.isChecked = false
when (move.natureEnum) {
Nature.Out -> nature_out.isChecked = true
Nature.Transfer -> nature_transfer.isChecked = true
Nature.In -> nature_in.isChecked = true
else -> {}
}
}
}
private fun populateValue() {
if (move.detailList.isNotEmpty()) {
useDetailed()
move.detailList.forEach {
addViewDetail(move, it.description, it.amount, it.value)
}
} else if (move.value != null) {
useSimple()
value.setText(String.format("%1$,.2f", move.value))
}
value.onChange { move.setValue(it) }
}
private fun useDetailed() {
move.isDetailed = true
simple_value.visibility = GONE
detailed_value.visibility = VISIBLE
account_in.nextFocusDownId = R.id.detail_description
scrollToTheEnd(detail_description)
}
private fun addViewDetail(move: Move, description: String, amount: Int, value: Double) {
val row = DetailBox(this, move, description, amount, value)
details.addView(row)
}
private fun useSimple() {
move.isDetailed = false
simple_value.visibility = VISIBLE
detailed_value.visibility = GONE
account_in.nextFocusDownId = R.id.value
scrollToTheEnd(value)
}
private fun scrollToTheEnd(view: View) {
form.post {
form.fullScroll(FOCUS_DOWN)
view.requestFocus()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putJson(moveKey, move)
outState.putJson(moveFormKey, moveForm)
outState.putInt(offlineHashKey, offlineHash)
}
fun useDetailed(@Suppress(ON_CLICK) view: View) {
useDetailed()
}
fun useSimple(@Suppress(ON_CLICK) view: View) {
useSimple()
}
fun addDetail(@Suppress(ON_CLICK) view: View) {
val description = detail_description.text.toString()
val amount = detail_amount.text.toString().toIntOrNull()
val value = detail_value.text.toString().toDoubleByCulture()
if (description.isEmpty() || amount == null || value == null) {
alertError(R.string.fill_all)
return
}
detail_description.setText("")
detail_amount.setText(amountDefault)
detail_value.setText("")
move.add(description, amount, value)
addViewDetail(move, description, amount, value)
scrollToTheEnd(detail_description)
}
fun save(@Suppress(ON_CLICK) view: View) {
move.clearNotUsedValues()
callApi {
it.saveMove(move) {
fallbackManager.remove(offlineHash)
clearAndBack()
}
}
}
override fun offline() {
if (loadedScreen) {
error(R.string.offline_fallback_moves, R.string.ok_button) {
MovesService.start(this, move)
clearAndBack()
}
} else {
super.offline()
}
}
private fun clearAndBack() {
intent.removeExtra("id")
backWithExtras()
}
fun cancel(@Suppress(ON_CLICK) view: View) {
fallbackManager.remove(offlineHash)
backWithExtras()
}
}
| gpl-3.0 | cd4cadd963ec2b0e25c7f2eea931bb8b | 23.589569 | 89 | 0.732294 | 3.428391 | false | false | false | false |
cketti/okhttp | okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt | 1 | 10239 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.tls.internal.der
import java.math.BigInteger
import java.net.ProtocolException
import okio.Buffer
import okio.BufferedSource
import okio.ByteString
import okio.ForwardingSource
import okio.IOException
import okio.Source
import okio.buffer
/**
* Streaming decoder of data encoded following Abstract Syntax Notation One (ASN.1). There are
* multiple variants of ASN.1, including:
*
* * DER: Distinguished Encoding Rules. This further constrains ASN.1 for deterministic encoding.
* * BER: Basic Encoding Rules.
*
* This class was implemented according to the [X.690 spec][[x690]], and under the advice of
* [Lets Encrypt's ASN.1 and DER][asn1_and_der] guide.
*
* [x690]: https://www.itu.int/rec/T-REC-X.690
* [asn1_and_der]: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/
*/
internal class DerReader(source: Source) {
private val countingSource: CountingSource = CountingSource(source)
private val source: BufferedSource = countingSource.buffer()
/** Total bytes read thus far. */
private val byteCount: Long
get() = countingSource.bytesRead - source.buffer.size
/** How many bytes to read before [peekHeader] should return false, or -1L for no limit. */
private var limit = -1L
/** Type hints scoped to the call stack, manipulated with [withTypeHint]. */
private val typeHintStack = mutableListOf<Any?>()
/**
* The type hint for the current object. Used to pick adapters based on other fields, such as
* in extensions which have different types depending on their extension ID.
*/
var typeHint: Any?
get() = typeHintStack.lastOrNull()
set(value) {
typeHintStack[typeHintStack.size - 1] = value
}
/** Names leading to the current location in the ASN.1 document. */
private val path = mutableListOf<String>()
private var constructed = false
private var peekedHeader: DerHeader? = null
private val bytesLeft: Long
get() = if (limit == -1L) -1L else (limit - byteCount)
fun hasNext(): Boolean = peekHeader() != null
/**
* Returns the next header to process unless this scope is exhausted.
*
* This returns null if:
*
* * The stream is exhausted.
* * We've read all of the bytes of an object whose length is known.
* * We've reached the [DerHeader.TAG_END_OF_CONTENTS] of an object whose length is unknown.
*/
fun peekHeader(): DerHeader? {
var result = peekedHeader
if (result == null) {
result = readHeader()
peekedHeader = result
}
if (result.isEndOfData) return null
return result
}
/**
* Consume the next header in the stream and return it. If there is no header to read because we
* have reached a limit, this returns [END_OF_DATA].
*/
private fun readHeader(): DerHeader {
require(peekedHeader == null)
// We've hit a local limit.
if (byteCount == limit) return END_OF_DATA
// We've exhausted the source stream.
if (limit == -1L && source.exhausted()) return END_OF_DATA
// Read the tag.
val tagAndClass = source.readByte().toInt() and 0xff
val tagClass = tagAndClass and 0b1100_0000
val constructed = (tagAndClass and 0b0010_0000) == 0b0010_0000
val tag0 = tagAndClass and 0b0001_1111
val tag = when (tag0) {
0b0001_1111 -> readVariableLengthLong()
else -> tag0.toLong()
}
// Read the length.
val length0 = source.readByte().toInt() and 0xff
val length = when {
length0 == 0b1000_0000 -> {
// Indefinite length.
-1L
}
(length0 and 0b1000_0000) == 0b1000_0000 -> {
// Length specified over multiple bytes.
val lengthBytes = length0 and 0b0111_1111
var lengthBits = source.readByte().toLong() and 0xff
for (i in 1 until lengthBytes) {
lengthBits = lengthBits shl 8
lengthBits += source.readByte().toInt() and 0xff
}
lengthBits
}
else -> {
// Length is 127 or fewer bytes.
(length0 and 0b0111_1111).toLong()
}
}
// Note that this may be be an encoded "end of data" header.
return DerHeader(tagClass, tag, constructed, length)
}
/**
* Consume a header and execute [block], which should consume the entire value described by the
* header. It is an error to not consume a full value in [block].
*/
internal inline fun <T> read(name: String?, block: (DerHeader) -> T): T {
if (!hasNext()) throw IOException("expected a value")
val header = peekedHeader!!
peekedHeader = null
val pushedLimit = limit
val pushedConstructed = constructed
limit = if (header.length != -1L) byteCount + header.length else -1L
constructed = header.constructed
if (name != null) path += name
try {
return block(header)
} finally {
peekedHeader = null
limit = pushedLimit
constructed = pushedConstructed
if (name != null) path.removeAt(path.size - 1)
}
}
private inline fun readAll(block: (DerHeader) -> Unit) {
while (hasNext()) {
read(null, block)
}
}
/**
* Execute [block] with a new namespace for type hints. Type hints from the enclosing type are no
* longer usable by the current type's members.
*/
fun <T> withTypeHint(block: () -> T): T {
typeHintStack.add(null)
try {
return block()
} finally {
typeHintStack.removeAt(typeHintStack.size - 1)
}
}
fun readBoolean(): Boolean {
if (bytesLeft != 1L) throw ProtocolException("unexpected length: $bytesLeft at $this")
return source.readByte().toInt() != 0
}
fun readBigInteger(): BigInteger {
if (bytesLeft == 0L) throw ProtocolException("unexpected length: $bytesLeft at $this")
val byteArray = source.readByteArray(bytesLeft)
return BigInteger(byteArray)
}
fun readLong(): Long {
if (bytesLeft !in 1..8) throw ProtocolException("unexpected length: $bytesLeft at $this")
var result = source.readByte().toLong() // No "and 0xff" because this is a signed value!
while (byteCount < limit) {
result = result shl 8
result += source.readByte().toInt() and 0xff
}
return result
}
fun readBitString(): BitString {
val buffer = Buffer()
val unusedBitCount = readBitString(buffer)
return BitString(buffer.readByteString(), unusedBitCount)
}
private fun readBitString(sink: Buffer): Int {
if (bytesLeft != -1L) {
val unusedBitCount = source.readByte().toInt() and 0xff
source.read(sink, bytesLeft)
return unusedBitCount
} else {
var unusedBitCount = 0
readAll {
unusedBitCount = readBitString(sink)
}
return unusedBitCount
}
}
fun readOctetString(): ByteString {
val buffer = Buffer()
readOctetString(buffer)
return buffer.readByteString()
}
private fun readOctetString(sink: Buffer) {
if (bytesLeft != -1L && !constructed) {
source.read(sink, bytesLeft)
} else {
readAll {
readOctetString(sink)
}
}
}
fun readUtf8String(): String {
val buffer = Buffer()
readUtf8String(buffer)
return buffer.readUtf8()
}
private fun readUtf8String(sink: Buffer) {
if (bytesLeft != -1L && !constructed) {
source.read(sink, bytesLeft)
} else {
readAll {
readUtf8String(sink)
}
}
}
fun readObjectIdentifier(): String {
val result = Buffer()
val dot = '.'.toByte().toInt()
when (val xy = readVariableLengthLong()) {
in 0L until 40L -> {
result.writeDecimalLong(0)
result.writeByte(dot)
result.writeDecimalLong(xy)
}
in 40L until 80L -> {
result.writeDecimalLong(1)
result.writeByte(dot)
result.writeDecimalLong(xy - 40L)
}
else -> {
result.writeDecimalLong(2)
result.writeByte(dot)
result.writeDecimalLong(xy - 80L)
}
}
while (byteCount < limit) {
result.writeByte(dot)
result.writeDecimalLong(readVariableLengthLong())
}
return result.readUtf8()
}
fun readRelativeObjectIdentifier(): String {
val result = Buffer()
val dot = '.'.toByte().toInt()
while (byteCount < limit) {
if (result.size > 0) {
result.writeByte(dot)
}
result.writeDecimalLong(readVariableLengthLong())
}
return result.readUtf8()
}
/** Used for tags and subidentifiers. */
private fun readVariableLengthLong(): Long {
// TODO(jwilson): detect overflow.
var result = 0L
while (true) {
val byteN = source.readByte().toLong() and 0xff
if ((byteN and 0b1000_0000L) == 0b1000_0000L) {
result = (result + (byteN and 0b0111_1111)) shl 7
} else {
return result + byteN
}
}
}
override fun toString() = path.joinToString(separator = " / ")
companion object {
/**
* A synthetic value that indicates there's no more bytes. Values with equivalent data may also
* show up in ASN.1 streams to also indicate the end of SEQUENCE, SET or other constructed
* value.
*/
private val END_OF_DATA = DerHeader(
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = DerHeader.TAG_END_OF_CONTENTS,
constructed = false,
length = -1L
)
}
/** A source that keeps track of how many bytes it's consumed. */
private class CountingSource(source: Source) : ForwardingSource(source) {
var bytesRead = 0L
override fun read(sink: Buffer, byteCount: Long): Long {
val result = delegate.read(sink, byteCount)
if (result == -1L) return -1L
bytesRead += result
return result
}
}
}
| apache-2.0 | 5c4f5251175a872a666981c164e1bfd4 | 28.422414 | 99 | 0.647622 | 4.0956 | false | false | false | false |
oukingtim/king-admin | king-admin-kotlin/src/main/kotlin/com/oukingtim/web/vm/MenuVM.kt | 1 | 782 | package com.oukingtim.web.vm
import com.oukingtim.domain.SysMenu
import org.springframework.beans.BeanUtils
/**
* Created by oukingtim
*/
class MenuVM() {
var id: String? = null
var parentId: String? = null
var name: String? = null
var stateRef: String? = null
var type: String? = null
var icon: String? = null
var title: String? = null
var level: Int? = null
var order: Int? = null
var subMenu: List<MenuVM>? = null
constructor(sm : SysMenu):this(){
this.stateRef = sm.name
this.name = sm.name
this.type = sm.type
this.icon = sm.icon
this.title = sm.title
this.level = sm.level
this.order = sm.order
this.parentId = sm.parentId
this.id = sm.id
}
} | mit | 93ae976a9a14e6a32d891e385fb29e48 | 24.258065 | 42 | 0.595908 | 3.603687 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/integration/crafttweaker/GasificationUnit.kt | 1 | 2887 | package com.cout970.magneticraft.systems.integration.crafttweaker
import com.cout970.magneticraft.api.internal.registries.machines.gasificationunit.GasificationUnitRecipeManager
import crafttweaker.annotations.ZenRegister
import crafttweaker.api.item.IIngredient
import crafttweaker.api.item.IItemStack
import crafttweaker.api.liquid.ILiquidStack
import net.minecraft.item.ItemStack
import stanhebben.zenscript.annotations.ZenClass
import stanhebben.zenscript.annotations.ZenMethod
@Suppress("UNUSED")
@ZenClass("mods.magneticraft.GasificationUnit")
@ZenRegister
object GasificationUnit {
@ZenMethod
@JvmStatic
fun addRecipe(input: IIngredient, out1: IItemStack?, out2: ILiquidStack?, ticks: Float, minTemp: Float) {
CraftTweakerPlugin.delayExecution {
val inStack = input.items
val outStack1 = out1?.toStack() ?: ItemStack.EMPTY
val outStack2 = out2?.toStack()
if (inStack != null) {
if (inStack.isEmpty()) {
ctLogError("[GasificationUnit] Invalid input stack: EMPTY")
return@delayExecution
}
}
if (outStack1.isEmpty && outStack2 == null) {
ctLogError("[GasificationUnit] Missing output: item: EMPTY, fluid: null, inputItem: $input")
return@delayExecution
}
if (minTemp < 0) {
ctLogError("[GasificationUnit] Invalid min temperature: $minTemp, must be positive")
return@delayExecution
}
if (ticks < 0) {
ctLogError("[GasificationUnit] Invalid processing time: $ticks, must be positive")
return@delayExecution
}
if (inStack != null) {
for (inputItem in inStack) {
val recipe = GasificationUnitRecipeManager.createRecipe(inputItem.toStack(), outStack1, outStack2, ticks, minTemp, false)
applyAction("Adding $recipe") {
GasificationUnitRecipeManager.registerRecipe(recipe)
}
}
}
}
}
@ZenMethod
@JvmStatic
fun removeRecipe(input: IItemStack) {
CraftTweakerPlugin.delayExecution {
val inStack = input.toStack()
inStack.ifEmpty {
ctLogError("[GasificationUnit] Invalid input stack: EMPTY")
return@delayExecution
}
val recipe = GasificationUnitRecipeManager.findRecipe(inStack)
if (recipe == null) {
ctLogError("[GasificationUnit] Cannot remove recipe: No recipe found for $input")
return@delayExecution
}
applyAction("Removing $recipe") {
GasificationUnitRecipeManager.removeRecipe(recipe)
}
}
}
} | gpl-2.0 | 96cc629a339c4aa0536a128d84b08043 | 33.380952 | 141 | 0.607551 | 5.137011 | false | false | false | false |
pokebyte/ararat | library/src/main/java/org/akop/ararat/io/CrosswordCompilerFormatter.kt | 1 | 7841 | // Copyright (c) Akop Karapetyan
//
// 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 org.akop.ararat.io
import org.akop.ararat.core.Crossword
import org.akop.ararat.util.SparseArray
import org.xmlpull.v1.XmlPullParser
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
class CrosswordCompilerFormatter : SimpleXmlParser(), CrosswordFormatter {
private var builder: Crossword.Builder? = null
private val wordBuilders = SparseArray<Crossword.Word.Builder>()
private var cells: Array<Array<CCCell?>>? = null
private var currentWordBuilder: Crossword.Word.Builder? = null
override fun setEncoding(encoding: String) { /* Stub */ }
@Throws(IOException::class)
override fun read(builder: Crossword.Builder, inputStream: InputStream) {
// Initialize state
wordBuilders.clear()
cells = null
currentWordBuilder = null
this.builder = builder
parseXml(inputStream)
wordBuilders.forEach { _, v ->
if (v.number == Crossword.Word.Builder.NUMBER_NONE) {
// For any words that don't have numbers, check the cells
val cell = cells!![v.startRow][v.startColumn]!!
if (cell.number != Crossword.Word.Builder.NUMBER_NONE) {
v.number = cell.number
}
}
builder.words += v.build()
}
}
@Throws(IOException::class)
override fun write(crossword: Crossword, outputStream: OutputStream) {
throw UnsupportedOperationException("Writing not supported")
}
override fun canRead(): Boolean = true
override fun canWrite(): Boolean = false
override fun onStartElement(path: SimpleXmlParser.SimpleXmlPath, parser: XmlPullParser) {
super.onStartElement(path, parser)
if (!path.startsWith("?", "rectangular-puzzle")) return
if (path.startsWith("crossword")) {
if (path.startsWith("grid")) {
if (path.isEqualTo("cell")) {
// ?/rectangular-puzzle/crossword/grid/cell
parser.stringValue("solution")?.let { sol ->
val row = parser.intValue("y", 0) - 1
val column = parser.intValue("x", 0) - 1
val number = parser.intValue("number", Crossword.Word.Builder.NUMBER_NONE)
val cell = CCCell(sol, number)
cells!![row][column] = cell
parser.stringValue("background-shape")?.let {
cell.attr = cell.attr or Crossword.Cell.ATTR_CIRCLED
}
}
} else if (path.isDeadEnd) {
// ?/rectangular-puzzle/crossword/grid
val width = parser.intValue("width", -1)
val height = parser.intValue("height", -1)
cells = Array(height) { arrayOfNulls<CCCell?>(width) }
builder!!.width = width
builder!!.height = height
}
} else if (path.isEqualTo("word")) {
// ?/rectangular-puzzle/crossword/word
val id = parser.intValue("id", -1)
val xSpan = parser.stringValue("x")!!
val ySpan = parser.stringValue("y")!!
val xDashIndex = xSpan.indexOf("-")
val wb = Crossword.Word.Builder()
if (xDashIndex != -1) {
val startColumn = xSpan.substring(0, xDashIndex).toInt() - 1
val endColumn = xSpan.substring(xDashIndex + 1).toInt() - 1
val row = ySpan.toInt() - 1
// Across
wb.direction = Crossword.Word.DIR_ACROSS
wb.startRow = row
wb.startColumn = startColumn
// Build the individual characters from the char map
for (column in startColumn..endColumn) {
val cell = cells!![row][column]!!
wb.addCell(cell.chars, cell.attr)
}
} else {
val yDashIndex = ySpan.indexOf("-")
val startRow = ySpan.substring(0, yDashIndex).toInt() - 1
val endRow = ySpan.substring(yDashIndex + 1).toInt() - 1
val column = xSpan.toInt() - 1
// Down
wb.direction = Crossword.Word.DIR_DOWN
wb.startRow = startRow
wb.startColumn = column
// Build the individual characters from the char map
for (row in startRow..endRow) {
val cell = cells!![row][column]!!
wb.addCell(cell.chars, cell.attr)
}
}
wordBuilders.put(id, wb)
} else if (path.isEqualTo("clues", "clue")) {
// ?/rectangular-puzzle/crossword/clues/clue
val wordId = parser.intValue("word", -1)
val number = parser.intValue("number", -1)
currentWordBuilder = wordBuilders[wordId]
currentWordBuilder!!.number = number
currentWordBuilder!!.hintUrl = parser.stringValue("hint-url")
currentWordBuilder!!.citation = parser.stringValue("citation")
}
} else if (path.isDeadEnd) {
// ?/rectangular-puzzle
parser.stringValue("alphabet")?.let {
builder!!.setAlphabet(it.toCharArray().toSet())
}
}
}
override fun onTextContent(path: SimpleXmlParser.SimpleXmlPath, text: String) {
super.onTextContent(path, text)
if (!path.startsWith("?", "rectangular-puzzle")) return
if (path.startsWith("metadata")) {
when {
path.isEqualTo("title") -> // ?/rectangular-puzzle/metadata/title
builder!!.title = text
path.isEqualTo("creator") -> // ?/rectangular-puzzle/metadata/creator
builder!!.author = text
path.isEqualTo("copyright") -> // ?/rectangular-puzzle/metadata/copyright
builder!!.copyright = text
path.isEqualTo("description") -> // ?/rectangular-puzzle/metadata/description
builder!!.description = text
}
} else if (path.isEqualTo("crossword", "clues", "clue")) {
// ?/rectangular-puzzle/crossword/clues/clue
currentWordBuilder!!.hint = text
}
}
private class CCCell(val chars: String,
val number: Int,
var attr: Int = 0)
}
| mit | b755b7bbe18b9040223990fbf5fc1316 | 40.707447 | 98 | 0.56128 | 5.039203 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.