repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
siosio/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/mirror/kotlinx.kt
1
3564
// 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.debugger.coroutine.proxy.mirror import com.sun.jdi.LongValue import com.sun.jdi.ObjectReference import com.sun.jdi.StringReference import org.jetbrains.kotlin.idea.debugger.evaluate.DefaultExecutionContext class CoroutineContext(context: DefaultExecutionContext) : BaseMirror<ObjectReference, MirrorOfCoroutineContext>("kotlin.coroutines.CombinedContext", context) { private val coroutineNameRef = CoroutineName(context) private val coroutineIdRef = CoroutineId(context) private val jobRef = Job(context) private val dispatcherRef = CoroutineDispatcher(context) private val getContextElement by MethodDelegate<ObjectReference>("get") override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): MirrorOfCoroutineContext? { val coroutineName = getElementValue(value, context, coroutineNameRef) val coroutineId = getElementValue(value, context, coroutineIdRef) val job = getElementValue(value, context, jobRef) val dispatcher = getElementValue(value, context, dispatcherRef) return MirrorOfCoroutineContext(value, coroutineName, coroutineId, dispatcher, job) } private fun <T> getElementValue(value: ObjectReference, context: DefaultExecutionContext, keyProvider: ContextKey<T>): T? { val key = keyProvider.key() ?: return null val elementValue = getContextElement.value(value, context, key) return keyProvider.mirror(elementValue, context) } } abstract class ContextKey<T>(name: String, context: DefaultExecutionContext) : BaseMirror<ObjectReference, T>(name, context) { abstract fun key(): ObjectReference? } class CoroutineName(context: DefaultExecutionContext) : ContextKey<String>("kotlinx.coroutines.CoroutineName", context) { private val key by FieldDelegate<ObjectReference>("Key") private val getNameRef by MethodDelegate<StringReference>("getName") override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): String? { return getNameRef.value(value, context)?.value() } override fun key() = key.staticValue() } class CoroutineId(context: DefaultExecutionContext) : ContextKey<Long>("kotlinx.coroutines.CoroutineId", context) { private val key by FieldDelegate<ObjectReference>("Key") private val getIdRef by MethodDelegate<LongValue>("getId") override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): Long? { return getIdRef.value(value, context)?.longValue() } override fun key() = key.staticValue() } class Job(context: DefaultExecutionContext) : ContextKey<ObjectReference>("kotlinx.coroutines.Job\$Key", context) { private val key by FieldDelegate<ObjectReference>("\$\$INSTANCE") override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): ObjectReference? { return value } override fun key() = key.staticValue() } class CoroutineDispatcher(context: DefaultExecutionContext) : ContextKey<String>("kotlinx.coroutines.CoroutineDispatcher", context) { private val key by FieldDelegate<ObjectReference>("Key") private val jlm = JavaLangObjectToString(context) override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): String? { return jlm.mirror(value, context) } override fun key() = key.staticValue() }
apache-2.0
af484cc8741c666f9ffacd98d6daf633
44.692308
158
0.759259
4.835821
false
false
false
false
nsk-mironov/sento
sento-compiler/src/main/kotlin/io/mironov/sento/compiler/common/Naming.kt
1
2549
package io.mironov.sento.compiler.common import io.mironov.sento.compiler.model.ListenerTargetSpec import io.mironov.sento.compiler.model.ViewSpec import io.mironov.sento.compiler.reflect.ClassSpec import io.mironov.sento.compiler.reflect.MethodSpec import org.objectweb.asm.Opcodes.ACC_PUBLIC import org.objectweb.asm.Opcodes.ACC_STATIC import org.objectweb.asm.Opcodes.ACC_SYNTHETIC import org.objectweb.asm.Type import org.objectweb.asm.commons.Method import java.util.HashMap import java.util.concurrent.atomic.AtomicInteger internal class Naming { private val anonymous = HashMap<Type, AtomicInteger>() private companion object { private val METHOD_BIND_SPEC = MethodSpec(ACC_PUBLIC, "bind", Type.getMethodType(Types.VOID, Types.OBJECT, Types.OBJECT, Types.FINDER)) private val METHOD_BIND_SYNTHETIC_SPEC = MethodSpec(ACC_PUBLIC + ACC_STATIC + ACC_SYNTHETIC, "sento\$bind", METHOD_BIND_SPEC.type) private val METHOD_UNBIND_SPEC = MethodSpec(ACC_PUBLIC, "unbind", Type.getMethodType(Types.VOID, Types.OBJECT)) private val METHOD_UNBIND_SYNTHETIC_SPEC = MethodSpec(ACC_PUBLIC + ACC_STATIC + ACC_SYNTHETIC, "sento\$unbind", METHOD_UNBIND_SPEC.type) } fun getBindingType(spec: ClassSpec): Type { return Type.getObjectType("${spec.type.internalName}\$SentoBinding"); } fun getAnonymousType(type: Type): Type { return Type.getObjectType("${type.internalName}\$${anonymous.getOrPut(type) { AtomicInteger() }.andIncrement}") } fun getSyntheticAccessor(owner: ClassSpec, method: MethodSpec): Method { return getSyntheticAccessor(owner, method, getSyntheticAccessorName(owner, method)) } fun getSyntheticAccessor(owner: ClassSpec, method: MethodSpec, name: String): Method { return Methods.get(name, method.returns, *arrayOf(owner.type, *method.arguments)) } fun getSyntheticAccessorName(owner: ClassSpec, method: MethodSpec): String { return "sento\$accessor\$${method.name}" } fun getBindMethodSpec(): MethodSpec { return METHOD_BIND_SPEC } fun getUnbindMethodSpec(): MethodSpec { return METHOD_UNBIND_SPEC } fun getSyntheticBindMethodSpec(): MethodSpec { return METHOD_BIND_SYNTHETIC_SPEC } fun getSyntheticUnbindMethodSpec(): MethodSpec { return METHOD_UNBIND_SYNTHETIC_SPEC } fun getSyntheticFieldName(target: ViewSpec): String { return "sento\$view\$id_${target.id}" } fun getSyntheticFieldName(target: ListenerTargetSpec): String { return "sento\$listener\$${target.method.name}\$${target.annotation.type.simpleName}" } }
apache-2.0
b5108609959d007b7a60af47fa47fdeb
35.942029
140
0.75716
4.014173
false
false
false
false
pokk/SSFM
app/src/main/kotlin/taiwan/no1/app/ssfm/models/entities/PreferenceEntity.kt
1
905
package taiwan.no1.app.ssfm.models.entities import android.support.annotation.DrawableRes import io.reactivex.Observer import taiwan.no1.app.ssfm.misc.widgets.recyclerviews.viewtype.ExpandableViewTypeFactory import taiwan.no1.app.ssfm.models.IExpandVisitable /** * The entity of the main item of the preference setting. * * @author jieyi * @since 9/8/17 */ data class PreferenceEntity(val title: String, var attributes: String, @DrawableRes val icon: Int = -1, var observer: Observer<String>? = null, override var childItemList: List<IExpandVisitable> = mutableListOf(), override var isExpanded: Boolean = false) : IExpandVisitable { override fun type(typeFactory: ExpandableViewTypeFactory): Int = typeFactory.type(this) }
apache-2.0
88ec6af9db5c196acca0cdfe08c53f02
40.181818
97
0.638674
4.547739
false
false
false
false
androidx/androidx
compose/ui/ui-lint/src/test/java/androidx/compose/ui/lint/ComposedModifierDetectorTest.kt
3
8989
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("UnstableApiUsage") package androidx.compose.ui.lint import androidx.compose.lint.test.Stubs import androidx.compose.lint.test.compiledStub import com.android.tools.lint.checks.infrastructure.LintDetectorTest import com.android.tools.lint.checks.infrastructure.TestMode import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Issue import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 /* ktlint-disable max-line-length */ /** * Test for [ComposedModifierDetector]. */ @RunWith(JUnit4::class) class ComposedModifierDetectorTest : LintDetectorTest() { override fun getDetector(): Detector = ComposedModifierDetector() override fun getIssues(): MutableList<Issue> = mutableListOf(ComposedModifierDetector.UnnecessaryComposedModifier) /** * Simplified Modifier.composed stub */ private val composedStub = compiledStub( filename = "ComposedModifier.kt", filepath = "androidx/compose/ui", checksum = 0xad91cb77, """ package androidx.compose.ui import androidx.compose.runtime.Composable fun Modifier.composed( inspectorInfo: () -> Unit = {}, factory: @Composable Modifier.() -> Modifier ): Modifier = this """, """ META-INF/main.kotlin_module: H4sIAAAAAAAAAGNgYGBmYGBgBGJWKM3ApcYlkZiXUpSfmVKhl5yfW5BfnKpX VJpXkpmbKsQVlJqbmpuUWuRdwqXJJYyhrjRTSMgZwk7xzU/JTMsEK+XjYilJ LS4RYgsBkt4lSgxaDACMRj6sewAAAA== """, """ androidx/compose/ui/ComposedModifierKt$composed$1.class: H4sIAAAAAAAAAJVUWU8TURT+7nQfipRFWdy1YgvKtOCaNiSEQJxQMBFsYni6 7Qxw6fSOmaXBN/6C/0Q0kUQTw7M/ynjutDW4gU4y956c831nn/n67dMXAA/w lKHMpeW5wjowmm77tevbRiiM5a5orbuW2BG2txbke1YrX06BMazVWm7gCGns d9qGkIHtSe4YNd5uWLxy2rYTymYgXOkbqz2pVO3bX0oRVBYrDFN/d5ZCnOHa 2Q5TSDIkq4LcLTLECsU6Q7xgFutZpKHrSGCAFMGe8BkWav9dMCWYFLLjtmyG sUKxts873HC43DWeN/btZlDJYggZHRqGGQZO1ZbCKEPa3NjcWtpYXmEY/Knw LC7iUgZjGCdQtelE6auMI1dTynwhQ9IVhuE+cd0OuMUDTilp7U6MhsjUkWBg LSXESH8glFQiySozjJ4cJvWTQ13LabmTwymtxJ7pyjRPqVa5dOWbthv61DYw TP9ba1KYZcj96I9l7/DQCRjeFv7Y2z7xvLU4x16umL93vnh2xCzuY4568GsN cy1KN77sWjTRkZrb5E6de4I3HHtLHQxDNSHtjbDdsL2eJmtKaXvLDvd9m9Zo aEU2HdcXcpdGsudaDJlNsSt5EHoE1jfd0Gvaq0IxJ1+EMhBtuy58Qa6WpHQD HtWGEo03QY2nTwqTat40uDi9tAOkKZOUJwTNBsmZ2DGyR2rgmKcz29ViMOIM qwXsMWYjDL0KrGEhgilF6hSRdYm5JSLmesR5upUtPfMRI+8x8e4MfroXOE1p 9wOPE1o9A5+hvTrG5Q+4ehQpEvSnAXSCdQETeBjVeQ8GHkVBYngc3SU8obtM yGvEur6NmIkbJm7SiVsmbiNv4g6mt8F83EVhG5qPoo+Z7xp9fu/RBAAA """, """ androidx/compose/ui/ComposedModifierKt.class: H4sIAAAAAAAAALVU308bRxD+9vzr7BpibJISh1DSOAkYkrNJ2qY1IY1QkE4x bhVTXnhazmuy+LyH7s6IvET8C33sa/+Cqk9RHyrUx0r9l6rOns+BAMKVqtq6 uZmdmW++nZ29P//+7XcAT/Atw32uOr4nO0eW4/UPvEBYA2mtD9XOpteRXSn8 V2EGjKGwzw+55XK1Z323uy8cWk0wmHFih+HdQvMyuBFMo9nzQlcqa/+wb3UH ygmlpwJrI9ZqY/z1xuLV8Ax//TcCqyP/D0qGjbVxfFYfXl1t6Wr32vj93G16 /p61L8Jdn0sqzZXyQj6k0fLC1sB1KSq9Gr6RwZqJLMPcGcpShcJX3LVsFfqU Lp0gg08YrjtvhNOL87/nPu8LCmR4sNA8f8KNMyttDbLXWNzOYwKTOeRxjWGC cA8o0PNt1fVMTDFkulzbb02UGCYrmlvldEbmxu15ftyUjA2pU0hhVLHSEV0+ cEOGH//n6bQvdm/sAdf/3fX70L9KPYNbdOfsVnvrRWv9JcPjS0tcCdHI4zbm spjFZx8PzCW7zuBOHimkczBwl2Fq1IRNEfIODzntwegfJuhzwrRIMbCeVgxa P5Jaq5HWqTPwk+O53MlxzpgxRi+jcKoOn/LTwslx2aixKj0rkyZFlM1ismjU krXEymwhVZ6JLDaUtfQfP6cNMxNJUxdaYSiOOJ4dGVyyrufk3sX2+QMVyr6I e8h3XdHQYxsnvzwKBV0lT41Qtt4e6IDS+ZY/6tHMJde9jmC41pRKtAb9XeFv aUBNxnO4u819qe14MduWe4qHA5/0W6+HNGx1KANJ7hend5+hct774Rp/FDbR DrnT2+QHcYG8rZTw110eBILcubY38B2xIbXvZgy5faEc6nT4SeifgZt6Gsj6 kqzXZOsjnq4Wc+9RWCoWSS4Xp0lWf4mivyKZ1r1HFk9Jnx/G4zpuRHjTmMKn 5NdaCTOU8XWUl8E3caZJ7wY9pURsnJGFLNEpk67JPCPolAa6nXz3E3K/Yv4E nzerS8vvURmSWSVJKBMRq8mISZr+Gfqcpcl6RnaOwGYjZjNYi5K+wHN6b9D6 PYK/v4OEjQc2Fkhi0UYVSzaW8XAHLMAjWDvIBkgFuBFgKkCNehegFGAlwOMA T/4BiHoaCXoHAAA= """ ) @Test fun noComposableCalls() { lint().files( kotlin( """ package test import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.runtime.Composable fun Modifier.test(): Modifier = composed { this@test } fun Modifier.test(): Modifier { return composed { this@test } } fun Modifier.test3(): Modifier = composed(factory = { this@test3 }) fun Modifier.test4(): Modifier = composed({}, { this@test4}) """ ), composedStub, Stubs.Composable, Stubs.Modifier ) .skipTestModes(TestMode.WHITESPACE) // b/202187519, remove when upgrading to 7.1.0 .run() .expect( """ src/test/test.kt:8: Warning: Unnecessary use of Modifier.composed [UnnecessaryComposedModifier] fun Modifier.test(): Modifier = composed { ~~~~~~~~ src/test/test.kt:13: Warning: Unnecessary use of Modifier.composed [UnnecessaryComposedModifier] return composed { ~~~~~~~~ src/test/test.kt:18: Warning: Unnecessary use of Modifier.composed [UnnecessaryComposedModifier] fun Modifier.test3(): Modifier = composed(factory = { ~~~~~~~~ src/test/test.kt:22: Warning: Unnecessary use of Modifier.composed [UnnecessaryComposedModifier] fun Modifier.test4(): Modifier = composed({}, { this@test4}) ~~~~~~~~ 0 errors, 4 warnings """ ) } @Test fun composableCalls() { lint().files( kotlin( """ package test import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.runtime.* inline fun <T> scopingFunction(lambda: () -> T): T { return lambda() } fun Modifier.test1(): Modifier = composed { val foo = remember { true } this@test1 } @Composable fun composableFunction() {} fun Modifier.test2(): Modifier = composed { composableFunction() this@test2 } fun Modifier.test3(): Modifier = composed { scopingFunction { val foo = remember { true } this@test3 } } @Composable fun <T> composableScopingFunction(lambda: @Composable () -> T): T { return lambda() } fun Modifier.test4(): Modifier = composed { composableScopingFunction { this@test4 } } val composableProperty: Boolean @Composable get() = true fun Modifier.test5(): Modifier = composed { composableProperty this@test5 } // Test for https://youtrack.jetbrains.com/issue/KT-46795 fun Modifier.test6(): Modifier = composed { val nullable: Boolean? = null val foo = nullable ?: false val bar = remember { true } this@test6 } """ ), composedStub, Stubs.Composable, Stubs.Modifier, Stubs.Remember ) .skipTestModes(TestMode.WHITESPACE) // b/202187519, remove when upgrading to 7.1.0 .run() .expectClean() } } /* ktlint-enable max-line-length */
apache-2.0
3534caeeb1d8e522b2b6424a6fe869fb
37.072034
96
0.613022
3.286394
false
true
false
false
GunoH/intellij-community
plugins/devkit/intellij.devkit.workspaceModel/src/codegen/writer/WorkspaceCodegenProblemsProvider.kt
3
4067
// 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.devkit.workspaceModel.codegen.writer import com.intellij.analysis.problemsView.FileProblem import com.intellij.analysis.problemsView.Problem import com.intellij.analysis.problemsView.ProblemsCollector import com.intellij.analysis.problemsView.ProblemsProvider import com.intellij.analysis.problemsView.toolWindow.ProblemsViewToolWindowUtils.selectProjectErrorsTab import com.intellij.codeHighlighting.HighlightDisplayLevel import com.intellij.devkit.workspaceModel.metaModel.ObjMetaElementWithSource import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.refactoring.suggested.startOffset import com.intellij.workspaceModel.codegen.engine.GenerationProblem import com.intellij.workspaceModel.codegen.engine.ProblemLocation import org.jetbrains.kotlin.resolve.source.getPsi import javax.swing.Icon @Service class WorkspaceCodegenProblemsProvider(override val project: Project): ProblemsProvider { private var currentProblems = emptyList<WorkspaceModelCodeGenerationProblem>() companion object { fun getInstance(project: Project): WorkspaceCodegenProblemsProvider = project.service() } fun reportProblems(generationProblems: List<GenerationProblem>) { if (generationProblems.isNotEmpty() && ApplicationManager.getApplication().isUnitTestMode) { val problem = generationProblems.first() error("Failed to generate code for ${problem.location}: ${problem.message}") } val problems = generationProblems.map { it.toProblem() } for (currentProblem in currentProblems) { ProblemsCollector.getInstance(project).problemDisappeared(currentProblem) } currentProblems = problems for (currentProblem in problems) { ProblemsCollector.getInstance(project).problemAppeared(currentProblem) } if (problems.isNotEmpty()) { selectProjectErrorsTab(project) } } private fun GenerationProblem.toProblem(): WorkspaceModelCodeGenerationProblem { val sourceElement = when (val problemLocation = location) { is ProblemLocation.Class -> (problemLocation.objClass as ObjMetaElementWithSource).sourceElement is ProblemLocation.Property -> (problemLocation.property as ObjMetaElementWithSource).sourceElement } val psiElement = sourceElement.getPsi() ?: return WorkspaceModelCodeGenerationProblem(this) val psiToHighlight = (psiElement as? PsiNameIdentifierOwner)?.nameIdentifier ?: psiElement val file = psiToHighlight.containingFile.virtualFile val document = FileDocumentManager.getInstance().getDocument(file) ?: return WorkspaceModelCodeGenerationProblem(this) val offset = psiToHighlight.startOffset val line = document.getLineNumber(offset) val column = offset - document.getLineStartOffset(line) return WorkspaceModelCodeGenerationProblemInFile(this, file, line, column) } private open inner class WorkspaceModelCodeGenerationProblem(private val originalProblem: GenerationProblem) : Problem { override val provider: ProblemsProvider get() = this@WorkspaceCodegenProblemsProvider override val text: String get() = originalProblem.message override val icon: Icon get() = when (originalProblem.level) { GenerationProblem.Level.ERROR -> HighlightDisplayLevel.ERROR.icon GenerationProblem.Level.WARNING -> HighlightDisplayLevel.WARNING.icon } } private open inner class WorkspaceModelCodeGenerationProblemInFile( originalProblem: GenerationProblem, override val file: VirtualFile, override val line: Int, override val column: Int ) : WorkspaceModelCodeGenerationProblem(originalProblem), FileProblem }
apache-2.0
f25b5869b18d7bdc73792cc1aff58aaf
45.747126
122
0.797885
5.115723
false
false
false
false
poetix/centipede
src/main/java/com/codepoetics/centipede/SuffixAwareLinkClassifier.kt
1
835
package com.codepoetics.centipede import java.net.URI class SuffixAwareLinkClassifier() : LinkClassifier { companion object { val staticSuffixes = setOf("js", "css", "gif", "jpg", "png", "ico", "ogg", "mp3", "zip", "pdf", "tgz") } override fun invoke(domain: Domain, uri: URI): Link = if (domainsMatch(domain, uri)) { if (isStaticResource(uri)) { Link.StaticResource(uri) } else { Link.SiteLink(uri) } } else { Link.ExternalLink(uri) } private fun domainsMatch(domain: Domain, uri: URI): Boolean = uri.host != null && uri.host.endsWith(domain) private fun isStaticResource(uri: URI): Boolean = staticSuffixes.stream().anyMatch { uri.path.endsWith(".${it}") } }
apache-2.0
5aa079cfa531c262c2bfac7dba7566a5
32.4
118
0.560479
3.957346
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToFunctionInvocationFix.kt
1
1984
// 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.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.* class ChangeToFunctionInvocationFix(element: KtExpression) : KotlinQuickFixAction<KtExpression>(element) { override fun getFamilyName() = KotlinBundle.message("fix.change.to.function.invocation") override fun getText() = familyName public override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val psiFactory = KtPsiFactory(element) val nextLiteralStringEntry = element.parent.nextSibling as? KtLiteralStringTemplateEntry val nextText = nextLiteralStringEntry?.text if (nextText != null && nextText.startsWith("(") && nextText.contains(")")) { val parentheses = nextText.takeWhile { it != ')' } + ")" val newNextText = nextText.removePrefix(parentheses) if (newNextText.isNotEmpty()) { nextLiteralStringEntry.replace(psiFactory.createLiteralStringTemplateEntry(newNextText)) } else { nextLiteralStringEntry.delete() } element.replace(KtPsiFactory(file).createExpressionByPattern("$0$1", element, parentheses)) } else { element.replace(KtPsiFactory(file).createExpressionByPattern("$0()", element)) } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtExpression>? { val expression = diagnostic.psiElement as? KtExpression ?: return null return ChangeToFunctionInvocationFix(expression) } } }
apache-2.0
4fb8abe5744f20308d03675a16160273
47.390244
158
0.705141
5.087179
false
false
false
false
BijoySingh/Quick-Note-Android
scarlet/src/main/java/com/bijoysingh/quicknote/drive/GDriveRemoteImageFolder.kt
1
5427
package com.bijoysingh.quicknote.drive import com.bijoysingh.quicknote.database.RemoteDataType import com.bijoysingh.quicknote.database.RemoteUploadData import com.bijoysingh.quicknote.database.RemoteUploadDataDao import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppImageStorage import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import java.io.File import java.util.* import java.util.concurrent.atomic.AtomicBoolean data class ImageUUID( val noteUuid: String, val imageUuid: String) { fun name(): String = "$noteUuid::$imageUuid" override fun equals(other: Any?): Boolean { if (other !is ImageUUID) { return false } return other.imageUuid == imageUuid && other.noteUuid == noteUuid } override fun hashCode(): Int { return Objects.hash(noteUuid, imageUuid) } } fun toImageUUID(imageUuid: String): ImageUUID? { val components = imageUuid.split("::") if (components.size == 2) { val noteUuid = components[0] val imageId = components[1] return ImageUUID(noteUuid, imageId) } return null } class GDriveRemoteImageFolder( dataType: RemoteDataType, database: RemoteUploadDataDao, service: GDriveServiceHelper, onPendingChange: () -> Unit) : GDriveRemoteFolderBase<File>(dataType, database, service, onPendingChange) { private val networkOrAbsoluteFailure = AtomicBoolean(false) private val contentLoading = AtomicBoolean(true) private var contentFolderUid: String = INVALID_FILE_ID private val contentFiles = emptyMap<ImageUUID, String>().toMutableMap() private val contentPendingActions = emptySet<ImageUUID>().toMutableSet() private val deletedPendingActions = emptySet<ImageUUID>().toMutableSet() override fun initContentFolder(resourceId: String?, onSuccess: () -> Unit) { if (resourceId === null) { return } initContentFolderId(resourceId, onSuccess) } override fun initDeletedFolder(resourceId: String?, onSuccess: () -> Unit) { // Ignore } override fun insert(remoteData: RemoteUploadData, resource: File) { val image = toImageUUID(remoteData.uuid) if (image !== null) { insert(image) } } override fun delete(remoteData: RemoteUploadData) { val image = toImageUUID(remoteData.uuid) if (image !== null) { delete(image) } } override fun invalidate() { networkOrAbsoluteFailure.set(false) contentLoading.set(true) contentFolderUid = INVALID_FILE_ID contentFiles.clear() contentPendingActions.clear() deletedPendingActions.clear() } private fun initContentFolderId(fUid: String, onLoaded: () -> Unit) { contentFolderUid = fUid GlobalScope.launch(Dispatchers.IO) { service.getFilesInFolder(contentFolderUid, GOOGLE_DRIVE_IMAGE_MIME_TYPE) { filesList -> networkOrAbsoluteFailure.set(filesList === null) val imageFiles = filesList?.files if (imageFiles !== null) { imageFiles.forEach { imageFile -> val components = toImageUUID(imageFile.name) if (components !== null) { contentFiles[components] = imageFile.id notifyDriveData(imageFile) } } contentLoading.set(false) } GlobalScope.launch { onLoaded() } } } } private fun insert(id: ImageUUID) { if (contentLoading.get()) { contentPendingActions.add(id) return } if (networkOrAbsoluteFailure.get()) { return } if (contentFiles.containsKey(id)) { GlobalScope.launch { database.getByUUID(dataType.name, id.name())?.apply { remoteUpdateTimestamp = lastUpdateTimestamp remoteStateDeleted = localStateDeleted save(database) } onPendingChange() } return } val gDriveUUID = id.name() val timestamp = database.getByUUID(dataType.name, gDriveUUID)?.lastUpdateTimestamp ?: getTrueCurrentTime() val imageFile = sAppImageStorage.getFile(id.noteUuid, id.imageUuid) if (!imageFile.exists()) { // notifyDriveData(id, gDriveUUID, timestamp) val existing = database.getByUUID(RemoteDataType.IMAGE.name, gDriveUUID) if (existing !== null) { database.delete(existing) } onPendingChange() return } service.createFileFromFile(contentFolderUid, gDriveUUID, imageFile, timestamp) { file -> if (file !== null) { contentFiles[id] = file.id notifyDriveData(file.id, gDriveUUID, timestamp) } } } private fun delete(id: ImageUUID) { if (contentLoading.get()) { deletedPendingActions.add(id) return } if (networkOrAbsoluteFailure.get()) { return } if (!contentFiles.containsKey(id)) { GlobalScope.launch { val existing = database.getByUUID(dataType.name, id.name()) if (existing !== null) { database.delete(existing) } } return } GlobalScope.launch { val fuid = contentFiles[id] ?: INVALID_FILE_ID val existing = database.getByUUID(dataType.name, id.name()) val timestamp = existing?.lastUpdateTimestamp ?: getTrueCurrentTime() service.removeFileOrFolder(fuid) { success -> if (success) { notifyDriveData(fuid, id.name(), timestamp, true) contentFiles.remove(id) } } } } }
gpl-3.0
6fb94768b66f463bf2d75e57821e971b
27.270833
109
0.669246
4.22993
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/security/controller/PinLockController.kt
1
1201
package com.maubis.scarlet.base.security.controller import android.os.SystemClock import com.github.bijoysingh.starter.util.TextUtils import com.maubis.scarlet.base.settings.sheet.sSecurityAppLockEnabled import com.maubis.scarlet.base.settings.sheet.sSecurityAskPinAlways import com.maubis.scarlet.base.settings.sheet.sSecurityCode object PinLockController { private var sLastLoginTimeMs = 0L fun isPinCodeEnabled(): Boolean { return !TextUtils.isNullOrEmpty(sSecurityCode) } fun needsAppLock(): Boolean { // App lock enabled if (isPinCodeEnabled() && sSecurityAppLockEnabled) { return needsLockCheckImpl() } return false } fun needsLockCheck(): Boolean { if (sSecurityAskPinAlways) { return true } return needsLockCheckImpl() } private fun needsLockCheckImpl(): Boolean { val deltaSinceLastUnlock = SystemClock.uptimeMillis() - sLastLoginTimeMs // unlock stays 10 minutes if (sLastLoginTimeMs == 0L || deltaSinceLastUnlock > 1000 * 60 * 5) { return true } // reset lock time notifyPinVerified() return false } fun notifyPinVerified() { sLastLoginTimeMs = SystemClock.uptimeMillis() } }
gpl-3.0
a0e33e31c038737e92dbb55463879b1f
23.530612
76
0.72856
4.098976
false
false
false
false
smmribeiro/intellij-community
java/compiler/impl/src/com/intellij/packaging/impl/artifacts/workspacemodel/EntityToElement.kt
1
11503
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.packaging.impl.artifacts.workspacemodel import com.intellij.configurationStore.deserializeInto import com.intellij.openapi.module.ModulePointerManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.registry.Registry import com.intellij.packaging.artifacts.ArtifactPointerManager import com.intellij.packaging.elements.CompositePackagingElement import com.intellij.packaging.elements.PackagingElement import com.intellij.packaging.elements.PackagingElementFactory import com.intellij.packaging.impl.artifacts.UnknownPackagingElementTypeException import com.intellij.packaging.impl.elements.* import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.storage.VersionedEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder import com.intellij.workspaceModel.storage.bridgeEntities.* import org.jetbrains.annotations.TestOnly import org.jetbrains.jps.util.JpsPathUtil import java.util.concurrent.TimeUnit import java.util.concurrent.locks.Condition import java.util.concurrent.locks.Lock import java.util.concurrent.locks.ReadWriteLock import java.util.concurrent.locks.ReentrantReadWriteLock private val rwLock: ReadWriteLock = if ( Registry.`is`("ide.new.project.model.artifacts.sync.initialization") ) ReentrantReadWriteLock() else EmptyReadWriteLock() internal fun CompositePackagingElementEntity.toCompositeElement( project: Project, storage: VersionedEntityStorage, addToMapping: Boolean = true, ): CompositePackagingElement<*> { rwLock.readLock().lock() var existing = try { testCheck(1) storage.current.elements.getDataByEntity(this) } catch (e: Exception) { rwLock.readLock().unlock() throw e } if (existing == null) { rwLock.readLock().unlock() rwLock.writeLock().lock() try { testCheck(2) // Double check existing = storage.current.elements.getDataByEntity(this) if (existing == null) { val element = when (this) { is DirectoryPackagingElementEntity -> { val element = DirectoryPackagingElement(this.directoryName) this.children.pushTo(element, project, storage) element } is ArchivePackagingElementEntity -> { val element = ArchivePackagingElement(this.fileName) this.children.pushTo(element, project, storage) element } is ArtifactRootElementEntity -> { val element = ArtifactRootElementImpl() this.children.pushTo(element, project, storage) element } is CustomPackagingElementEntity -> { val unpacked = unpackCustomElement(storage, project) if (unpacked !is CompositePackagingElement<*>) { error("Expected composite packaging element") } unpacked } else -> unknownElement() } if (addToMapping) { val storageBase = storage.base if (storageBase is WorkspaceEntityStorageBuilder) { val mutableMapping = storageBase.mutableElements mutableMapping.addMapping(this, element) } else { WorkspaceModel.getInstance(project).updateProjectModelSilent { val mutableMapping = it.mutableElements mutableMapping.addMapping(this, element) } } } existing = element } // Lock downgrade rwLock.readLock().lock() } finally { rwLock.writeLock().unlock() } } rwLock.readLock().unlock() return existing as CompositePackagingElement<*> } fun PackagingElementEntity.toElement(project: Project, storage: VersionedEntityStorage): PackagingElement<*> { rwLock.readLock().lock() var existing = try { testCheck(3) storage.current.elements.getDataByEntity(this) } catch (e: Exception) { rwLock.readLock().unlock() throw e } if (existing == null) { rwLock.readLock().unlock() rwLock.writeLock().lock() try { testCheck(4) // Double check existing = storage.current.elements.getDataByEntity(this) if (existing == null) { val element = when (this) { is ModuleOutputPackagingElementEntity -> { val module = this.module if (module != null) { val modulePointer = ModulePointerManager.getInstance(project).create(module.name) ProductionModuleOutputPackagingElement(project, modulePointer) } else { ProductionModuleOutputPackagingElement(project) } } is ModuleTestOutputPackagingElementEntity -> { val module = this.module if (module != null) { val modulePointer = ModulePointerManager.getInstance(project).create(module.name) TestModuleOutputPackagingElement(project, modulePointer) } else { TestModuleOutputPackagingElement(project) } } is ModuleSourcePackagingElementEntity -> { val module = this.module if (module != null) { val modulePointer = ModulePointerManager.getInstance(project).create(module.name) ProductionModuleSourcePackagingElement(project, modulePointer) } else { ProductionModuleSourcePackagingElement(project) } } is ArtifactOutputPackagingElementEntity -> { val artifact = this.artifact if (artifact != null) { val artifactPointer = ArtifactPointerManager.getInstance(project).createPointer(artifact.name) ArtifactPackagingElement(project, artifactPointer) } else { ArtifactPackagingElement(project) } } is ExtractedDirectoryPackagingElementEntity -> { val pathInArchive = this.pathInArchive val archive = this.filePath ExtractedDirectoryPackagingElement(JpsPathUtil.urlToPath(archive.url), pathInArchive) } is FileCopyPackagingElementEntity -> { val file = this.filePath val renamedOutputFileName = this.renamedOutputFileName if (renamedOutputFileName != null) { FileCopyPackagingElement(JpsPathUtil.urlToPath(file.url), renamedOutputFileName) } else { FileCopyPackagingElement(JpsPathUtil.urlToPath(file.url)) } } is DirectoryCopyPackagingElementEntity -> { val directory = this.filePath DirectoryCopyPackagingElement(JpsPathUtil.urlToPath(directory.url)) } is ArchivePackagingElementEntity -> this.toCompositeElement(project, storage, false) is DirectoryPackagingElementEntity -> this.toCompositeElement(project, storage, false) is ArtifactRootElementEntity -> this.toCompositeElement(project, storage, false) is LibraryFilesPackagingElementEntity -> { val mapping = storage.current.getExternalMapping<PackagingElement<*>>("intellij.artifacts.packaging.elements") val data = mapping.getDataByEntity(this) if (data != null) { return data } val library = this.library if (library != null) { val tableId = library.tableId val moduleName = if (tableId is LibraryTableId.ModuleLibraryTableId) tableId.moduleId.name else null LibraryPackagingElement(tableId.level, library.name, moduleName) } else { LibraryPackagingElement() } } is CustomPackagingElementEntity -> unpackCustomElement(storage, project) else -> unknownElement() } val storageBase = storage.base if (storageBase is WorkspaceEntityStorageBuilder) { val mutableMapping = storageBase.mutableElements mutableMapping.addIfAbsent(this, element) } else { WorkspaceModel.getInstance(project).updateProjectModelSilent { val mutableMapping = it.mutableElements mutableMapping.addIfAbsent(this, element) } } existing = element } // Lock downgrade rwLock.readLock().lock() } finally { rwLock.writeLock().unlock() } } rwLock.readLock().unlock() return existing as PackagingElement<*> } private fun CustomPackagingElementEntity.unpackCustomElement(storage: VersionedEntityStorage, project: Project): PackagingElement<*> { val mapping = storage.current.getExternalMapping<PackagingElement<*>>("intellij.artifacts.packaging.elements") val data = mapping.getDataByEntity(this) if (data != null) { return data } // TODO: 09.04.2021 It should be invalid artifact instead of error val elementType = PackagingElementFactory.getInstance().findElementType(this.typeId) ?: throw UnknownPackagingElementTypeException(this.typeId) @Suppress("UNCHECKED_CAST") val packagingElement = elementType.createEmpty(project) as PackagingElement<Any> val state = packagingElement.state if (state != null) { val element = JDOMUtil.load(this.propertiesXmlTag) element.deserializeInto(state) packagingElement.loadState(state) } if (packagingElement is CompositePackagingElement<*>) { this.children.pushTo(packagingElement, project, storage) } return packagingElement } private fun PackagingElementEntity.unknownElement(): Nothing { error("Unknown packaging element entity: $this") } private fun Sequence<PackagingElementEntity>.pushTo(element: CompositePackagingElement<*>, project: Project, storage: VersionedEntityStorage) { val children = this.map { it.toElement(project, storage) }.toList() children.reversed().forEach { element.addFirstChild(it) } } private class EmptyReadWriteLock : ReadWriteLock { override fun readLock(): Lock = EmptyLock override fun writeLock(): Lock = EmptyLock } private object EmptyLock : Lock { override fun lock() { // Nothing } override fun lockInterruptibly() { // Nothing } override fun tryLock(): Boolean { throw UnsupportedOperationException() } override fun tryLock(time: Long, unit: TimeUnit): Boolean { throw UnsupportedOperationException() } override fun unlock() { // Nothing } override fun newCondition(): Condition { throw UnsupportedOperationException() } } // Instruments for testing code with unexpected exceptions // I assume that tests with bad approach is better than no tests at all @TestOnly object ArtifactsTestingState { var testLevel: Int = 0 var exceptionsThrows: MutableList<Int> = ArrayList() fun reset() { testLevel = 0 exceptionsThrows = ArrayList() } } @Suppress("TestOnlyProblems") private fun testCheck(level: Int) { if (level == ArtifactsTestingState.testLevel) { ArtifactsTestingState.exceptionsThrows += level error("Exception on level: $level") } }
apache-2.0
7b99bb537439b4ba78a79a0b0b05a935
34.613003
140
0.663218
5.30826
false
true
false
false
smmribeiro/intellij-community
plugins/filePrediction/test/com/intellij/filePrediction/predictor/FilePredictionFeaturesBuilder.kt
12
4099
package com.intellij.filePrediction.predictor import com.intellij.filePrediction.features.FilePredictionFeature import com.intellij.filePrediction.features.history.FileHistoryFeatures import com.intellij.filePrediction.features.history.NextFileProbability @Suppress("unused") internal class FilePredictionFeaturesBuilder { private val features: HashMap<String, FilePredictionFeature> = hashMapOf() fun withCustomFeature(name: String, value: Any): FilePredictionFeaturesBuilder { features[name] = newFeature(value) return this } private fun newFeature(value: Any): FilePredictionFeature { return when (value) { is Boolean -> FilePredictionFeature.binary(value) is Double -> FilePredictionFeature.numerical(value) is Int -> FilePredictionFeature.numerical(value) is String -> FilePredictionFeature.fileType(value) else -> FilePredictionFeature.fileType(value.toString()) } } fun withVcs(inChangeList: Boolean): FilePredictionFeaturesBuilder { features["vcs_in_changelist"] = FilePredictionFeature.binary(inChangeList) return this } fun withInRef(inRef: Boolean): FilePredictionFeaturesBuilder { features["in_ref"] = FilePredictionFeature.binary(inRef) return this } fun withPositionFeatures(sameModule: Boolean, sameDirectory: Boolean): FilePredictionFeaturesBuilder { features["same_module"] = FilePredictionFeature.binary(sameModule) features["same_dir"] = FilePredictionFeature.binary(sameDirectory) return this } fun withStructureFeatures(excluded: Boolean, inProject: Boolean, inLibrary: Boolean, inSource: Boolean): FilePredictionFeaturesBuilder { features["excluded"] = FilePredictionFeature.binary(excluded) features["in_project"] = FilePredictionFeature.binary(inProject) features["in_library"] = FilePredictionFeature.binary(inLibrary) features["in_source"] = FilePredictionFeature.binary(inSource) return this } fun withNameFeatures(pathPrefix: Int, namePrefix: Int, relativePathPrefix: Int): FilePredictionFeaturesBuilder { features["path_prefix"] = FilePredictionFeature.numerical(pathPrefix) features["name_prefix"] = FilePredictionFeature.numerical(namePrefix) features["relative_path_prefix"] = FilePredictionFeature.numerical(relativePathPrefix) return this } fun withFileType(type: String): FilePredictionFeaturesBuilder { features["file_type"] = FilePredictionFeature.fileType(type) return this } fun withPrevFileType(type: String): FilePredictionFeaturesBuilder { features["prev_file_type"] = FilePredictionFeature.fileType(type) return this } fun withHistorySize(size: Int): FilePredictionFeaturesBuilder { features["history_size"] = FilePredictionFeature.numerical(size) return this } fun withHistoryPosition(position: Int?): FilePredictionFeaturesBuilder { if (position != null) { features["history_position"] = FilePredictionFeature.numerical(position) } return this } fun withUniGram(uni: NextFileProbability): FilePredictionFeaturesBuilder { addNGramFeatures(uni, "uni", features) return this } fun withHistory(history: FileHistoryFeatures): FilePredictionFeaturesBuilder { withHistoryPosition(history.position) addNGramFeatures(history.uniGram, "uni", features) addNGramFeatures(history.biGram, "bi", features) return this } private fun addNGramFeatures(probability: NextFileProbability, prefix: String, result: HashMap<String, FilePredictionFeature>) { result["history_" + prefix + "_mle"] = FilePredictionFeature.numerical(probability.mle) result["history_" + prefix + "_min"] = FilePredictionFeature.numerical(probability.minMle) result["history_" + prefix + "_max"] = FilePredictionFeature.numerical(probability.maxMle) result["history_" + prefix + "_mle_to_min"] = FilePredictionFeature.numerical(probability.mleToMin) result["history_" + prefix + "_mle_to_max"] = FilePredictionFeature.numerical(probability.mleToMax) } fun build(): Map<String, FilePredictionFeature> { return features } }
apache-2.0
ff591084ee637a7d4fa5a28e870cfba9
39.196078
138
0.759941
4.569677
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/firstStep/BuildSystemTypeSettingComponent.kt
1
5825
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.firstStep import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionButtonLook import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.ActionButtonWithText import com.intellij.openapi.project.DumbAware import icons.OpenapiIcons import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.extensions.gradle.KotlinGradleFacade import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.entity.ValidationResult import org.jetbrains.kotlin.tools.projectWizard.core.entity.isSpecificError import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.DropDownSettingType import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType import org.jetbrains.kotlin.tools.projectWizard.wizard.OnUserSettingChangeStatisticsLogger import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.TitleComponentAlignment import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.IdeaBasedComponentValidator import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.SettingComponent import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.ValidationIndicator import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.awt.Dimension import java.awt.Insets import javax.swing.JComponent class BuildSystemTypeSettingComponent( context: Context ) : SettingComponent<BuildSystemType, DropDownSettingType<BuildSystemType>>( BuildSystemPlugin.type.reference, context ) { private val toolbar by lazy(LazyThreadSafetyMode.NONE) { val buildSystemTypes = read { setting.type.values.filter { setting.type.filter(this, reference, it) } } val actionGroup = DefaultActionGroup(buildSystemTypes.map(::BuildSystemTypeAction)) val buildSystemToolbar = BuildSystemToolbar(ActionPlaces.NEW_PROJECT_WIZARD, actionGroup, true) buildSystemToolbar.also { it.targetComponent = null } } override val alignment: TitleComponentAlignment get() = TitleComponentAlignment.AlignFormTopWithPadding(6) override val component: JComponent by lazy(LazyThreadSafetyMode.NONE) { toolbar } override val validationIndicator: ValidationIndicator = IdeaBasedComponentValidator(this, component) override fun navigateTo(error: ValidationResult.ValidationError) { if (validationIndicator.validationState.isSpecificError(error)) { component.requestFocus() } } private fun validateBuildSystem(buildSystem: BuildSystemType) = read { setting.validator.validate(this, buildSystem) } private inner class BuildSystemTypeAction( val buildSystemType: BuildSystemType ) : ToggleAction(buildSystemType.text, null, buildSystemType.icon), DumbAware { override fun isSelected(e: AnActionEvent): Boolean = value == buildSystemType override fun setSelected(e: AnActionEvent, state: Boolean) { if (state) { value = buildSystemType OnUserSettingChangeStatisticsLogger.logSettingValueChangedByUser( context.contextComponents.get(), BuildSystemPlugin.type.path, buildSystemType ) } } override fun update(e: AnActionEvent) { super.update(e) val validationResult = validateBuildSystem(buildSystemType) e.presentation.isEnabled = validationResult.isOk e.presentation.description = validationResult.safeAs<ValidationResult.ValidationError>()?.messages?.firstOrNull() } } private inner class BuildSystemToolbar( place: String, actionGroup: ActionGroup, horizontal: Boolean ) : ActionToolbarImplWrapper(place, actionGroup, horizontal) { init { layoutPolicy = ActionToolbar.WRAP_LAYOUT_POLICY } override fun createToolbarButton( action: AnAction, look: ActionButtonLook?, place: String, presentation: Presentation, minimumSize: Dimension ): ActionButton = BuildSystemChooseButton(action as BuildSystemTypeAction, presentation, place, minimumSize) } private inner class BuildSystemChooseButton( action: BuildSystemTypeAction, presentation: Presentation, place: String?, minimumSize: Dimension ) : ActionButtonWithText(action, presentation, place, minimumSize) { override fun getInsets(): Insets = super.getInsets().apply { right += left left = 0 } override fun getPreferredSize(): Dimension { val old = super.getPreferredSize() return Dimension(old.width + LEFT_RIGHT_PADDING * 2, old.height + TOP_BOTTOM_PADDING * 2) } } companion object { private const val LEFT_RIGHT_PADDING = 6 private const val TOP_BOTTOM_PADDING = 2 } } private val BuildSystemType.icon get() = when (this) { BuildSystemType.GradleKotlinDsl -> KotlinIcons.GRADLE_SCRIPT BuildSystemType.GradleGroovyDsl -> KotlinGradleFacade.instance?.gradleIcon ?: KotlinIcons.GRADLE_SCRIPT BuildSystemType.Maven -> OpenapiIcons.RepositoryLibraryLogo BuildSystemType.Jps -> AllIcons.Nodes.Module }
apache-2.0
4964f0ef3cd2b5d1ad0cc12785f90e56
41.830882
158
0.732189
5.14576
false
false
false
false
Phakx/AdventOfCode
2017/src/main/kotlin/daythirteen/Daythirteen.kt
1
3725
package main.kotlin.daythirteen import java.io.File import java.net.URLDecoder class Daythirteen { private fun load_file(): String? { val resource = this::class.java.classLoader.getResource("daythirteen" + File.separator + "input") return URLDecoder.decode(resource.file, "UTF-8") } fun solvePartOne() { val input = File(load_file()).readLines() var cursorPosition = -1 var severity = 0 val caught = mutableListOf<Int>() val firewallMap = generateFirewallMap(input) firewallMap.forEach({ _, _ -> if (cursorPosition == firewallMap.keys.max()) { return@forEach } cursorPosition += 1 if (firewallMap[cursorPosition]!!.second == 0 && firewallMap[cursorPosition]!!.first != 0) { caught += cursorPosition } firewallMap.map { val second: Int = if (it.value.second >= it.value.first - 1) { -it.value.second + 1 } else { it.value.second + 1 } firewallMap[it.key] = Pair(it.value.first, second) } }) caught.forEach { val depth = firewallMap[it]!!.first severity += it * depth } println("Part 1: $severity") } private fun generateFirewallMap(input: List<String>): MutableMap<Int, Pair<Int, Int>> { val returnMap = mutableMapOf<Int, Pair<Int, Int>>() input.forEach { val map = it.split(":").map { it.trim() }.map { it.toInt() } returnMap[map[0]] = Pair(map[1], 0) } (0..returnMap.keys.max()!!).forEach { if (returnMap[it] == null) { returnMap[it] = Pair(0, 0) } } return returnMap } fun solvePartTwo() { val input = File(load_file()).readLines() var neededDelay = 0 val caught = mutableListOf<Int>() caught.add(1) var firewallSnapshot = generateFirewallMap(input) while (true) { neededDelay += 1 caught.removeAll { true } var cursorPosition = -1 val firewallMap = firewallSnapshot.toMutableMap() firewallMap.map { val second: Int = if (it.value.second >= it.value.first - 1) { -it.value.second + 1 } else { it.value.second + 1 } firewallMap[it.key] = Pair(it.value.first, second) } firewallSnapshot = firewallMap.toMutableMap() firewallMap.forEach({ if (cursorPosition == firewallMap.keys.max()) { return@forEach } cursorPosition += 1 if (firewallMap[cursorPosition]!!.second == 0 && firewallMap[cursorPosition]!!.first != 0) { caught += cursorPosition } firewallMap.map { val second: Int = if (it.value.second >= it.value.first - 1) { -it.value.second + 1 } else { it.value.second + 1 } firewallMap[it.key] = Pair(it.value.first, second) } }) println("Current Delay: $neededDelay Current Caught Count: ${caught.size}") if (caught.isEmpty()) { break } } println("Part 2: $neededDelay") } } fun main(args: Array<String>) { val solver = Daythirteen() solver.solvePartOne() solver.solvePartTwo() }
mit
6dc0431c725e1bd1f69c865401505fca
31.4
108
0.491544
4.450418
false
false
false
false
ppamorim/ThreadExecutor
threadexecutor/src/main/kotlin/com/github/ppamorim/threadexecutor/ThreadExecutor.kt
1
3133
/* * Copyright (C) 2017 Pedro Paulo de Amorim * * 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.ppamorim.threadexecutor import java.util.* import java.util.concurrent.* import java.util.concurrent.atomic.AtomicInteger import javax.inject.Inject const val DEFAULT_KEEP_ALIVE_TIME = 30L /** * This class will create the instance of * BlockingQueue to be used with ThreadPool. * The thread pool has some limitations and * automatically will release any thread of * the memory. * Some configurations can be used to change * some variables of ThreadPool. Use the method * .build to finished every configuration. */ class ThreadExecutor @Inject constructor(): InteractorExecutor { val CPU_COUNT = Runtime.getRuntime().availableProcessors() var corePoolSize: Int = Math.max(2, Math.min(CPU_COUNT - 1, 4)) var maxPoolSize: Int = CPU_COUNT * 2 + 1 var keepAliveTime: Long = DEFAULT_KEEP_ALIVE_TIME var timeUnit: TimeUnit = TimeUnit.SECONDS private val workQueue by lazy { LinkedBlockingQueue<Runnable>(128) } private val threadPoolExecutor by lazy { val threadPoolExecutor = ThreadPoolExecutor( corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue, threadFactory, rejectedExecutionHandler) threadPoolExecutor.allowCoreThreadTimeOut(true) threadPoolExecutor } private val serialExecutor by lazy { SerialExecutor(threadPoolExecutor) } private val threadFactory = object: ThreadFactory { private val count = AtomicInteger(1) override fun newThread(r: Runnable): Thread { return Thread(r, "AsyncTask #${count.getAndIncrement()}") } } private val rejectedExecutionHandler: RejectedExecutionHandler = RejectedExecutionHandler { _, _ -> threadPoolExecutor.shutdown() } override fun run(serial: Boolean, interactor: Interactor) { if (serial) { serialExecutor.execute { interactor.run() } } else { threadPoolExecutor.submit { interactor.run() } } } } class SerialExecutor(val threadPoolExecutor: ThreadPoolExecutor): Executor { private val tasks = ArrayDeque<Runnable>() private var active: Runnable? = null override fun execute(runnable: Runnable?) { synchronized(this) { tasks.offer(Runnable { try { runnable?.run() } finally { scheduleNext() } }) if (active == null) { scheduleNext() } } } fun scheduleNext() { synchronized(this) { active = tasks.poll() active?.let { threadPoolExecutor.submit(it) } } } }
apache-2.0
d7a88ebc93b244ee966f7e1614616687
26.491228
76
0.694861
4.514409
false
false
false
false
ThiagoGarciaAlves/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInspection/Java9NonAccessibleTypeExposedTest.kt
1
14493
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.java.codeInspection import com.intellij.java.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor.M2 import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor.MAIN import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl import com.siyeh.ig.visibility.ClassEscapesItsScopeInspection import org.intellij.lang.annotations.Language import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.NotNull /** * @author Pavel.Dolgov */ class Java9NonAccessibleTypeExposedTest : LightJava9ModulesCodeInsightFixtureTestCase() { override fun setUp() { super.setUp() myFixture.enableInspections(ClassEscapesItsScopeInspection()) (myFixture as CodeInsightTestFixtureImpl).setVirtualFileFilter({ it.name != "module-info.java"}) addFile("module-info.java", "module MAIN { exports apiPkg; exports otherPkg; requires M2; }", MAIN) addFile("module-info.java", "module M2 { exports m2Pkg; }", M2) add("apiPkg", "PublicApi", "public class PublicApi {}") add("apiPkg", "PackageLocal", "class PackageLocal {}") add("otherPkg", "PublicOther", "public class PublicOther {}") } fun testPrimitives() { highlight("""package apiPkg; public class Highlighted { public int i; public int getInt() {return i;} public void setInt(int n) {i=n;} protected Long l; protected Long getLong() {return l;} protected void setLong(Long n) {l=n;} public void run() {} }""") } fun testExported() { addFile("m2Pkg/Exported.java", "package m2Pkg; public class Exported {}", M2) highlight("""package apiPkg; import m2Pkg.Exported; public class Highlighted { static { Exported tmp = new Exported(); System.out.println(tmp);} public Exported myVar; protected Highlighted() {} public Highlighted(Exported var) { Exported tmp = new Exported(); myVar = var!= null ? var : tmp; } public Exported getVar() {return myVar;} protected void setVar(Exported var) {myVar = var;} }""") } fun testPackageLocalExposed() { highlight("""package apiPkg; public class Highlighted { static { PackageLocal tmp = new PackageLocal(); System.out.println(tmp);} public <warning descr="Class 'PackageLocal' is not exported from module 'MAIN'">PackageLocal</warning> myVar; protected Highlighted() {} public Highlighted(<warning descr="Class 'PackageLocal' is not exported from module 'MAIN'">PackageLocal</warning> var) { PackageLocal tmp = new PackageLocal(); myVar = var!= null ? var : tmp; } public <warning descr="Class 'PackageLocal' is not exported from module 'MAIN'">PackageLocal</warning> getVar() {return myVar;} protected void setVar(<warning descr="Class 'PackageLocal' is not exported from module 'MAIN'">PackageLocal</warning> var) {myVar = var;} } """) } fun testPackageLocalEncapsulated() { highlight("""package apiPkg; public class Highlighted { static { PackageLocal tmp = new PackageLocal(); System.out.println(tmp);} private PackageLocal myVar; private Highlighted() {} Highlighted(PackageLocal var) { PackageLocal tmp = new PackageLocal(); myVar = var!= null ? var : tmp; } PackageLocal getVar() {return myVar;} private void setVar(PackageLocal var) {myVar = var;} } """) } fun testPackageLocalEncapsulated2() { highlight("""package apiPkg; public class Highlighted { Highlighted(PackageLocal var) { } } """) } fun testPackageLocalUsedLocally() { highlight("""package apiPkg; class Highlighted { static { PackageLocal tmp = new PackageLocal(); System.out.println(tmp);} public PackageLocal myVar; protected Highlighted() {} public Highlighted(PackageLocal var) { PackageLocal tmp = new PackageLocal(); myVar = var!= null ? var : tmp; } public PackageLocal getVar() {return myVar;} protected void setVar(PackageLocal var) {myVar = var;} } """) } fun testPublicApi() { highlight("""package apiPkg; public class Highlighted { static { PublicApi tmp = new PublicApi(); System.out.println(tmp);} public PublicApi myVar; protected Highlighted() {} public Highlighted(PublicApi var) { PublicApi tmp = new PublicApi(); myVar = var!= null ? var : tmp; } public PublicApi getVar() {return myVar;} protected void setVar(PublicApi var) {myVar = var;} } """) } fun testPublicOther() { highlight("""package apiPkg; import otherPkg.PublicOther; public class Highlighted { static { PublicOther tmp = new PublicOther(); System.out.println(tmp);} public PublicOther myVar; protected Highlighted() {} public Highlighted(PublicOther var) { PublicOther tmp = new PublicOther(); myVar = var!= null ? var : tmp; } public PublicOther getVar() {return myVar;} protected void setVar(PublicOther var) {myVar = var;} } """) } fun testPublicNested() { highlight("""package apiPkg; public class Highlighted { public class PublicNested {} { PublicNested tmp = new PublicNested(); System.out.println(tmp);} public PublicNested myVar; protected Highlighted() {} public Highlighted(PublicNested var) { PublicNested tmp = new PublicNested(); myVar = var!= null ? var : tmp; } public PublicNested getVar() {return myVar;} protected void setVar(PublicNested var) {myVar = var;} } """) } fun testPackageLocalNested() { highlight("""package apiPkg; public class Highlighted { class PackageLocalNested {} { PackageLocalNested tmp = new PackageLocalNested(); System.out.println(tmp);} public <warning descr="Class 'PackageLocalNested' is not exported from module 'MAIN'">PackageLocalNested</warning> myVar; protected Highlighted() {} public Highlighted(<warning descr="Class 'PackageLocalNested' is not exported from module 'MAIN'">PackageLocalNested</warning> var) { PackageLocalNested tmp = new PackageLocalNested(); myVar = var!= null ? var : tmp; } public <warning descr="Class 'PackageLocalNested' is not exported from module 'MAIN'">PackageLocalNested</warning> getVar() {return myVar;} protected void setVar(<warning descr="Class 'PackageLocalNested' is not exported from module 'MAIN'">PackageLocalNested</warning> var) {myVar = var;} } """) } fun testPackageLocalInInterface() { highlight("""package apiPkg; public interface Highlighted { <warning descr="Class 'PackageLocal' is not exported from module 'MAIN'">PackageLocal</warning> myVar = new PackageLocal(); <warning descr="Class 'PackageLocal' is not exported from module 'MAIN'">PackageLocal</warning> getVar(); void setVar(<warning descr="Class 'PackageLocal' is not exported from module 'MAIN'">PackageLocal</warning> var); } """) } fun testPublicInInterface() { highlight("""package apiPkg; public interface Highlighted { PublicApi myVar = new PublicApi(); PublicApi getVar(); void setVar(PublicApi var); } """) } fun testNotExportedPackage() { add("implPkg", "NotExported", "public class NotExported {}") highlight("""package apiPkg; import implPkg.NotExported; public class Highlighted { public <warning descr="Class 'NotExported' is not exported from module 'MAIN'">NotExported</warning> myVar; protected Highlighted() {} public Highlighted(<warning descr="Class 'NotExported' is not exported from module 'MAIN'">NotExported</warning> var) {setVar(var);} public <warning descr="Class 'NotExported' is not exported from module 'MAIN'">NotExported</warning> getVar() {return myVar;} protected void setVar(<warning descr="Class 'NotExported' is not exported from module 'MAIN'">NotExported</warning> var) {myVar = var;} } """) } fun testDoubleNested() { add("apiPkg", "PublicOuter", """public class PublicOuter { static class PackageLocal { public class DoubleNested {} } }""") highlight("""package apiPkg; import apiPkg.PublicOuter.PackageLocal; public class Highlighted { private PackageLocal.DoubleNested myVar; public <warning descr="Class 'PackageLocal.DoubleNested' is not exported from module 'MAIN'">PackageLocal.DoubleNested</warning> getVar() {return myVar;} protected void setVar(<warning descr="Class 'PackageLocal.DoubleNested' is not exported from module 'MAIN'">PackageLocal.DoubleNested</warning> var) {myVar = var;} } """) } fun testExportedArray() { addFile("m2Pkg/Exported.java", "package m2Pkg; public class Exported {}", M2) highlight("""package apiPkg; import m2Pkg.Exported; import java.util.*; public class Highlighted { public Exported[] myVar; protected Highlighted(List<Exported[]> list) {Iterator<Exported[]> it = list.iterator(); myVar = it.next();} public Highlighted(Exported[] var) {myVar = var;} public Exported[] getVar() {return myVar;} protected void setVar(Exported[][] var) {myVar = var[0];} }""") } fun testNotExportedArray() { add("implPkg", "NotExported", "public class NotExported {}") highlight("""package apiPkg; import implPkg.NotExported; import java.util.*; public class Highlighted { public <warning descr="Class 'NotExported' is not exported from module 'MAIN'">NotExported</warning>[] myVar; protected Highlighted(List<<warning descr="Class 'NotExported' is not exported from module 'MAIN'">NotExported</warning>[]> list) {Iterator<NotExported[]> it = list.iterator(); myVar = it.next();} public Highlighted(<warning descr="Class 'NotExported' is not exported from module 'MAIN'">NotExported</warning>[] var) {myVar = var;} public <warning descr="Class 'NotExported' is not exported from module 'MAIN'">NotExported</warning>[] getVar() {return myVar;} protected void setVar(<warning descr="Class 'NotExported' is not exported from module 'MAIN'">NotExported</warning>[][] var) {myVar = var[0];} }""") } fun testThrows() { add("apiPkg", "PublicException", "public class PublicException extends Exception {}") add("apiPkg", "PackageLocalException", "class PackageLocalException extends Exception {}") add("otherPkg", "OtherException", "public class OtherException extends Exception {}") add("implPkg", "NotExportedException", "public class NotExportedException extends Exception {}") highlight("""package apiPkg; import otherPkg.*; import implPkg.*; public class Highlighted { public void throwsPublic() throws PublicException {} public void throwsPackageLocal() throws <warning descr="Class 'PackageLocalException' is not exported from module 'MAIN'">PackageLocalException</warning> {} public void throwsOther() throws OtherException {} public void throwsNotExported() throws <warning descr="Class 'NotExportedException' is not exported from module 'MAIN'">NotExportedException</warning> {} } """) } fun testGenericPublic() { add("apiPkg", "MyInterface", "public interface MyInterface {}") add("apiPkg", "MyClass", "public class MyClass implements MyInterface {}") highlight("""package apiPkg; import java.util.*; public class Highlighted<T extends MyInterface> { protected Set<T> get1() { return new HashSet<>();} public Set<MyClass> get2() { return new HashSet<MyClass>();} protected Set<? extends MyClass> get3() { return new HashSet<>();} public <X extends Object&MyInterface> Set<X> get4() { return new HashSet<>();} public Map<String, Set<MyInterface>> get5() {return new HashMap<>();} public void copy1(Set<MyInterface> s) {} public void copy2(Set<? super MyClass> s) {} public static class Nested1<T extends MyClass&Iterable<MyInterface>> { public Iterator<MyInterface> iterator() {return null;} } public static class Nested2<T extends MyInterface&AutoCloseable> { public void close(){} } public interface Nested3<X extends Iterable<MyInterface>> {} public interface Nested4<X extends Iterable<? extends MyInterface>> {} } """) } fun testGenericNotExported() { add("implPkg", "MyInterface", "public interface MyInterface {}") add("implPkg", "MyClass", "public class MyClass implements MyInterface {}") highlight("""package apiPkg; import java.util.*; import implPkg.*; public class Highlighted<T extends MyInterface> { protected Set<T> get1() { return new HashSet<>();} public Set<<warning descr="Class 'MyClass' is not exported from module 'MAIN'">MyClass</warning>> get2() { return new HashSet<MyClass>();} protected Set<? extends <warning descr="Class 'MyClass' is not exported from module 'MAIN'">MyClass</warning>> get3() { return new HashSet<>();} public <X extends Object&<warning descr="Class 'MyInterface' is not exported from module 'MAIN'">MyInterface</warning>> Set<X> get4() { return new HashSet<>();} public Map<String, Set<<warning descr="Class 'MyInterface' is not exported from module 'MAIN'">MyInterface</warning>>> get5() {return new HashMap<>();} public void copy1(Set<<warning descr="Class 'MyInterface' is not exported from module 'MAIN'">MyInterface</warning>> s) {} public void copy2(Set<? super <warning descr="Class 'MyClass' is not exported from module 'MAIN'">MyClass</warning>> s) {} public static class Nested1<T extends MyClass& Iterable<MyInterface>> { public Iterator<<warning descr="Class 'MyInterface' is not exported from module 'MAIN'">MyInterface</warning>> iterator() {return null;} } public static class Nested2<T extends MyInterface&AutoCloseable> { public void close() {} } public interface Nested3<X extends Iterable<MyInterface>> {} public interface Nested4<X extends Iterable<? extends MyInterface>> {} } """) } private fun highlight(@Language("JAVA") @NotNull @NonNls text: String) { val file = addFile("apiPkg/Highlighted.java", text, MAIN) myFixture.configureFromExistingVirtualFile(file) myFixture.checkHighlighting() } private fun add(packageName: String, className: String, @Language("JAVA") @NotNull @NonNls text: String) { addFile("$packageName/$className.java", "package $packageName; $text", MAIN) } }
apache-2.0
f92c031d15da021ae44eecb239ca2496
40.527221
198
0.722694
4.478677
false
true
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/ui/repo/webdav/WebdavRepoActivity.kt
1
9255
package com.orgzly.android.ui.repo.webdav import android.app.Activity import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.view.WindowManager import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.orgzly.R import com.orgzly.android.App import com.orgzly.android.repos.RepoFactory import com.orgzly.android.repos.RepoType import com.orgzly.android.repos.WebdavRepo.Companion.CERTIFICATES_PREF_KEY import com.orgzly.android.repos.WebdavRepo.Companion.PASSWORD_PREF_KEY import com.orgzly.android.repos.WebdavRepo.Companion.USERNAME_PREF_KEY import com.orgzly.android.ui.CommonActivity import com.orgzly.android.ui.showSnackbar import com.orgzly.android.ui.util.KeyboardUtils import com.orgzly.android.util.UriUtils import com.orgzly.databinding.ActivityRepoWebdavBinding import com.orgzly.databinding.DialogCertificatesBinding import javax.inject.Inject class WebdavRepoActivity : CommonActivity() { private lateinit var binding: ActivityRepoWebdavBinding @Inject lateinit var repoFactory: RepoFactory private lateinit var viewModel: WebdavRepoViewModel override fun onCreate(savedInstanceState: Bundle?) { App.appComponent.inject(this) super.onCreate(savedInstanceState) binding = ActivityRepoWebdavBinding.inflate(layoutInflater) setContentView(binding.root) binding.activityRepoWebdavCertificates.setOnClickListener { editCertificates() } binding.activityRepoWebdavTestButton.setOnClickListener { testConnection() } val repoId = intent.getLongExtra(ARG_REPO_ID, 0) val factory = WebdavRepoViewModelFactory.getInstance(dataRepository, repoId) viewModel = ViewModelProvider(this, factory).get(WebdavRepoViewModel::class.java) viewModel.finishEvent.observeSingle(this, Observer { finish() }) viewModel.alreadyExistsEvent.observeSingle(this, Observer { showSnackbar(R.string.repository_url_already_exists) }) viewModel.errorEvent.observeSingle(this, Observer { error -> if (error != null) { showSnackbar((error.cause ?: error).localizedMessage) } }) viewModel.connectionTestStatus.observe(this, Observer { binding.activityRepoWebdavTestResult.text = when (it) { is WebdavRepoViewModel.ConnectionResult.InProgress -> { binding.activityRepoWebdavTestButton.isEnabled = false getString(it.msg) } is WebdavRepoViewModel.ConnectionResult.Success -> { binding.activityRepoWebdavTestButton.isEnabled = true val bookCountMsg = resources.getQuantityString( R.plurals.found_number_of_notebooks, it.bookCount, it.bookCount) "${getString(R.string.connection_successful)}\n$bookCountMsg" } is WebdavRepoViewModel.ConnectionResult.Error -> { binding.activityRepoWebdavTestButton.isEnabled = true when (it.msg) { is Int -> getString(it.msg) is String -> it.msg else -> null } } } }) viewModel.certificates.observe(this, Observer { str -> binding.activityRepoWebdavCertificates.text = getString(if (str.isNullOrEmpty()) { R.string.add_trusted_certificates_optional } else { R.string.edit_trusted_certificates }) }) if (viewModel.repoId != 0L) { // Editing existing viewModel.loadRepoProperties()?.let { repoWithProps -> binding.activityRepoWebdavUrl.setText(repoWithProps.repo.url) binding.activityRepoWebdavUsername.setText(repoWithProps.props[USERNAME_PREF_KEY]) binding.activityRepoWebdavPassword.setText(repoWithProps.props[PASSWORD_PREF_KEY]) viewModel.certificates.value = repoWithProps.props[CERTIFICATES_PREF_KEY] } } binding.topToolbar.run { setNavigationOnClickListener { finish() } } binding.fab.setOnClickListener { saveAndFinish() } } private fun saveAndFinish() { if (isInputValid()) { val uriString = getUrl() val username = getUsername() val password = getPassword() val certificates = getCertificates() val props = mutableMapOf( USERNAME_PREF_KEY to username, PASSWORD_PREF_KEY to password) if (certificates != null) { props[CERTIFICATES_PREF_KEY] = certificates } if (UriUtils.isUrlSecure(uriString)) { viewModel.saveRepo(RepoType.WEBDAV, uriString, props) } else { // Warn about clear-text traffic alertDialog = MaterialAlertDialogBuilder(this) .setTitle(R.string.cleartext_traffic) .setMessage(R.string.cleartext_traffic_message) .setPositiveButton(R.string.yes) { _, _ -> viewModel.saveRepo(RepoType.WEBDAV, uriString, props) } .setNegativeButton(R.string.cancel, null) .show() } } } private fun getUrl(): String { return binding.activityRepoWebdavUrl.text.toString().trim { it <= ' ' } } private fun getUsername(): String { return binding.activityRepoWebdavUsername.text.toString().trim { it <= ' ' } } private fun getPassword(): String { return binding.activityRepoWebdavPassword.text.toString().trim { it <= ' ' } } private fun getCertificates(): String? { return viewModel.certificates.value } private fun isInputValid(): Boolean { val url = getUrl() val username = getUsername() val password = getPassword() binding.activityRepoWebdavUrlLayout.error = when { TextUtils.isEmpty(url) -> getString(R.string.can_not_be_empty) !WEB_DAV_SCHEME_REGEX.matches(url) -> getString(R.string.invalid_url) UriUtils.containsUser(url) -> getString(R.string.credentials_in_url_not_supported) else -> null } binding.activityRepoWebdavUsernameLayout.error = when { TextUtils.isEmpty(username) -> getString(R.string.can_not_be_empty) else -> null } binding.activityRepoWebdavPasswordLayout.error = when { TextUtils.isEmpty(password) -> getString(R.string.can_not_be_empty) else -> null } return binding.activityRepoWebdavUrlLayout.error == null && binding.activityRepoWebdavUsernameLayout.error == null && binding.activityRepoWebdavPasswordLayout.error == null } private fun editCertificates() { val dialogBinding = DialogCertificatesBinding.inflate(layoutInflater).apply { certificates.setText(viewModel.certificates.value) } alertDialog = MaterialAlertDialogBuilder(this) .setTitle(getString(R.string.trusted_certificates)) .setPositiveButton(R.string.set) { _, _ -> viewModel.certificates.value = dialogBinding.certificates.text.toString() } .setNeutralButton(R.string.clear) { _, _ -> viewModel.certificates.value = null } .setNegativeButton(R.string.cancel) { _, _ -> // Cancel } .setView(dialogBinding.root) .show() .apply { window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) } } private fun testConnection() { KeyboardUtils.closeSoftKeyboard(this) if (!isInputValid()) { return } val uriString = getUrl() val username = getUsername() val password = getPassword() val certificates = getCertificates() viewModel.testConnection(uriString, username, password, certificates) } companion object { private const val ARG_REPO_ID = "repo_id" private val WEB_DAV_SCHEME_REGEX = Regex("^(webdav|dav|http)s?://.+\$") @JvmStatic @JvmOverloads fun start(activity: Activity, repoId: Long = 0) { val intent = Intent(Intent.ACTION_VIEW) .setClass(activity, WebdavRepoActivity::class.java) .putExtra(ARG_REPO_ID, repoId) activity.startActivity(intent) } } }
gpl-3.0
1dcc2caab366e5065f813b8a8f3d42f5
34.872093
100
0.597839
4.989218
false
false
false
false
Litote/kmongo
kmongo-flapdoodle/src/main/kotlin/org/litote/kmongo/KFlapdoodleRule.kt
1
3417
/* * Copyright (C) 2016/2022 Litote * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.litote.kmongo import com.mongodb.client.MongoClient import com.mongodb.client.MongoCollection import com.mongodb.client.MongoDatabase import de.flapdoodle.embed.mongo.distribution.IFeatureAwareVersion import org.bson.types.ObjectId import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement import org.litote.kmongo.util.KMongoUtil import java.util.concurrent.ConcurrentHashMap import kotlin.reflect.KClass /** * A [org.junit.Rule] to help writing tests for KMongo using [Flapdoodle](http://flapdoodle-oss.github.io/de.flapdoodle.embed.mongo/). */ class KFlapdoodleRule<T : Any>( val defaultDocumentClass: KClass<T>, val generateRandomCollectionName: Boolean = false, val dbName: String = "test", val version: IFeatureAwareVersion = defaultMongoTestVersion ) : TestRule { companion object { inline fun <reified T : Any> rule(generateRandomCollectionName: Boolean = false): KFlapdoodleRule<T> = KFlapdoodleRule(T::class, generateRandomCollectionName) private val versionsMap = ConcurrentHashMap<IFeatureAwareVersion, KFlapdoodleConfiguration>() } private val configuration = versionsMap.getOrPut(version) { KFlapdoodleConfiguration(version)} val mongoClient: MongoClient by lazy { configuration.mongoClient } val database: MongoDatabase by lazy { configuration.getDatabase(dbName) } inline fun <reified T : Any> getCollection(): MongoCollection<T> = database.getCollection(KMongoUtil.defaultCollectionName(T::class), T::class.java) fun <T : Any> getCollection(clazz: KClass<T>): MongoCollection<T> = getCollection(KMongoUtil.defaultCollectionName(clazz), clazz) fun <T : Any> getCollection(name: String, clazz: KClass<T>): MongoCollection<T> = database.getCollection(name, clazz.java) inline fun <reified T : Any> dropCollection() = dropCollection(KMongoUtil.defaultCollectionName(T::class)) fun dropCollection(clazz: KClass<*>) = dropCollection(KMongoUtil.defaultCollectionName(clazz)) fun dropCollection(collectionName: String) { database.getCollection(collectionName).drop() } val col: MongoCollection<T> by lazy { val name = if (generateRandomCollectionName) { ObjectId().toString() } else { KMongoUtil.defaultCollectionName(defaultDocumentClass) } getCollection(name, defaultDocumentClass) } override fun apply(base: Statement, description: Description): Statement { return object : Statement() { override fun evaluate() { try { base.evaluate() } finally { col.drop() } } } } }
apache-2.0
6ed996876d03244d5d26dcdcda67f6b6
33.18
134
0.702078
4.507916
false
true
false
false
hwki/SimpleBitcoinWidget
bitcoin/src/main/java/com/brentpanther/bitcoinwidget/receiver/WidgetBroadcastReceiver.kt
1
2435
package com.brentpanther.bitcoinwidget.receiver import android.appwidget.AppWidgetManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.widget.Toast import com.brentpanther.bitcoinwidget.NetworkStatusHelper import com.brentpanther.bitcoinwidget.WidgetApplication import com.brentpanther.bitcoinwidget.WidgetUpdater import com.brentpanther.bitcoinwidget.db.WidgetDatabase import com.brentpanther.bitcoinwidget.strategy.presenter.RemoteWidgetPresenter import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class WidgetBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { when (intent.action) { Intent.ACTION_CONFIGURATION_CHANGED -> refreshAllWidgets(context) "message" -> postMessage(context, intent.getIntExtra("message", 0)) "refresh" -> refreshWidget(context, intent) } } private fun refreshAllWidgets(context: Context) = CoroutineScope(Dispatchers.IO).launch { for (widgetProvider in WidgetApplication.instance.widgetProviders) { val widgetUpdateIntent = Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, context, widgetProvider) widgetUpdateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, WidgetApplication.instance.getWidgetIds(widgetProvider)) context.sendBroadcast(widgetUpdateIntent) } } private fun refreshWidget(context: Context, intent: Intent) { // check if anything is restricted us from getting an updated price val restriction = NetworkStatusHelper.getRestriction(context) if (restriction != 0) { Toast.makeText(context, restriction, Toast.LENGTH_LONG).show() return } CoroutineScope(Dispatchers.IO).launch { val widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 0) val dao = WidgetDatabase.getInstance(context).widgetDao() val widget = dao.getByWidgetId(widgetId) ?: return@launch RemoteWidgetPresenter(context, widget).loading(context, widgetId) WidgetUpdater.update(context, intArrayOf(widgetId), manual = true) } } private fun postMessage(context: Context, message: Int) = Toast.makeText(context, message, Toast.LENGTH_LONG).show() }
mit
42b1325fa6cb2f0b2abd223674e62928
44.962264
134
0.738398
4.755859
false
false
false
false
VerifAPS/verifaps-lib
symbex/src/main/kotlin/edu/kit/iti/formal/automation/smt/DefaultS2SFunctionTranslator.kt
1
5521
package edu.kit.iti.formal.automation.smt /*- * #%L * iec-symbex * %% * Copyright (C) 2017 Alexander Weigl * %% * This program isType free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program isType distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a clone of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import edu.kit.iti.formal.smt.SExpr import edu.kit.iti.formal.smt.SSymbol import edu.kit.iti.formal.smv.EnumType import edu.kit.iti.formal.smv.SMVType import edu.kit.iti.formal.smv.SMVTypes import edu.kit.iti.formal.smv.SMVWordType import edu.kit.iti.formal.smv.ast.SBinaryOperator import edu.kit.iti.formal.smv.ast.SFunction import edu.kit.iti.formal.smv.ast.SUnaryOperator import java.util.* /** * http://smtlib.cs.uiowa.edu/Logics/QF_BV.smt2 * * @author Alexander Weigl * @version 1 (15.10.17) */ class DefaultS2SFunctionTranslator : S2SFunctionTranslator { override fun translateOperator(operator: SBinaryOperator, typeLeft: SMVType?, rightType: SMVType?): SExpr { val defaultValue = "not-found-operator-${operator.symbol()}-$typeLeft-$rightType" val lookup = when (typeLeft) { is SMVWordType -> { val (signed) = typeLeft if (signed) bvsOperators else bvuOperators } is EnumType -> bvuOperators SMVTypes.INT -> arithOperators else -> logicalOperators } val value = lookup[operator] ?: defaultValue return SSymbol(value) } override fun translateOperator(operator: SUnaryOperator, type: SMVType?): SExpr { val bvneg = SSymbol("bvneg") val not = SSymbol("not") return when (operator) { SUnaryOperator.MINUS -> bvneg SUnaryOperator.NEGATE -> not } } override fun translateOperator(func: SFunction, args: List<SExpr>): SExpr = TODO("translation of various functions") companion object { internal var logicalOperators: MutableMap<SBinaryOperator, String> = HashMap() internal var bvuOperators: MutableMap<SBinaryOperator, String> = HashMap() internal var bvsOperators: MutableMap<SBinaryOperator, String> = HashMap() internal var arithOperators: MutableMap<SBinaryOperator, String> = HashMap() init { logicalOperators[SBinaryOperator.AND] = "and" logicalOperators[SBinaryOperator.OR] = "or" logicalOperators[SBinaryOperator.IMPL] = "impl" logicalOperators[SBinaryOperator.EQUAL] = "=" logicalOperators[SBinaryOperator.NOT_EQUAL] = "xor" logicalOperators[SBinaryOperator.XOR] = "xor" logicalOperators[SBinaryOperator.XNOR] = "=" bvsOperators[SBinaryOperator.MUL] = "bvmul" bvsOperators[SBinaryOperator.PLUS] = "bvadd" bvsOperators[SBinaryOperator.DIV] = "bvsdiv" bvsOperators[SBinaryOperator.XOR] = "bvxor" bvsOperators[SBinaryOperator.XNOR] = "bvxnor" bvsOperators[SBinaryOperator.EQUAL] = "=" bvsOperators[SBinaryOperator.MINUS] = "bvsub" bvsOperators[SBinaryOperator.MOD] = "bvsmod" bvsOperators[SBinaryOperator.GREATER_EQUAL] = "bvsge" bvsOperators[SBinaryOperator.GREATER_THAN] = "bvsgt" bvsOperators[SBinaryOperator.LESS_EQUAL] = "bvsle" bvsOperators[SBinaryOperator.LESS_THAN] = "bvslt" bvsOperators[SBinaryOperator.NOT_EQUAL] = "<>" bvuOperators[SBinaryOperator.NOT_EQUAL] = "<>" bvuOperators[SBinaryOperator.MUL] = "bvmul" bvuOperators[SBinaryOperator.PLUS] = "bvadd" bvuOperators[SBinaryOperator.DIV] = "bvudiv" bvuOperators[SBinaryOperator.XOR] = "bvxor" bvuOperators[SBinaryOperator.EQUAL] = "=" bvuOperators[SBinaryOperator.XNOR] = "bvxnor" bvuOperators[SBinaryOperator.MINUS] = "bvsub" bvuOperators[SBinaryOperator.MOD] = "bvurem" bvuOperators[SBinaryOperator.GREATER_EQUAL] = "bvuge" bvuOperators[SBinaryOperator.GREATER_THAN] = "bvugt" bvuOperators[SBinaryOperator.LESS_EQUAL] = "bvule" bvuOperators[SBinaryOperator.LESS_THAN] = "bvult" arithOperators[SBinaryOperator.NOT_EQUAL] = "distinct" arithOperators[SBinaryOperator.MUL] = "*" arithOperators[SBinaryOperator.PLUS] = "+" arithOperators[SBinaryOperator.DIV] = "div" arithOperators[SBinaryOperator.XOR] = "xor" arithOperators[SBinaryOperator.EQUAL] = "=" //arithOperators[SBinaryOperator.XNOR] = "" arithOperators[SBinaryOperator.MINUS] = "-" arithOperators[SBinaryOperator.MOD] = "mod" arithOperators[SBinaryOperator.GREATER_EQUAL] = ">=" arithOperators[SBinaryOperator.GREATER_THAN] = ">" arithOperators[SBinaryOperator.LESS_EQUAL] = "<=" arithOperators[SBinaryOperator.LESS_THAN] = "<" } } }
gpl-3.0
ffb474047094d02d42039099f73bb814
41.145038
111
0.65441
3.932336
false
false
false
false
Nandi/adventofcode
src/Day12/December12.kt
1
2872
package Day12 import org.json.simple.JSONArray import org.json.simple.JSONObject import org.json.simple.parser.JSONParser import java.nio.file.Files import java.nio.file.Paths import kotlin.text.Regex /** * Santa's Accounting-Elves need help balancing the books after a recent order. Unfortunately, their accounting * software uses a peculiar storage format. That's where you come in. * * They have a JSON document which contains a variety of things: arrays ([1,2,3]), objects ({"a":1, "b":2}), numbers, * and strings. Your first job is to simply find all of the numbers throughout the document and add them together. * * You will not encounter any strings containing numbers. * * Part 1 * * What is the sum of all numbers in the document? * * Part 2 * * Uh oh - the Accounting-Elves have realized that they double-counted everything red. * * Ignore any object (and all of its children) which has any property with the value "red". Do this only for objects * ({...}), not arrays ([...]). * * Created by Simon on 13/12/2015. */ class December12 { fun part1() { val json = loadFile("src/Day12/12.dec_input.txt") val matches = Regex("(-?\\d+)").findAll(json) var total = 0 for (match in matches) { total += match.value.toInt() } println("Sum total $total") } fun part2() { val json = loadFile("src/Day12/12.dec_input.txt") val parser = JSONParser() val jsonObject = parser.parse(json) as JSONObject val amount = getAmountFromJsonObject(jsonObject) println("Revised sum total $amount") } fun getAmountFromJsonObject(jsonObject: JSONObject): Long { var result = 0L if (jsonObject.values.contains("red")) return result for (child in jsonObject.values) { if (child is JSONObject) { result += getAmountFromJsonObject(child) } else if (child is Long) { result += child } else if (child is JSONArray) { result += getAmountFromJsonArray(child) } } return result; } fun getAmountFromJsonArray(jsonArray: JSONArray): Long { var result = 0L for (arrayPart in jsonArray) { if (arrayPart is JSONObject) { result += getAmountFromJsonObject(arrayPart) } else if (arrayPart is Long) { result += arrayPart } else if (arrayPart is JSONArray) { result += getAmountFromJsonArray(arrayPart) } } return result } fun loadFile(path: String): String { val input = Paths.get(path) val reader = Files.newBufferedReader(input) return reader.readText() } } fun main(args: Array<String>) { December12().part1() December12().part2() }
mit
0bd18f3ade9bc683f4b7857473115f29
28.316327
117
0.616643
4.114613
false
false
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/util/Strings.kt
1
6752
/* * Strings */ @file:Suppress("unused") package cn.yiiguxing.plugin.translate.util import com.intellij.util.io.DigestUtil import java.net.URLEncoder import java.security.MessageDigest import java.util.* import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec private val REGEX_UNDERLINE = Regex("([A-Za-z])_+([A-Za-z])") private val REGEX_NUM_WORD = Regex("([0-9])([A-Za-z])") private val REGEX_WORD_NUM = Regex("([A-Za-z])([0-9])") private val REGEX_LOWER_UPPER = Regex("([a-z])([A-Z])") private val REGEX_UPPER_WORD = Regex("([A-Z])([A-Z][a-z])") private val REGEX_WHITESPACE_CHARACTER = Regex("\\s") private val REGEX_WHITESPACE_CHARACTERS = Regex("\\s+") private val REGEX_SINGLE_LINE = Regex("\\r\\n|\\r|\\n") private val REGEX_COMPRESS_WHITESPACE = Regex("\\s{2,}") private const val REPLACEMENT_SPLIT_GROUP = "$1 $2" /** * 单词拆分 */ fun String.splitWords(): String { return replace(REGEX_UNDERLINE, REPLACEMENT_SPLIT_GROUP) .replace(REGEX_NUM_WORD, REPLACEMENT_SPLIT_GROUP) .replace(REGEX_WORD_NUM, REPLACEMENT_SPLIT_GROUP) .replace(REGEX_LOWER_UPPER, REPLACEMENT_SPLIT_GROUP) .replace(REGEX_UPPER_WORD, REPLACEMENT_SPLIT_GROUP) } fun String.filterIgnore(): String { return try { Settings.ignoreRegex .takeIf { it.isNotEmpty() } ?.toRegex(RegexOption.MULTILINE) ?.let { replace(it, "") } ?: this } catch (e: Exception) { this } } fun String.processBeforeTranslate(): String? { val filteredIgnore = filterIgnore() val formatted = if (!Settings.keepFormat) { filteredIgnore.replace(REGEX_WHITESPACE_CHARACTERS, " ").trim() } else filteredIgnore return formatted .takeIf { it.isNotBlank() } ?.let { if (!it.contains(REGEX_WHITESPACE_CHARACTER)) it.splitWords() else it } } /** * 分割句子 * * @param maxSentenceLength 句子最大长度 * @throws IllegalArgumentException 如果[maxSentenceLength] <= 0. * * @see String.splitSentenceTo */ fun String.splitSentence(maxSentenceLength: Int): List<String> = when { maxSentenceLength <= 0 -> throw IllegalArgumentException("maxSentenceLength must be greater than 0.") isBlank() -> emptyList() else -> splitSentenceTo(ArrayList(), maxSentenceLength) } /** * 分割句子到指定集合 * * @param destination 目标集合 * @param maxSentenceLength 句子最大长度 * @throws IllegalArgumentException 如果[maxSentenceLength] <= 0. */ fun <C : MutableCollection<String>> String.splitSentenceTo(destination: C, maxSentenceLength: Int): C { require(maxSentenceLength > 0) { "maxSentenceLength must be greater than 0." } if (isBlank()) { return destination } val whitespaceReg = Regex("[ \\u3000\\n\\r\\t\\s]+") // \u3000:全角空格 val optimized = replace(whitespaceReg, " ") if (optimized.length <= maxSentenceLength) { destination += optimized return destination } return optimized.splitSentenceTo(destination, maxSentenceLength, String::splitByPunctuation) { splitSentenceTo(destination, maxSentenceLength, String::splitBySpace) { splitByLengthTo(destination, maxSentenceLength) } } } private fun <C : MutableCollection<String>> String.splitSentenceTo( destination: C, maxSentenceLength: Int, splitFun: String.() -> List<String>, reSplitFun: String.(C) -> Unit ): C { val sentences = splitFun() val sentenceBuilder = StringBuilder() for (sentence in sentences) { val merged = (sentenceBuilder.toString() + sentence).trim() if (merged.length <= maxSentenceLength) { sentenceBuilder.append(sentence) } else { if (sentenceBuilder.isNotBlank()) { destination += sentenceBuilder.trim().toString() sentenceBuilder.setLength(0) } val trimmedSentence = sentence.trim() if (trimmedSentence.length <= maxSentenceLength) { sentenceBuilder.setLength(0) sentenceBuilder.append(sentence) } else { trimmedSentence.reSplitFun(destination) } } } if (sentenceBuilder.isNotBlank()) { destination += sentenceBuilder.trim().toString() } return destination } private fun String.splitByPunctuation() = splitBy(Regex("([?.,;:!][ ]+)|([、。!(),.:;?][ ]?)")) private fun String.splitBySpace() = splitBy(Regex(" ")) private fun String.splitBy(regex: Regex): List<String> { val splits = mutableListOf<String>() var currIndex = 0 for (mr in regex.findAll(this)) { val index = mr.range.last + 1 if (index > currIndex) { splits += substring(currIndex, index) } currIndex = index } if (length > currIndex) { splits += substring(currIndex) } return splits } private fun String.splitByLengthTo(destination: MutableCollection<String>, maxLength: Int) { for (i in indices step maxLength) { destination += substring(i, minOf(i + maxLength, length)) } } fun String.singleLine(): String = replace(REGEX_SINGLE_LINE, " ") fun String.compressWhitespace(): String = replace(REGEX_COMPRESS_WHITESPACE, " ") /** * 如果内容长度超出指定[长度][n],则省略超出部分,显示为”...“。 */ fun String.ellipsis(n: Int): String { require(n >= 0) { "Requested character count $n is less than zero." } return when { n == 0 -> "..." n < length -> "${take(n)}..." else -> this } } /** * URL编码 */ fun String.urlEncode(): String = if (isEmpty()) this else URLEncoder.encode(this, "UTF-8") private val HEX_DIGITS = charArrayOf( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ) fun String.getMessageDigest(messageDigest: MessageDigest): String { return with(messageDigest) { update(toByteArray(Charsets.UTF_8)) digest().toHexString() } } /** * 生成32位MD5摘要 * @return MD5摘要 */ fun String.md5(): String = getMessageDigest(DigestUtil.md5()) /** * 生成SHA-256摘要 * @return SHA-256摘要 */ fun String.sha256(): String = getMessageDigest(DigestUtil.sha256()) /** * 生成Base64格式的MD5摘要 */ fun String.md5Base64(): String { return with(DigestUtil.md5()) { update(toByteArray()) Base64.getEncoder().encodeToString(digest()) } } fun String.hmacSha1(key: String): String { val mac: Mac = Mac.getInstance("HMACSha1") val secretKeySpec = SecretKeySpec(key.toByteArray(), mac.algorithm) mac.init(secretKeySpec) return Base64.getEncoder().encodeToString(mac.doFinal(toByteArray())) }
mit
8ba47c053a9a8c1c362f7c6e0a77ff52
28.124444
105
0.637821
3.693348
false
false
false
false
Bastien7/Lux-transport-analyzer
src/main/com/bastien7/transport/analyzer/park/entityTFL/MetaTFL.kt
1
633
package com.bastien7.transport.analyzer.park.entityTFL data class MetaTFL( val open: Boolean? = null, val elevator: Boolean? = null, val link: String? = null, val address: AddressTFL? = null, val phone: Int? = null, val reserved_for_disabled: Int? = null, val reserved_for_women: Int? = null, val motorbike_lots: Int? = null, val bus_lots: Int? = null, val bicycle_docks: Int? = null, val payment_methods: PaymentMethodsTFL? = null, val restrictions: RestrictionsTFL? = null, val additionalProperties: Map<String, Any>? = null )
apache-2.0
17f6e0069905fdb487b040cb2601e9b1
36.294118
58
0.612954
3.723529
false
false
false
false
shyiko/ktlint
ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingRuleAsciiTest.kt
1
8394
package com.pinterest.ktlint.ruleset.standard.importordering import com.pinterest.ktlint.core.LintError import com.pinterest.ktlint.core.api.FeatureInAlphaState import com.pinterest.ktlint.ruleset.standard.ImportOrderingRule import com.pinterest.ktlint.test.EditorConfigTestRule import com.pinterest.ktlint.test.format import com.pinterest.ktlint.test.lint import org.assertj.core.api.Assertions.assertThat import org.junit.Rule import org.junit.Test @OptIn(FeatureInAlphaState::class) class ImportOrderingRuleAsciiTest { companion object { private fun expectedErrors(additionalMessage: String = "") = listOf( LintError( 1, 1, "import-ordering", "Imports must be ordered in lexicographic order without any empty lines in-between$additionalMessage" ) ) } @get:Rule val editorConfigTestRule = EditorConfigTestRule() private val rule = ImportOrderingRule() @Test fun testFormat() { val imports = """ import a.A import b.C import a.AB """.trimIndent() val formattedImports = """ import a.A import a.AB import b.C """.trimIndent() val testFile = writeAsciiImportsOrderingConfig() assertThat( rule.lint(testFile, imports) ).isEqualTo(expectedErrors()) assertThat( rule.format(testFile, imports) ).isEqualTo(formattedImports) } @Test fun testFormatOk() { val formattedImports = """ import android.app.Activity import android.view.View import android.view.ViewGroup import java.util.List import kotlin.concurrent.Thread """.trimIndent() val testFile = writeAsciiImportsOrderingConfig() assertThat( rule.lint(testFile, formattedImports) ).isEmpty() assertThat( rule.format(testFile, formattedImports) ).isEqualTo(formattedImports) } @Test fun testFormatWrongOrder() { val imports = """ import android.view.ViewGroup import android.view.View import android.app.Activity import kotlin.concurrent.Thread import java.util.List """.trimIndent() val formattedImports = """ import android.app.Activity import android.view.View import android.view.ViewGroup import java.util.List import kotlin.concurrent.Thread """.trimIndent() val testFile = writeAsciiImportsOrderingConfig() assertThat( rule.lint(testFile, imports) ).isEqualTo(expectedErrors()) assertThat( rule.format(testFile, imports) ).isEqualTo(formattedImports) } @Test fun testFormatDuplicate() { val imports = """ import android.view.ViewGroup import android.view.View import android.view.ViewGroup """.trimIndent() val formattedImports = """ import android.view.View import android.view.ViewGroup """.trimIndent() val testFile = writeAsciiImportsOrderingConfig() assertThat( rule.lint(testFile, imports) ).isEqualTo(expectedErrors()) assertThat( rule.format(testFile, imports) ).isEqualTo(formattedImports) } @Test fun testFormatWrongOrderAndBlankLines() { val imports = """ import android.view.ViewGroup import android.view.View import android.app.Activity import kotlin.concurrent.Thread import java.util.List """.trimIndent() val formattedImports = """ import android.app.Activity import android.view.View import android.view.ViewGroup import java.util.List import kotlin.concurrent.Thread """.trimIndent() val testFile = writeAsciiImportsOrderingConfig() assertThat( rule.lint(testFile, imports) ).isEqualTo(expectedErrors()) assertThat( rule.format(testFile, imports) ).isEqualTo(formattedImports) } @Test fun testFormatBlankLines() { val imports = """ import android.app.Activity import android.view.View import android.view.ViewGroup import java.util.List import kotlin.concurrent.Thread """.trimIndent() val formattedImports = """ import android.app.Activity import android.view.View import android.view.ViewGroup import java.util.List import kotlin.concurrent.Thread """.trimIndent() val testFile = writeAsciiImportsOrderingConfig() assertThat( rule.lint(testFile, imports) ).isEqualTo(expectedErrors()) assertThat( rule.format(testFile, imports) ).isEqualTo(formattedImports) } @Test fun testFormatImportsWithEOLComments() { val imports = """ import android.view.View import android.app.Activity // comment import android.view.ViewGroup """.trimIndent() val formattedImports = """ import android.app.Activity // comment import android.view.View import android.view.ViewGroup """.trimIndent() val testFile = writeAsciiImportsOrderingConfig() assertThat( rule.lint(testFile, imports) ).isEqualTo(expectedErrors()) assertThat( rule.format(testFile, imports) ).isEqualTo(formattedImports) } @Test fun testCannotFormatImportsWithBlockComments() { val imports = """ import android.view.View /* comment */ import android.app.Activity import android.view.ViewGroup """.trimIndent() val testFile = writeAsciiImportsOrderingConfig() assertThat( rule.lint(testFile, imports) ).isEqualTo(expectedErrors(" -- no autocorrection due to comments in the import list")) assertThat( rule.format(testFile, imports) ).isEqualTo(imports) } @Test fun testCannotFormatImportsWithEOLComments() { val imports = """ import android.view.View // comment import android.app.Activity import android.view.ViewGroup """.trimIndent() val testFile = writeAsciiImportsOrderingConfig() assertThat( rule.lint(testFile, imports) ).isEqualTo(expectedErrors(" -- no autocorrection due to comments in the import list")) assertThat( rule.format(testFile, imports) ).isEqualTo(imports) } @Test fun testAliasesAreSortedAmongNormalImports() { val imports = """ import android.view.ViewGroup as VG import android.view.View as V import android.app.Activity import kotlin.concurrent.Thread import java.util.List as L """.trimIndent() val formattedImports = """ import android.app.Activity import android.view.View as V import android.view.ViewGroup as VG import java.util.List as L import kotlin.concurrent.Thread """.trimIndent() val testFile = writeAsciiImportsOrderingConfig() assertThat( rule.lint(testFile, imports) ).isEqualTo(expectedErrors()) assertThat( rule.format(testFile, imports) ).isEqualTo(formattedImports) } private fun writeAsciiImportsOrderingConfig() = editorConfigTestRule .writeToEditorConfig( mapOf( ImportOrderingRule.ideaImportsLayoutProperty.type to "*" ) ) .absolutePath }
mit
821bfc05d86c8443e0fb250caf0f9836
26.611842
117
0.573028
5.384221
false
true
false
false
eugeis/ee
ee-lang/src/main/kotlin/ee/lang/gen/kt/LangKotlinTemplates.kt
1
4080
package ee.lang.gen.kt import ee.lang.* import ee.lang.gen.itemNameAsKotlinFileName open class LangKotlinTemplates { private val defaultNameBuilder: TemplateI<*>.(CompilationUnitI<*>) -> NamesI constructor(defaultNameBuilder: TemplateI<*>.(CompilationUnitI<*>) -> NamesI = itemNameAsKotlinFileName) { this.defaultNameBuilder = defaultNameBuilder } open fun dslBuilderI( nameBuilder: TemplateI<CompilationUnitI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("BuilderI", nameBuilder) { item, c -> item.toKotlinDslBuilderI(c) } open fun dslObjectTree( nameBuilder: TemplateI<CompilationUnitI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("ObjectTree", nameBuilder) { item, c -> item.toKotlinObjectTree(c) } open fun dslBuilder( nameBuilder: TemplateI<CompilationUnitI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("DslBuilder", nameBuilder) { item, c -> item.toKotlinDslBuilder(c) } open fun builderI( nameBuilder: TemplateI<CompilationUnitI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("Builder", nameBuilder) { item, c -> item.toKotlinBuilderI(c) } open fun builder( nameBuilder: TemplateI<CompilationUnitI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("BuilderI", nameBuilder) { item, c -> item.toKotlinBuilder(c) } open fun enum(nameBuilder: TemplateI<EnumTypeI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("Enum", nameBuilder) { item, c -> item.toKotlinEnum(c) } open fun enumParseAndIsMethodsTestsParseMethodTests( nameBuilder: TemplateI<EnumTypeI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("EnumParseMethodTests", nameBuilder) { item, c -> item.toKotlinEnumParseAndIsMethodsTests(c) } open fun ifc(nameBuilder: TemplateI<CompilationUnitI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("Ifc", nameBuilder) { item, c -> item.toKotlinIfc(c, LangDerivedKind.API) } open fun ifcBlocking(nameBuilder: TemplateI<CompilationUnitI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("ifcBlocking", nameBuilder) { item, c -> item.toKotlinIfc(c, LangDerivedKind.API, itemName = c.n(item, "Blocking"), nonBlock = false) } open fun ifcEmpty(nameBuilder: TemplateI<CompilationUnitI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("IfcEmpty", nameBuilder) { item, c -> item.toKotlinEMPTY(c, LangDerivedKind.API) } open fun emptyBlocking(nameBuilder: TemplateI<CompilationUnitI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("IfcEmptyBlocking", nameBuilder) { item, c -> item.toKotlinEMPTY(c, LangDerivedKind.API, itemName = c.n(item, "Blocking"), nonBlock = false) } open fun blockingWrapper(nameBuilder: TemplateI<CompilationUnitI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("blockingWrapper", nameBuilder) { item, c -> item.toKotlinBlockingWrapper(c, LangDerivedKind.API) } open fun pojo(nameBuilder: TemplateI<CompilationUnitI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("Pojo", nameBuilder) { item, c -> item.toKotlinImpl(c, LangDerivedKind.API) } open fun pojoBlocking(nameBuilder: TemplateI<CompilationUnitI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("PojoBlocking", nameBuilder) { item, c -> item.toKotlinIfc(c, LangDerivedKind.API, itemName = c.n(item, "Blocking"), nonBlock = false) } open fun pojoTest(nameBuilder: TemplateI<CompilationUnitI<*>>.(CompilationUnitI<*>) -> NamesI = defaultNameBuilder) = Template("Pojo", nameBuilder) { item, c -> item.toKotlinFieldTest(c, LangDerivedKind.API) } }
apache-2.0
2307efa6759294f4d7a4f8e4d0f15714
56.464789
128
0.673284
4.303797
false
true
false
false
edsilfer/presence-control
app/src/main/java/br/com/edsilfer/android/presence_control/commons/utils/Utils.kt
1
1193
package br.com.edsilfer.android.presence_control.commons.utils import android.support.design.widget.Snackbar import android.view.View import com.facebook.AccessToken import android.net.NetworkInfo import android.content.Context.CONNECTIVITY_SERVICE import android.net.ConnectivityManager import br.com.edsilfer.android.presence_control.core.App /** * Created by ferna on 5/13/2017. */ object Utils { private val TAG = "Utils" private val ERR_001 = "Unable to move camera because Map object is null" private val ERR_002 = "Unable to move camera because Location object is null" fun showSnack(root: View, message: String, length: Int = Snackbar.LENGTH_SHORT) { Snackbar.make( root, message, length ).show() } fun isUserLoggedIn(): Boolean { val accessToken = AccessToken.getCurrentAccessToken() return accessToken != null } fun hasInternetAccess(): Boolean { val cm = App.getContext().getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager val netInfo = cm.activeNetworkInfo return netInfo != null && netInfo.isConnectedOrConnecting } }
apache-2.0
ac17811da06a5d35c21303fd7750a1da
28.097561
95
0.695725
4.553435
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/services/cooee/CooeeAuthInterceptor.kt
1
1828
package com.baulsupp.okurl.services.cooee import com.baulsupp.oksocial.output.OutputHandler import com.baulsupp.okurl.authenticator.AuthInterceptor import com.baulsupp.okurl.authenticator.Jwt import com.baulsupp.okurl.authenticator.ValidatedCredentials import com.baulsupp.okurl.credentials.CredentialsStore import com.baulsupp.okurl.credentials.TokenValue import com.baulsupp.okurl.kotlin.edit import com.baulsupp.okurl.kotlin.query import com.baulsupp.okurl.secrets.Secrets import com.baulsupp.okurl.services.AbstractServiceDefinition import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response class CooeeAuthInterceptor : AuthInterceptor<Jwt>() { override val serviceDefinition = object : AbstractServiceDefinition<Jwt>( "coo.ee", "Cooee API", "cooee", "https://coo.ee", "https://coo.ee" ) { override fun parseCredentialsString(s: String): Jwt = Jwt(s) override fun formatCredentialsString(credentials: Jwt): String = credentials.token } override suspend fun intercept(chain: Interceptor.Chain, credentials: Jwt): Response { val request = chain.request() val newRequest = request.edit { addHeader("Authorization", "Bearer " + credentials.token) } return chain.proceed(newRequest) } override suspend fun authorize( client: OkHttpClient, outputHandler: OutputHandler<Response>, authArguments: List<String> ): Jwt = Jwt(Secrets.prompt("Cooee API Token", "cooee.token", "", true)) override suspend fun validate( client: OkHttpClient, credentials: Jwt ): ValidatedCredentials = ValidatedCredentials( client.query<UserInfo>( "https://api.coo.ee/api/v0/user", TokenValue(credentials) ).name ) override fun hosts(credentialsStore: CredentialsStore): Set<String> = setOf("api.coo.ee") }
apache-2.0
c97f64c1145f888ce6adf3d8c985a595
31.642857
91
0.75
4.231481
false
false
false
false
ze-pequeno/okhttp
okhttp/src/commonMain/kotlin/okhttp3/internal/-RequestCommon.kt
2
3565
/* * Copyright (C) 2022 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.internal import kotlin.reflect.KClass import okhttp3.CacheControl import okhttp3.Headers import okhttp3.Request import okhttp3.RequestBody import okhttp3.internal.http.HttpMethod fun Request.commonHeader(name: String): String? = headers[name] fun Request.commonHeaders(name: String): List<String> = headers.values(name) fun Request.commonNewBuilder(): Request.Builder = Request.Builder(this) fun Request.commonCacheControl(): CacheControl { var result = lazyCacheControl if (result == null) { result = CacheControl.parse(headers) lazyCacheControl = result } return result } internal fun canonicalUrl(url: String): String { // Silently replace web socket URLs with HTTP URLs. return when { url.startsWith("ws:", ignoreCase = true) -> { "http:${url.substring(3)}" } url.startsWith("wss:", ignoreCase = true) -> { "https:${url.substring(4)}" } else -> url } } fun Request.Builder.commonHeader(name: String, value: String) = apply { headers[name] = value } fun Request.Builder.commonAddHeader(name: String, value: String) = apply { headers.add(name, value) } fun Request.Builder.commonRemoveHeader(name: String) = apply { headers.removeAll(name) } fun Request.Builder.commonHeaders(headers: Headers) = apply { this.headers = headers.newBuilder() } fun Request.Builder.commonCacheControl(cacheControl: CacheControl): Request.Builder { val value = cacheControl.toString() return when { value.isEmpty() -> removeHeader("Cache-Control") else -> header("Cache-Control", value) } } fun Request.Builder.commonGet(): Request.Builder = method("GET", null) fun Request.Builder.commonHead(): Request.Builder = method("HEAD", null) fun Request.Builder.commonPost(body: RequestBody): Request.Builder = method("POST", body) fun Request.Builder.commonDelete(body: RequestBody?): Request.Builder = method("DELETE", body) fun Request.Builder.commonPut(body: RequestBody): Request.Builder = method("PUT", body) fun Request.Builder.commonPatch(body: RequestBody): Request.Builder = method("PATCH", body) fun Request.Builder.commonMethod(method: String, body: RequestBody?): Request.Builder = apply { require(method.isNotEmpty()) { "method.isEmpty() == true" } if (body == null) { require(!HttpMethod.requiresRequestBody(method)) { "method $method must have a request body." } } else { require(HttpMethod.permitsRequestBody(method)) { "method $method must not have a request body." } } this.method = method this.body = body } fun <T : Any> Request.Builder.commonTag(type: KClass<T>, tag: T?) = apply { if (tag == null) { if (tags.isNotEmpty()) { (tags as MutableMap).remove(type) } } else { val mutableTags: MutableMap<KClass<*>, Any> = when { tags.isEmpty() -> mutableMapOf<KClass<*>, Any>().also { tags = it } else -> tags as MutableMap<KClass<*>, Any> } mutableTags[type] = tag } }
apache-2.0
4f2b06e506ac23717180bd9bd197e22c
28.708333
95
0.702945
3.808761
false
false
false
false
inorichi/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryAdapter.kt
1
4864
package eu.kanade.tachiyomi.ui.library import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import eu.kanade.tachiyomi.data.database.models.Category import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.databinding.LibraryCategoryBinding import eu.kanade.tachiyomi.ui.library.setting.DisplayModeSetting import eu.kanade.tachiyomi.widget.RecyclerViewPagerAdapter import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get /** * This adapter stores the categories from the library, used with a ViewPager. * * @constructor creates an instance of the adapter. */ class LibraryAdapter( private val controller: LibraryController, private val preferences: PreferencesHelper = Injekt.get() ) : RecyclerViewPagerAdapter() { /** * The categories to bind in the adapter. */ var categories: List<Category> = emptyList() // This setter helps to not refresh the adapter if the reference to the list doesn't change. set(value) { if (field !== value) { field = value notifyDataSetChanged() } } /** * The number of manga in each category. */ var itemsPerCategory: Map<Int, Int> = emptyMap() set(value) { if (field !== value) { field = value notifyDataSetChanged() } } private var boundViews = arrayListOf<View>() private val isPerCategory by lazy { preferences.categorizedDisplaySettings().get() } private var currentDisplayMode = preferences.libraryDisplayMode().get() init { preferences.libraryDisplayMode() .asFlow() .drop(1) .onEach { currentDisplayMode = it } .launchIn(controller.viewScope) } /** * Creates a new view for this adapter. * * @return a new view. */ override fun inflateView(container: ViewGroup, viewType: Int): View { val binding = LibraryCategoryBinding.inflate(LayoutInflater.from(container.context), container, false) val view: LibraryCategoryView = binding.root view.onCreate(controller, binding, viewType) return view } /** * Binds a view with a position. * * @param view the view to bind. * @param position the position in the adapter. */ override fun bindView(view: View, position: Int) { (view as LibraryCategoryView).onBind(categories[position]) boundViews.add(view) } /** * Recycles a view. * * @param view the view to recycle. * @param position the position in the adapter. */ override fun recycleView(view: View, position: Int) { (view as LibraryCategoryView).onRecycle() boundViews.remove(view) } /** * Returns the number of categories. * * @return the number of categories or 0 if the list is null. */ override fun getCount(): Int { return categories.size } /** * Returns the title to display for a category. * * @param position the position of the element. * @return the title to display. */ override fun getPageTitle(position: Int): CharSequence { if (preferences.categoryNumberOfItems().get()) { return categories[position].let { "${it.name} (${itemsPerCategory[it.id]})" } } return categories[position].name } /** * Returns the position of the view. */ override fun getItemPosition(obj: Any): Int { val view = obj as? LibraryCategoryView ?: return POSITION_NONE val index = categories.indexOfFirst { it.id == view.category.id } return if (index == -1) POSITION_NONE else index } /** * Called when the view of this adapter is being destroyed. */ fun onDestroy() { for (view in boundViews) { if (view is LibraryCategoryView) { view.onDestroy() } } } override fun getViewType(position: Int): Int { val category = categories.getOrNull(position) return if (isPerCategory && category?.id != 0) { if (DisplayModeSetting.fromFlag(category?.displayMode) == DisplayModeSetting.LIST) { LIST_DISPLAY_MODE } else { GRID_DISPLAY_MODE } } else { if (currentDisplayMode == DisplayModeSetting.LIST) { LIST_DISPLAY_MODE } else { GRID_DISPLAY_MODE } } } companion object { const val LIST_DISPLAY_MODE = 1 const val GRID_DISPLAY_MODE = 2 } }
apache-2.0
ccc64bd160f67bff72421be0d03a4118
29.024691
110
0.614309
4.67243
false
false
false
false
vase4kin/TeamCityApp
app/src/main/java/com/github/vase4kin/teamcityapp/buildlist/data/BuildListDataManagerImpl.kt
1
7203
/* * Copyright 2019 Andrey Tolpeev * * 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.vase4kin.teamcityapp.buildlist.data import com.github.vase4kin.teamcityapp.account.create.data.OnLoadingListener import com.github.vase4kin.teamcityapp.api.Repository import com.github.vase4kin.teamcityapp.base.list.data.BaseListRxDataManagerImpl import com.github.vase4kin.teamcityapp.buildlist.api.Build import com.github.vase4kin.teamcityapp.buildlist.api.Builds import com.github.vase4kin.teamcityapp.buildlist.filter.BuildListFilter import com.github.vase4kin.teamcityapp.overview.data.BuildDetails import com.github.vase4kin.teamcityapp.overview.data.BuildDetailsImpl import com.github.vase4kin.teamcityapp.storage.SharedUserStorage import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.rxkotlin.addTo import io.reactivex.rxkotlin.subscribeBy import io.reactivex.schedulers.Schedulers /** * Impl of [BuildListDataManager] */ open class BuildListDataManagerImpl( protected val repository: Repository, private val sharedUserStorage: SharedUserStorage ) : BaseListRxDataManagerImpl<Builds, Build>(), BuildListDataManager { /** * Load more url */ private var loadMoreUrl: String? = null /** * {@inheritDoc} */ override fun load( id: String, loadingListener: OnLoadingListener<List<BuildDetails>>, update: Boolean ) { loadBuilds(repository.listBuilds(id, BuildListFilter.DEFAULT_FILTER_LOCATOR, update), loadingListener) } /** * {@inheritDoc} */ override fun load( id: String, filter: BuildListFilter, loadingListener: OnLoadingListener<List<BuildDetails>>, update: Boolean ) { loadBuilds(repository.listBuilds(id, filter.toLocator(), update), loadingListener) } /** * {@inheritDoc} */ override fun canLoadMore(): Boolean { return loadMoreUrl != null } /** * {@inheritDoc} */ override fun addToFavorites(buildTypeId: String) { sharedUserStorage.addBuildTypeToFavorites(buildTypeId) } /** * {@inheritDoc} */ override fun removeFromFavorites(buildTypeId: String) { sharedUserStorage.removeBuildTypeFromFavorites(buildTypeId) } /** * {@inheritDoc} */ override fun hasBuildTypeAsFavorite(buildTypeId: String): Boolean { for (favBuildTypeId in sharedUserStorage.activeUser.buildTypeIds) { if (favBuildTypeId == buildTypeId) { return true } } return false } /** * {@inheritDoc} */ private fun loadBuilds( call: Single<Builds>, loadingListener: OnLoadingListener<List<BuildDetails>> ) { val buildDetailsList = getBuildDetailsObservable(call) // putting them all to the sorted list // where queued builds go first .toSortedList { build, build2 -> when { build.isQueued == build2.isQueued -> 0 build.isQueued -> -1 else -> 1 } } loadBuildDetailsList(buildDetailsList, loadingListener) } protected fun loadBuildDetailsList( call: Single<List<BuildDetails>>, loadingListener: OnLoadingListener<List<BuildDetails>> ) { subscriptions.clear() call .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onSuccess = { loadingListener.onSuccess(it) }, onError = { loadingListener.onFail(it.message ?: "") } ) .addTo(subscriptions) } /** * {@inheritDoc} */ protected fun loadNotSortedBuilds( call: Single<Builds>, loadingListener: OnLoadingListener<List<BuildDetails>> ) { val buildDetailsList = getBuildDetailsObservable(call).toList() loadBuildDetailsList(buildDetailsList, loadingListener) } protected fun getBuildDetailsObservable(call: Single<Builds>): Observable<BuildDetails> { return call // converting all received builds to observables .flatMapObservable { builds -> if (builds.count == 0) { Observable.fromIterable(emptyList<Build>()) } else { loadMoreUrl = builds.nextHref Observable.fromIterable(builds.objects) } } // returning new updated build observables for each stored build already .flatMapSingle { serverBuild -> // Make sure cache is updated val serverBuildDetails = BuildDetailsImpl(serverBuild) // If server build's running update cache immediately if (serverBuildDetails.isRunning) { repository.build(serverBuild.href, true) } else { // Call cache repository.build(serverBuild.href, false) .flatMap { cachedBuild -> val cacheBuildDetails = BuildDetailsImpl(cachedBuild) // Compare if server side and cache are updated // If cache's not updated -> update it repository.build( cachedBuild.href, // Don't update cache if server and cache builds are finished serverBuildDetails.isFinished != cacheBuildDetails.isFinished ) } } } .map { BuildDetailsImpl(it) } .cast(BuildDetails::class.java) } /** * Load build count * * @param call - Retrofit call * @param loadingListener - Listener to receive server callbacks */ fun loadCount(call: Single<Int>, loadingListener: OnLoadingListener<Int>) { subscriptions.clear() call .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onSuccess = { loadingListener.onSuccess(it) }, onError = { loadingListener.onSuccess(0) } ) .addTo(subscriptions) } /** * {@inheritDoc} */ override fun loadMore(loadingListener: OnLoadingListener<List<BuildDetails>>) { loadBuilds(repository.listMoreBuilds(loadMoreUrl!!), loadingListener) } }
apache-2.0
9658a3915508ae78b0a2fb0fac0945a7
33.137441
110
0.614744
4.974448
false
false
false
false
Kotlin/dokka
plugins/base/src/test/kotlin/translators/utils.kt
1
1798
package translators import org.jetbrains.dokka.model.* import org.jetbrains.dokka.model.doc.Description import org.jetbrains.dokka.model.doc.Text import java.util.NoSuchElementException fun DModule.documentationOf(className: String, functionName: String? = null): String = descriptionOf(className, functionName) ?.firstMemberOfType<Text>() ?.body.orEmpty() fun DModule.descriptionOf(className: String, functionName: String? = null): Description? { val classlike = packages.single() .classlikes.single { it.name == className } val target: Documentable = if (functionName != null) classlike.functions.single { it.name == functionName } else classlike return target.documentation.values.singleOrNull() ?.firstChildOfTypeOrNull<Description>() } fun DModule.findPackage(packageName: String? = null) = packageName?.let { packages.firstOrNull { pkg -> pkg.packageName == packageName } ?: throw NoSuchElementException("No packageName with name $packageName") } ?: packages.single() fun DModule.findClasslike(packageName: String? = null, className: String? = null): DClasslike { val pkg = findPackage(packageName) return className?.let { pkg.classlikes.firstOrNull { cls -> cls.name == className } ?: throw NoSuchElementException("No classlike with name $className") } ?: pkg.classlikes.single() } fun DModule.findFunction(packageName: String? = null, className: String, functionName: String? = null): DFunction { val classlike = findClasslike(packageName, className) return functionName?.let { classlike.functions.firstOrNull { fn -> fn.name == functionName } ?: throw NoSuchElementException("No classlike with name $functionName") } ?: classlike.functions.single() }
apache-2.0
4efc255aa4f08d5576f54b8d5a670738
43.95
115
0.716908
4.517588
false
false
false
false
michael-johansen/workshop-jb
src/vi_generics/_27_ErasedGenerics.kt
5
2282
package vi_generics.generics import util.questions.Answer import util.questions.Answer.* import util.TODO // Generics are NOT reified (they're erased, as in Java). fun <T> bar(c: Collection<T>) { // That means you can't make an is-check for a generic type: // if (c is List<Int>) { } // However, if the compiler can guarantee the parameter type, the check is allowed: if (c is List<T>) {} // List<*> means 'List of elements of unknown type', the same as List<?> in Java: if (c is List<*>) {} } fun <E> enclose(list: MutableList<E>) { val head = list.firstOrNull() if (head != null) { list.add(head) } } fun encloseV2(list: MutableList<*>) { val head = list.firstOrNull() if (head != null) { // doesn't compile // for now 'add' is unresolved, but the diagnostic here has to be improved // list.add(head) } } fun todoTask27() = TODO( """ Task 27. Look at the questions below and give your answers: change 'insertAnswerHere()' in task27's map to your choice (a, b or c). """ ) fun insertAnswerHere() = todoTask27() fun task27() = linkedMapOf<Int, Answer>( /* 1. The function fun isListOfNumbers(c: List<*>) = c is List<Int> doesn't compile because a. Generic types are reified b. Generic types are erased c. List<*> can never be a List of Ints */ 1 to insertAnswerHere(), /* Note: You can use the IntelliJ action "Show expression type" on variable initializer or invoke the "Specify type explicitly" intention on a declared variable to see the type of an expression / variable. The type of the variable 'head' in the following function fun encloseV2(list: MutableList<*>) { val head = list.head } is a. 'Any?' b. '*' c. unknown */ 2 to insertAnswerHere(), /* The code fun encloseV2(list: MutableList<*>) { val head = list.head if (head != null) { list.add(head) } } doesn't compile because a. There is no 'add' method on MutableList b. We can't invoke any methods on MutableList<*> c. The type of an element of MutableList<*> is unknown so the compiler can't allow adding an element of type 'Any' to the list */ 3 to insertAnswerHere() )
mit
b598bf9dde934db693fa2a1d3ef2f99c
24.355556
88
0.630587
3.740984
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/docs/RsDocumentationProvider.kt
1
14899
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.docs import com.intellij.codeInsight.documentation.DocumentationManagerUtil import com.intellij.lang.documentation.AbstractDocumentationProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiManager import org.rust.ide.presentation.escaped import org.rust.ide.presentation.presentableQualifiedName import org.rust.ide.presentation.presentationInfo import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.types.type import org.rust.lang.doc.documentationAsHtml class RsDocumentationProvider : AbstractDocumentationProvider() { override fun generateDoc(element: PsiElement, originalElement: PsiElement?): String? = when (element) { is RsDocAndAttributeOwner -> generateDoc(element) is RsPatBinding -> pre { generateDoc(element) } is RsTypeParameter -> pre { generateDoc(element) } else -> null } override fun getQuickNavigateInfo(element: PsiElement, originalElement: PsiElement?): String? = when (element) { is RsPatBinding -> generateDoc(element) is RsTypeParameter -> generateDoc(element) is RsConstant -> element.presentationInfo?.quickDocumentationText is RsMod -> element.presentationInfo?.quickDocumentationText is RsItemElement -> element.header(false) + element.signature(false) is RsNamedElement -> element.presentationInfo?.quickDocumentationText else -> null } private fun generateDoc(element: RsDocAndAttributeOwner): String? { val doc = element.documentationAsHtml() ?: "" return element.header(true) + element.signature(true) + doc } private fun generateDoc(element: RsPatBinding): String? { val presentationInfo = element.presentationInfo ?: return null val type = element.type.toString().escaped return "${presentationInfo.type} <b>${presentationInfo.name}</b>: $type" } private fun generateDoc(element: RsTypeParameter): String? { val name = element.name ?: return null return buildString { append("type parameter ") b { it += name } val typeBounds = element.bounds if (typeBounds.isNotEmpty()) { typeBounds.joinTo(this, " + ", ": ") { generateDocumentation(it) } } element.typeReference?.generateDocumentation(this, " = ") } } override fun getDocumentationElementForLink(psiManager: PsiManager, link: String, context: PsiElement): PsiElement? { if (context !is RsCompositeElement) return null return RsCodeFragmentFactory(context.project) .createPath(link, context) ?.reference ?.resolve() } } private fun RsDocAndAttributeOwner.header(usePreTag: Boolean): String { val rawLines = when (this) { is RsFieldDecl -> listOfNotNull((parent?.parent as? RsDocAndAttributeOwner)?.presentableQualifiedName) is RsFunction -> { val owner = owner when (owner) { is RsFunctionOwner.Foreign, is RsFunctionOwner.Free -> listOfNotNull(presentableQualifiedModName) is RsFunctionOwner.Impl -> listOfNotNull(presentableQualifiedModName) + owner.impl.declarationText is RsFunctionOwner.Trait -> owner.trait.declarationText } } is RsStructOrEnumItemElement, is RsTraitItem -> listOfNotNull(presentableQualifiedModName) is RsTypeAlias -> { val owner = owner when (owner) { is RsTypeAliasOwner.Impl -> listOfNotNull(presentableQualifiedModName) + owner.impl.declarationText is RsTypeAliasOwner.Trait -> owner.trait.declarationText is RsTypeAliasOwner.Free -> listOfNotNull(presentableQualifiedModName) } } else -> listOfNotNull(presentableQualifiedName) } val startTag = if (usePreTag) "<pre>" else "" val endTag = if (usePreTag) "</pre>" else "" return when (rawLines.size) { 0 -> "" 1 -> "$startTag${rawLines[0]}$endTag\n" else -> { val firstLine = "$startTag${rawLines[0]}$endTag\n" val additionalLines = rawLines.drop(1).joinToString("<br>", startTag, endTag) "$firstLine$additionalLines\n" } } } private fun RsDocAndAttributeOwner.signature(usePreTag: Boolean): String { val rawLines = when (this) { is RsFieldDecl -> listOfNotNull(presentationInfo?.signatureText) is RsFunction -> { val buffer = StringBuilder() declarationModifiers.joinTo(buffer, " ") buffer += " " buffer.b { it += name } typeParameterList?.generateDocumentation(buffer) valueParameterList?.generateDocumentation(buffer) retType?.generateDocumentation(buffer) listOf(buffer.toString()) + whereClause?.documentationText.orEmpty() } // All these types extend RsTypeBearingItemElement and RsGenericDeclaration interfaces // so all casts are safe is RsStructOrEnumItemElement, is RsTraitItem, is RsTypeAlias -> { val name = name if (name != null) { val buffer = StringBuilder() (this as RsItemElement).declarationModifiers.joinTo(buffer, " ", "", " ") buffer.b { it += name } (this as RsGenericDeclaration).typeParameterList?.generateDocumentation(buffer) (this as? RsTypeAlias)?.typeReference?.generateDocumentation(buffer, " = ") listOf(buffer.toString()) + whereClause?.documentationText.orEmpty() } else emptyList() } else -> emptyList() } val startTag = if (usePreTag) "<pre>" else "" val endTag = if (usePreTag) "</pre>" else "" return if (rawLines.isNotEmpty()) rawLines.joinToString("<br>", startTag, "$endTag\n") else "" } private val RsImplItem.declarationText: List<String> get() { val typeRef = typeReference ?: return emptyList() val buffer = StringBuilder("impl") typeParameterList?.generateDocumentation(buffer) buffer += " " val traitRef = traitRef if (traitRef != null) { traitRef.generateDocumentation(buffer) buffer += " for " } typeRef.generateDocumentation(buffer) return listOf(buffer.toString()) + whereClause?.documentationText.orEmpty() } private val RsTraitItem.declarationText: List<String> get() { val name = presentableQualifiedName ?: return emptyList() val buffer = StringBuilder(name) typeParameterList?.generateDocumentation(buffer) return listOf(buffer.toString()) + whereClause?.documentationText.orEmpty() } private val RsItemElement.declarationModifiers: List<String> get() { val modifiers = mutableListOf<String>() if (isPublic) { modifiers += "pub" } when (this) { is RsFunction -> { if (isConst) { modifiers += "const" } if (isUnsafe) { modifiers += "unsafe" } if (isExtern) { modifiers += "extern" abiName?.let { modifiers += it } } modifiers += "fn" } is RsStructItem -> modifiers += "struct" is RsEnumItem -> modifiers += "enum" is RsTypeAlias -> modifiers += "type" is RsTraitItem -> { if (isUnsafe) { modifiers += "unsafe" } modifiers += "trait" } else -> error("unexpected type $javaClass") } return modifiers } private val RsWhereClause.documentationText: List<String> get() { return listOf("where") + wherePredList.mapNotNull { val buffer = StringBuilder() val lifetime = it.lifetime val typeReference = it.typeReference when { lifetime != null -> { lifetime.generateDocumentation(buffer) it.lifetimeParamBounds?.generateDocumentation(buffer) } typeReference != null -> { typeReference.generateDocumentation(buffer) it.typeParamBounds?.generateDocumentation(buffer) } else -> return@mapNotNull null } "&nbsp;&nbsp;&nbsp;&nbsp;$buffer," } } private val RsDocAndAttributeOwner.presentableQualifiedModName: String? get() = presentableQualifiedName?.removeSuffix("::$name") private fun PsiElement.generateDocumentation(buffer: StringBuilder, prefix: String = "", suffix: String = "") { buffer += prefix when (this) { is RsPath -> generatePathDocumentation(this, buffer) is RsAssocTypeBinding -> { buffer += identifier.text typeReference.generateDocumentation(buffer, " = ") } is RsTraitRef -> path.generateDocumentation(buffer) is RsLifetimeParamBounds -> lifetimeList.joinTo(buffer, " + ", ": ") { generateDocumentation(it) } is RsTypeParamBounds -> { if (polyboundList.isNotEmpty()) { polyboundList.joinTo(buffer, " + ", ": ") { generateDocumentation(it) } } } // TODO: support 'for lifetimes' is RsPolybound -> { if (q != null) { buffer += "?" } (bound.lifetime ?: bound.traitRef)?.generateDocumentation(buffer) } is RsTypeArgumentList -> (lifetimeList + typeReferenceList + assocTypeBindingList) .joinTo(buffer, ", ", "&lt;", "&gt;") { generateDocumentation(it) } is RsTypeParameterList -> (lifetimeParameterList + typeParameterList) .joinTo(buffer, ", ", "&lt;", "&gt;") { generateDocumentation(it) } is RsValueParameterList -> (listOfNotNull(selfParameter) + valueParameterList + listOfNotNull(dotdotdot)) .joinTo(buffer, ", ", "(", ")") { generateDocumentation(it) } is RsLifetimeParameter -> { buffer += quoteIdentifier.text.escaped lifetimeParamBounds?.generateDocumentation(buffer) } is RsTypeParameter -> { buffer += name typeParamBounds?.generateDocumentation(buffer) typeReference?.generateDocumentation(buffer, " = ") } is RsValueParameter -> { pat?.generateDocumentation(buffer, suffix = ": ") typeReference?.generateDocumentation(buffer) } is RsTypeReference -> generateTypeReferenceDocumentation(this, buffer) is RsRetType -> typeReference?.generateDocumentation(buffer, " -&gt; ") is RsTypeQual -> { buffer += "&lt;" typeReference.generateDocumentation(buffer) traitRef?.generateDocumentation(buffer, " as ") buffer += "&gt;::" } else -> buffer += text.escaped } buffer += suffix } private fun generatePathDocumentation(element: RsPath, buffer: StringBuilder) { val path = element.path if (path != null) { buffer += path.text.escaped buffer += "::" } element.typeQual?.generateDocumentation(buffer) val name = element.referenceName if (element.isLinkNeeded()) { createLink(buffer, element.link(), name) } else { buffer += name } val typeArgumentList = element.typeArgumentList val valueParameterList = element.valueParameterList when { typeArgumentList != null -> typeArgumentList.generateDocumentation(buffer) valueParameterList != null -> { valueParameterList.generateDocumentation(buffer) element.retType?.generateDocumentation(buffer) } } } private fun generateTypeReferenceDocumentation(element: RsTypeReference, buffer: StringBuilder) { val typeElement = element.typeElement when (typeElement) { is RsBaseType -> { when { typeElement.isUnit -> buffer += "()" typeElement.isCself -> buffer += "Self" else -> typeElement.path?.generateDocumentation(buffer) } } is RsTupleType -> typeElement.typeReferenceList.joinTo(buffer, ", ", "(", ")") { generateDocumentation(it) } is RsArrayType -> { buffer += "[" typeElement.typeReference.generateDocumentation(buffer) typeElement.arraySize?.let { buffer += "; " buffer.append(it) } buffer += "]" } is RsRefLikeType -> { if (typeElement.isRef) { buffer += "&amp;" typeElement.lifetime?.generateDocumentation(buffer, suffix = " ") if (typeElement.mutability.isMut) { buffer += "mut " } } else { buffer += "*" buffer += if (typeElement.mutability.isMut) "mut " else "const " } typeElement.typeReference.generateDocumentation(buffer) } is RsFnPointerType -> { // TODO: handle abi buffer += "fn" typeElement.valueParameterList.generateDocumentation(buffer) typeElement.retType?.generateDocumentation(buffer) } else -> buffer += element.text.escaped } } private fun RsPath.isLinkNeeded(): Boolean { val element = reference.resolve() // If it'll find out that links for type parameters are useful // just check element for null return !(element == null || element is RsTypeParameter) } private fun RsPath.link(): String { val path = path val prefix = if (path != null) "${path.text.escaped}::" else typeQual?.text?.escaped return if (prefix != null) "$prefix$referenceName" else referenceName } private fun createLink(buffer: StringBuilder, refText: String, text: String) { DocumentationManagerUtil.createHyperlink(buffer, refText, text, true) } private inline fun pre(block: () -> String?): String? = block()?.let { "<pre>$it</pre>" } private operator fun StringBuilder.plusAssign(value: String?) { if (value != null) { append(value) } } private inline fun StringBuilder.b(action: (StringBuilder) -> Unit) { append("<b>") action(this) append("</b>") } private inline fun <T> Iterable<T>.joinTo( buffer: StringBuilder, separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", action: T.(StringBuilder) -> Unit ) { buffer.append(prefix) var needInsertSeparator = false for (element in this) { if (needInsertSeparator) { buffer.append(separator) } element.action(buffer) needInsertSeparator = true } buffer.append(postfix) }
mit
74227e05424ef7cd6f8f16bf80c687df
37.104859
121
0.615545
4.917162
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/features/tournaments/TournamentsFragment.kt
1
7321
package com.garpr.android.features.tournaments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.garpr.android.R import com.garpr.android.extensions.layoutInflater import com.garpr.android.features.common.fragments.BaseFragment import com.garpr.android.features.common.views.NoResultsItemView import com.garpr.android.features.tournament.TournamentActivity import com.garpr.android.features.tournaments.TournamentsViewModel.ListItem import com.garpr.android.misc.ListLayout import com.garpr.android.misc.Refreshable import com.garpr.android.misc.RegionHandleUtils import com.garpr.android.repositories.RegionRepository import kotlinx.android.synthetic.main.fragment_tournaments.* import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.sharedViewModel class TournamentsFragment : BaseFragment(), ListLayout, Refreshable, SwipeRefreshLayout.OnRefreshListener, TournamentItemView.Listener { private val adapter = Adapter(this) private val viewModel: TournamentsViewModel by sharedViewModel() protected val regionHandleUtils: RegionHandleUtils by inject() protected val regionRepository: RegionRepository by inject() companion object { fun create() = TournamentsFragment() } private fun fetchTournamentsBundle() { viewModel.fetchTournaments(regionHandleUtils.getRegion(context)) } override fun getRecyclerView(): RecyclerView? { return recyclerView } private fun initListeners() { onCreateViewDisposable.add(regionRepository.observable .subscribe { refresh() }) viewModel.stateLiveData.observe(viewLifecycleOwner, Observer { refreshState(it) }) } private fun initViews() { refreshLayout.setOnRefreshListener(this) recyclerView.addItemDecoration(DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL)) recyclerView.setHasFixedSize(true) recyclerView.adapter = adapter } override fun onClick(v: TournamentItemView) { startActivity(TournamentActivity.getLaunchIntent( context = requireContext(), tournament = v.tournament, region = regionHandleUtils.getRegion(context) )) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) return inflater.inflate(R.layout.fragment_tournaments, container, false) } override fun onRefresh() { refresh() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initViews() initListeners() fetchTournamentsBundle() } override fun refresh() { fetchTournamentsBundle() } private fun refreshState(state: TournamentsViewModel.State) { if (state.hasError) { showError() } else if (state.isEmpty) { showEmpty() } else if (state.searchResults != null) { showList(state.searchResults) } else { showList(state.list) } refreshLayout.isRefreshing = state.isFetching } private fun showEmpty() { adapter.clear() recyclerView.visibility = View.GONE error.visibility = View.GONE empty.visibility = View.VISIBLE } private fun showError() { adapter.clear() recyclerView.visibility = View.GONE empty.visibility = View.GONE error.visibility = View.VISIBLE } private fun showList(list: List<ListItem>?) { adapter.set(list) empty.visibility = View.GONE error.visibility = View.GONE recyclerView.visibility = View.VISIBLE } private class Adapter( private val tournamentItemViewListener: TournamentItemView.Listener ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val list = mutableListOf<ListItem>() companion object { private const val VIEW_TYPE_NO_RESULTS = 0 private const val VIEW_TYPE_TOURNAMENT = 1 } init { setHasStableIds(true) } private fun bindNoResults(holder: NoResultsViewHolder, item: ListItem.NoResults) { holder.noResultsItemView.setContent(item.query) } private fun bindTournament(holder: TournamentViewHolder, item: ListItem.Tournament) { holder.tournamentItemView.setContent(item.tournament) } internal fun clear() { list.clear() notifyDataSetChanged() } override fun getItemCount(): Int { return list.size } override fun getItemId(position: Int): Long { return list[position].hashCode().toLong() } override fun getItemViewType(position: Int): Int { return when (list[position]) { is ListItem.NoResults -> VIEW_TYPE_NO_RESULTS is ListItem.Tournament -> VIEW_TYPE_TOURNAMENT } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (val item = list[position]) { is ListItem.NoResults -> bindNoResults(holder as NoResultsViewHolder, item) is ListItem.Tournament -> bindTournament(holder as TournamentViewHolder, item) else -> throw RuntimeException("unknown item: $item, position: $position") } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = parent.layoutInflater return when (viewType) { VIEW_TYPE_NO_RESULTS -> NoResultsViewHolder(inflater.inflate( R.layout.item_no_results, parent, false)) VIEW_TYPE_TOURNAMENT -> TournamentViewHolder(tournamentItemViewListener, inflater.inflate(R.layout.item_tournament, parent, false)) else -> throw IllegalArgumentException("unknown viewType: $viewType") } } internal fun set(list: List<ListItem>?) { this.list.clear() if (!list.isNullOrEmpty()) { this.list.addAll(list) } notifyDataSetChanged() } } private class NoResultsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { internal val noResultsItemView: NoResultsItemView = itemView as NoResultsItemView } private class TournamentViewHolder( listener: TournamentItemView.Listener, itemView: View ) : RecyclerView.ViewHolder(itemView) { internal val tournamentItemView: TournamentItemView = itemView as TournamentItemView init { tournamentItemView.listener = listener } } }
unlicense
240c00ee5fe837393f40b91e280fffab
32.126697
100
0.660019
5.297395
false
false
false
false
msebire/intellij-community
platform/configuration-store-impl/src/StoreAwareProjectManager.kt
1
12029
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.configurationStore.schemeManager.SchemeChangeEvent import com.intellij.configurationStore.schemeManager.SchemeFileTracker import com.intellij.configurationStore.schemeManager.useSchemeLoader import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.application.impl.ApplicationInfoImpl import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.components.stateStore import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.project.impl.ProjectManagerImpl import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.ex.VirtualFileManagerAdapter import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.ui.AppUIUtil import com.intellij.util.ExceptionUtil import com.intellij.util.SingleAlarm import com.intellij.util.containers.MultiMap import gnu.trove.THashSet import java.util.* import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference private val CHANGED_FILES_KEY = Key.create<MultiMap<ComponentStoreImpl, StateStorage>>("CHANGED_FILES_KEY") private val CHANGED_SCHEMES_KEY = Key.create<MultiMap<SchemeFileTracker, SchemeChangeEvent>>("CHANGED_SCHEMES_KEY") /** * Should be a separate service, not closely related to ProjectManager, but it requires some cleanup/investigation. */ class StoreAwareProjectManager(virtualFileManager: VirtualFileManager, progressManager: ProgressManager) : ProjectManagerImpl(progressManager) { private val reloadBlockCount = AtomicInteger() private val blockStackTrace = AtomicReference<String?>() private val changedApplicationFiles = LinkedHashSet<StateStorage>() private val restartApplicationOrReloadProjectTask = Runnable { if (!isReloadUnblocked() || !tryToReloadApplication()) { return@Runnable } val projectsToReload = THashSet<Project>() for (project in openProjects) { if (project.isDisposed) { continue } val changedSchemes = project.getUserData(CHANGED_SCHEMES_KEY) if (changedSchemes != null) { CHANGED_SCHEMES_KEY.set(project, null) } val changedStorages = project.getUserData(CHANGED_FILES_KEY) if (changedStorages != null) { CHANGED_FILES_KEY.set(project, null) } if ((changedSchemes == null || changedSchemes.isEmpty) && (changedStorages == null || changedStorages.isEmpty)) { continue } runBatchUpdate(project.messageBus) { // reload schemes first because project file can refer to scheme (e.g. inspection profile) if (changedSchemes != null) { useSchemeLoader { schemeLoaderRef -> for ((tracker, files) in changedSchemes.entrySet()) { LOG.runAndLogException { tracker.reload(files, schemeLoaderRef) } } } } if (changedStorages != null) { for ((store, storages) in changedStorages.entrySet()) { if ((store.storageManager as? StateStorageManagerImpl)?.componentManager?.isDisposed == true) { continue } @Suppress("UNCHECKED_CAST") if (reloadStore(storages as Set<StateStorage>, store) == ReloadComponentStoreStatus.RESTART_AGREED) { projectsToReload.add(project) } } } } } for (project in projectsToReload) { ProjectManagerImpl.doReloadProject(project) } } private val changedFilesAlarm = SingleAlarm(restartApplicationOrReloadProjectTask, 300, this) init { ApplicationManager.getApplication().messageBus.connect().subscribe(STORAGE_TOPIC, object : StorageManagerListener { override fun storageFileChanged(event: VFileEvent, storage: StateStorage, componentManager: ComponentManager) { if (event.requestor is ProjectManagerEx) { return } registerChangedStorage(storage, componentManager) } }) virtualFileManager.addVirtualFileManagerListener(object : VirtualFileManagerAdapter() { override fun beforeRefreshStart(asynchronous: Boolean) { blockReloadingProjectOnExternalChanges() } override fun afterRefreshFinish(asynchronous: Boolean) { unblockReloadingProjectOnExternalChanges() } }) } private fun isReloadUnblocked(): Boolean { val count = reloadBlockCount.get() LOG.debug { "[RELOAD] myReloadBlockCount = $count" } return count == 0 } override fun saveChangedProjectFile(file: VirtualFile, project: Project) { val storageManager = (project.stateStore as ComponentStoreImpl).storageManager as? StateStorageManagerImpl ?: return storageManager.getCachedFileStorages(listOf(storageManager.collapseMacros(file.path))).firstOrNull()?.let { // if empty, so, storage is not yet loaded, so, we don't have to reload registerChangedStorage(it, project) } } override fun blockReloadingProjectOnExternalChanges() { if (reloadBlockCount.getAndIncrement() == 0 && !ApplicationInfoImpl.isInStressTest()) { blockStackTrace.set(ExceptionUtil.currentStackTrace()) } } override fun unblockReloadingProjectOnExternalChanges() { val counter = reloadBlockCount.get() if (counter <= 0) { LOG.error("Block counter $counter must be > 0, first block stack trace: ${blockStackTrace.get()}") } if (reloadBlockCount.decrementAndGet() != 0) { return } blockStackTrace.set(null) if (changedFilesAlarm.isEmpty) { if (ApplicationManager.getApplication().isUnitTestMode) { // todo fix test to handle invokeLater changedFilesAlarm.request(true) } else { ApplicationManager.getApplication().invokeLater(restartApplicationOrReloadProjectTask, ModalityState.NON_MODAL) } } } override fun flushChangedProjectFileAlarm() { changedFilesAlarm.drainRequestsInTest() } override fun reloadProject(project: Project) { CHANGED_FILES_KEY.set(project, null) super.reloadProject(project) } private fun registerChangedStorage(storage: StateStorage, componentManager: ComponentManager) { if (LOG.isDebugEnabled) { LOG.debug("[RELOAD] Registering project to reload: $storage", Exception()) } val project: Project? = when (componentManager) { is Project -> componentManager is Module -> componentManager.project else -> null } if (project == null) { val changes = changedApplicationFiles synchronized (changes) { changes.add(storage) } } else { var changes = CHANGED_FILES_KEY.get(project) if (changes == null) { changes = MultiMap.createLinkedSet() CHANGED_FILES_KEY.set(project, changes) } synchronized (changes) { changes.putValue(componentManager.stateStore as ComponentStoreImpl, storage) } } if (storage is StateStorageBase<*>) { storage.disableSaving() } if (isReloadUnblocked()) { changedFilesAlarm.cancelAndRequest() } } internal fun registerChangedScheme(event: SchemeChangeEvent, schemeFileTracker: SchemeFileTracker, project: Project) { if (LOG.isDebugEnabled) { LOG.debug("[RELOAD] Registering scheme to reload: $event", Exception()) } var changes = CHANGED_SCHEMES_KEY.get(project) if (changes == null) { changes = MultiMap.createLinkedSet() CHANGED_SCHEMES_KEY.set(project, changes) } synchronized(changes) { changes.putValue(schemeFileTracker, event) } if (isReloadUnblocked()) { changedFilesAlarm.cancelAndRequest() } } private fun tryToReloadApplication(): Boolean { if (ApplicationManager.getApplication().isDisposed) { return false } if (changedApplicationFiles.isEmpty()) { return true } val changes = LinkedHashSet<StateStorage>(changedApplicationFiles) changedApplicationFiles.clear() return reloadAppStore(changes) } } fun reloadAppStore(changes: Set<StateStorage>): Boolean { val status = reloadStore(changes, ApplicationManager.getApplication().stateStore as ComponentStoreImpl) if (status == ReloadComponentStoreStatus.RESTART_AGREED) { ApplicationManagerEx.getApplicationEx().restart(true) return false } else { return status == ReloadComponentStoreStatus.SUCCESS || status == ReloadComponentStoreStatus.RESTART_CANCELLED } } internal fun reloadStore(changedStorages: Set<StateStorage>, store: ComponentStoreImpl): ReloadComponentStoreStatus { val notReloadableComponents: Collection<String>? var willBeReloaded = false try { try { notReloadableComponents = store.reload(changedStorages) } catch (e: Throwable) { LOG.warn(e) AppUIUtil.invokeOnEdt { Messages.showWarningDialog(ProjectBundle.message("project.reload.failed", e.message), ProjectBundle.message("project.reload.failed.title")) } return ReloadComponentStoreStatus.ERROR } if (notReloadableComponents == null || notReloadableComponents.isEmpty()) { return ReloadComponentStoreStatus.SUCCESS } willBeReloaded = askToRestart(store, notReloadableComponents, changedStorages, store.project == null) return if (willBeReloaded) ReloadComponentStoreStatus.RESTART_AGREED else ReloadComponentStoreStatus.RESTART_CANCELLED } finally { if (!willBeReloaded) { for (storage in changedStorages) { if (storage is StateStorageBase<*>) { storage.enableSaving() } } } } } // used in settings repository plugin fun askToRestart(store: IComponentStore, notReloadableComponents: Collection<String>, changedStorages: Set<StateStorage>?, isApp: Boolean): Boolean { val message = StringBuilder() val storeName = if (store is IProjectStore) "Project '${store.projectName}'" else "Application" message.append(storeName).append(' ') message.append("components were changed externally and cannot be reloaded:\n\n") var count = 0 for (component in notReloadableComponents) { if (count == 10) { message.append('\n').append("and ").append(notReloadableComponents.size - count).append(" more").append('\n') } else { message.append(component).append('\n') count++ } } message.append("\nWould you like to ") if (isApp) { message.append(if (ApplicationManager.getApplication().isRestartCapable) "restart" else "shutdown").append(' ') message.append(ApplicationNamesInfo.getInstance().productName).append('?') } else { message.append("reload project?") } if (Messages.showYesNoDialog(message.toString(), "$storeName Files Changed", Messages.getQuestionIcon()) == Messages.YES) { if (changedStorages != null) { for (storage in changedStorages) { if (storage is StateStorageBase<*>) { storage.disableSaving() } } } return true } return false } enum class ReloadComponentStoreStatus { RESTART_AGREED, RESTART_CANCELLED, ERROR, SUCCESS }
apache-2.0
57438df8f0fdcfa3cfd91822f6c8ae27
33.869565
149
0.718514
4.966557
false
true
false
false
czyzby/gdx-setup
src/main/kotlin/com/github/czyzby/setup/data/templates/unofficial/autumnMvcBox2d.kt
2
80686
package com.github.czyzby.setup.data.templates.unofficial import com.github.czyzby.setup.data.files.CopiedFile import com.github.czyzby.setup.data.files.SourceFile import com.github.czyzby.setup.data.files.path import com.github.czyzby.setup.data.libs.official.Box2D import com.github.czyzby.setup.data.libs.official.Controllers import com.github.czyzby.setup.data.platforms.Assets import com.github.czyzby.setup.data.platforms.Core import com.github.czyzby.setup.data.project.Project import com.github.czyzby.setup.views.ProjectTemplate /** * Advanced Autumn MVC template showing VisUI, Controllers and Box2D usage. * @author MJ */ @ProjectTemplate class AutumnMvcBox2dTemplate : AutumnMvcVisTemplate() { override val id = "autumnMvcBox2dTemplate" override val description: String get() = "Project template included launchers with [Autumn](https://github.com/czyzby/gdx-lml/tree/master/autumn) class scanners and an [Autumn MVC](https://github.com/czyzby/gdx-lml/tree/master/mvc) application showing usage of Box2D and Controllers LibGDX extensions. A simple GUI consisting of several screens and dialogs was provided, including a settings view that allows the players to choose their controls." override fun apply(project: Project) { super.apply(project) // Adding extra dependencies: Box2D().initiate(project) Controllers().initiate(project) } override fun addResources(project: Project) { // Adding music theme: project.files.add(CopiedFile(projectName = Assets.ID, path = path("music", "theme.ogg"), original = path("generator", "templates", "autumn", "theme.ogg"))) // Adding I18N bundle: arrayOf("", "_en", "_pl").forEach { val fileName = "bundle${it}.properties" project.files.add(CopiedFile(projectName = Assets.ID, path = path("i18n", fileName), original = path("generator", "templates", "autumn", "box2d", fileName))) } // Adding LML views: arrayOf("game.lml", "loading.lml", "menu.lml").forEach { project.files.add(CopiedFile(projectName = Assets.ID, path = path("ui", "templates", it), original = path("generator", "templates", "autumn", "box2d", it))) } arrayOf("controls.lml", "edit.lml", "inactive.lml", "settings.lml", "switch.lml").forEach { project.files.add(CopiedFile(projectName = Assets.ID, path = path("ui", "templates", "dialogs", it), original = path("generator", "templates", "autumn", "box2d", "dialogs", it))) } project.files.add(CopiedFile(projectName = Assets.ID, path = path("ui", "templates", "macros", "global.lml"), original = path("generator", "templates", "autumn", "box2d", "macros", "global.lml"))) } override fun addSources(project: Project) { project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.configuration", fileName = "Configuration.java", content = """package ${project.basic.rootPackage}.configuration; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.github.czyzby.autumn.annotation.Component; import com.github.czyzby.autumn.annotation.Initiate; import com.github.czyzby.autumn.mvc.component.ui.InterfaceService; import com.github.czyzby.autumn.mvc.component.ui.SkinService; import com.github.czyzby.autumn.mvc.component.ui.controller.ViewResizer; import com.github.czyzby.autumn.mvc.stereotype.preference.AvailableLocales; import com.github.czyzby.autumn.mvc.stereotype.preference.I18nBundle; import com.github.czyzby.autumn.mvc.stereotype.preference.I18nLocale; import com.github.czyzby.autumn.mvc.stereotype.preference.LmlMacro; import com.github.czyzby.autumn.mvc.stereotype.preference.LmlParserSyntax; import com.github.czyzby.autumn.mvc.stereotype.preference.Preference; import com.github.czyzby.autumn.mvc.stereotype.preference.sfx.MusicEnabled; import com.github.czyzby.autumn.mvc.stereotype.preference.sfx.MusicVolume; import com.github.czyzby.autumn.mvc.stereotype.preference.sfx.SoundEnabled; import com.github.czyzby.autumn.mvc.stereotype.preference.sfx.SoundVolume; import com.github.czyzby.kiwi.util.gdx.scene2d.Actors; import com.github.czyzby.lml.parser.LmlSyntax; import com.github.czyzby.lml.vis.parser.impl.VisLmlSyntax; import com.kotcrab.vis.ui.VisUI; /** Thanks to the Component annotation, this class will be automatically found and processed. * * This is a utility class that configures application settings. */ @Component public class Configuration { /** Name of the application's preferences file. */ public static final String PREFERENCES = "${project.basic.name}"; /** Max players amount. */ public static final int PLAYERS_AMOUNT = 3; /** Path to global macro file. */ @LmlMacro private final String globalMacro = "ui/templates/macros/global.lml"; /** Path to the internationalization bundle. */ @I18nBundle private final String bundlePath = "i18n/bundle"; /** Enabling VisUI usage. */ @LmlParserSyntax private final LmlSyntax syntax = new VisLmlSyntax(); /** These sound-related fields allow MusicService to store settings in preferences file. Sound preferences will be * automatically saved when the application closes and restored the next time it's turned on. Sound-related methods * methods will be automatically added to LML templates - see settings.lml template. */ @SoundVolume(preferences = PREFERENCES) private final String soundVolume = "soundVolume"; @SoundEnabled(preferences = PREFERENCES) private final String soundEnabled = "soundOn"; @MusicVolume(preferences = PREFERENCES) private final String musicVolume = "musicVolume"; @MusicEnabled(preferences = PREFERENCES) private final String musicEnabledPreference = "musicOn"; /** These i18n-related fields will allow LocaleService to save game's locale in preferences file. Locale changing * actions will be automatically added to LML templates - see settings.lml template. */ @I18nLocale(propertiesPath = PREFERENCES, defaultLocale = "en") private final String localePreference = "locale"; @AvailableLocales private final String[] availableLocales = new String[] { "en", "pl" }; /** Setting the default Preferences object path. */ @Preference private final String preferencesPath = PREFERENCES; /** Thanks to the Initiate annotation, this method will be automatically invoked during context building. All * method's parameters will be injected with values from the context. * * @param skinService contains GUI skin. */ @Initiate public void initiateConfiguration(final SkinService skinService) { // Loading default VisUI skin with the selected scale: VisUI.load(VisUI.SkinScale.X2); // Registering VisUI skin with "default" name - this skin will be the default one for all LML widgets: skinService.addSkin("default", VisUI.getSkin()); // Changing the default resizer - centering actors on resize. InterfaceService.DEFAULT_VIEW_RESIZER = new ViewResizer() { @Override public void resize(final Stage stage, final int width, final int height) { stage.getViewport().update(width, height, true); for (final Actor actor : stage.getActors()) { Actors.centerActor(actor); } } }; } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.configuration.preferences", fileName = "ControlsData.java", content = """package ${project.basic.rootPackage}.configuration.preferences; import ${project.basic.rootPackage}.service.controls.ControlType; /** JSON-encoded class. Uses public fields to support LibGDX JSON utilities. */ public class ControlsData { /** Up movement shortcut. */ public int up; /** Down movement shortcut. */ public int down; /** Left movement shortcut. */ public int left; /** Right movement shortcut. */ public int right; /** Jump shortcut. */ public int jump; /** Type of controls */ public ControlType type; /** Additional data. Might be used for device ID. */ public int index; /** Optional settings. Might not be supported by every controller. */ public boolean invertX, invertY, invertXY; public ControlsData() { } public ControlsData(final ControlType type) { this.type = type; } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.configuration.preferences", fileName = "ControlsPreference.java", content = """package ${project.basic.rootPackage}.configuration.preferences; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Base64Coder; import com.badlogic.gdx.utils.Json; import com.github.czyzby.autumn.mvc.component.preferences.dto.AbstractPreference; import com.github.czyzby.autumn.mvc.stereotype.preference.Property; import com.github.czyzby.kiwi.util.gdx.GdxUtilities; import com.github.czyzby.kiwi.util.gdx.collection.GdxArrays; import ${project.basic.rootPackage}.configuration.Configuration; import ${project.basic.rootPackage}.service.controls.ControlType; import ${project.basic.rootPackage}.service.controls.impl.KeyboardControl; import ${project.basic.rootPackage}.service.controls.impl.TouchControl; /** Allows to save controls in preferences. */ @Property("Controls") public class ControlsPreference extends AbstractPreference<Array<ControlsData>> { private final Json json = new Json(); @Override public Array<ControlsData> getDefault() { final Array<ControlsData> controls = GdxArrays.newArray(); // First player defaults to touch (on mobile) or keyboard (on desktop) controls. controls.add(GdxUtilities.isMobile() ? new TouchControl().toData() : new KeyboardControl().toData()); for (int index = 1; index < Configuration.PLAYERS_AMOUNT; index++) { // Other players are simply inactive: controls.add(new ControlsData(ControlType.INACTIVE)); } return controls; } @Override public Array<ControlsData> extractFromActor(final Actor actor) { throw new UnsupportedOperationException(); } @Override @SuppressWarnings("unchecked") protected Array<ControlsData> convert(final String rawPreference) { return json.fromJson(Array.class, ControlsData.class, Base64Coder.decodeString(rawPreference)); } @Override protected String serialize(final Array<ControlsData> preference) { return Base64Coder.encodeString(json.toJson(preference, Array.class, ControlsData.class)); } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.controller", fileName = "GameController.java", content = """package ${project.basic.rootPackage}.controller; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.github.czyzby.autumn.annotation.Inject; import com.github.czyzby.autumn.mvc.component.ui.controller.ViewRenderer; import com.github.czyzby.autumn.mvc.component.ui.controller.ViewResizer; import com.github.czyzby.autumn.mvc.component.ui.controller.impl.StandardViewShower; import com.github.czyzby.autumn.mvc.stereotype.View; import ${project.basic.rootPackage}.service.Box2DService; /** Renders Box2D world. */ @View(id = "game", value = "ui/templates/game.lml", themes = "music/theme.ogg") public class GameController extends StandardViewShower implements ViewResizer, ViewRenderer { @Inject private Box2DService box2d; private final Box2DDebugRenderer renderer = new Box2DDebugRenderer(); @Override public void show(final Stage stage, final Action action) { box2d.create(); super.show(stage, Actions.sequence(action, Actions.run(new Runnable() { @Override public void run() { // Listening to user input events: final InputMultiplexer inputMultiplexer = new InputMultiplexer(stage); box2d.initiateControls(inputMultiplexer); Gdx.input.setInputProcessor(inputMultiplexer); } }))); } @Override public void resize(final Stage stage, final int width, final int height) { box2d.resize(width, height); stage.getViewport().update(width, height, true); } @Override public void render(final Stage stage, final float delta) { box2d.update(delta); renderer.render(box2d.getWorld(), box2d.getViewport().getCamera().combined); stage.act(delta); stage.draw(); } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.controller", fileName = "LoadingController.java", content = """package ${project.basic.rootPackage}.controller; import com.badlogic.gdx.scenes.scene2d.Stage; import com.github.czyzby.autumn.annotation.Inject; import com.github.czyzby.autumn.mvc.component.asset.AssetService; import com.github.czyzby.autumn.mvc.component.ui.controller.ViewRenderer; import com.github.czyzby.autumn.mvc.stereotype.View; import com.github.czyzby.lml.annotation.LmlActor; import com.kotcrab.vis.ui.widget.VisProgressBar; /** Thanks to View annotation, this class will be automatically found and initiated. * * This is the first application's view, shown right after the application starts. It will hide after all assests are * loaded. */ @View(value = "ui/templates/loading.lml", first = true) public class LoadingController implements ViewRenderer { /** Will be injected automatically. Manages assets. Used to display loading progress. */ @Inject private AssetService assetService; /** This is a widget injected from the loading.lml template. "loadingBar" is its ID. */ @LmlActor("loadingBar") private VisProgressBar loadingBar; // Since this class implements ViewRenderer, it can modify the way its view is drawn. Additionally to drawing the // stage, this view also updates assets manager and reads its progress. @Override public void render(final Stage stage, final float delta) { assetService.update(); loadingBar.setValue(assetService.getLoadingProgress()); stage.act(delta); stage.draw(); } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.controller", fileName = "MenuController.java", content = """package ${project.basic.rootPackage}.controller; import com.badlogic.gdx.utils.Array; import com.github.czyzby.autumn.annotation.Inject; import com.github.czyzby.autumn.mvc.component.ui.InterfaceService; import com.github.czyzby.autumn.mvc.stereotype.View; import com.github.czyzby.lml.annotation.LmlAction; import com.github.czyzby.lml.parser.action.ActionContainer; import ${project.basic.rootPackage}.controller.dialog.NotEnoughPlayersErrorController; import ${project.basic.rootPackage}.service.ControlsService; import ${project.basic.rootPackage}.service.controls.Control; /** Thanks to View annotation, this class will be automatically found and initiated. * * This is application's main view, displaying a menu with several options. */ @View(id = "menu", value = "ui/templates/menu.lml", themes = "music/theme.ogg") public class MenuController implements ActionContainer { @Inject private InterfaceService interfaceService; @Inject private ControlsService controlsService; @LmlAction("startGame") public void startPlaying() { if (isAnyPlayerActive()) { interfaceService.show(GameController.class); } else { interfaceService.showDialog(NotEnoughPlayersErrorController.class); } } private boolean isAnyPlayerActive() { final Array<Control> controls = controlsService.getControls(); for (final Control control : controls) { if (control.isActive()) { return true; } } return false; } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.controller.action", fileName = "Global.java", content = """package ${project.basic.rootPackage}.controller.action; import com.github.czyzby.autumn.mvc.stereotype.ViewActionContainer; import com.github.czyzby.kiwi.util.gdx.GdxUtilities; import com.github.czyzby.lml.annotation.LmlAction; import com.github.czyzby.lml.parser.action.ActionContainer; import ${project.basic.rootPackage}.configuration.Configuration; /** Since this class implements ActionContainer and is annotated with ViewActionContainer, its methods will be reflected * and available in all LML templates. Note that this class is a component like any other, so it can inject any fields, * use Initiate-annotated methods, etc. */ @ViewActionContainer("global") public class Global implements ActionContainer { /** This is a mock-up method that does nothing. It will be available in LML templates through "close" (annotation * argument) and "noOp" (method name) IDs. */ @LmlAction("close") public void noOp() { } /** @return true if the game is currently running on a mobile platform. */ @LmlAction("isMobile") public boolean isOnMobilePlatform() { return GdxUtilities.isMobile(); } /** @return total amount of playable characters. */ @LmlAction("playersAmount") public int getPlayersAmount() { return Configuration.PLAYERS_AMOUNT; } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.controller.dialog", fileName = "ControlsController.java", content = """package ${project.basic.rootPackage}.controller.dialog; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.Window; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectMap; import com.github.czyzby.autumn.annotation.Inject; import com.github.czyzby.autumn.mvc.component.ui.InterfaceService; import com.github.czyzby.autumn.mvc.component.ui.controller.ViewDialogShower; import com.github.czyzby.autumn.mvc.stereotype.ViewDialog; import com.github.czyzby.lml.annotation.LmlAction; import com.github.czyzby.lml.annotation.LmlActor; import com.github.czyzby.lml.parser.action.ActionContainer; import com.github.czyzby.lml.util.LmlUtilities; import ${project.basic.rootPackage}.configuration.Configuration; import ${project.basic.rootPackage}.service.ControlsService; import ${project.basic.rootPackage}.service.controls.Control; /** Allows to set up player controls. */ @ViewDialog(id = "controls", value = "ui/templates/dialogs/controls.lml", cacheInstance = true) public class ControlsController implements ActionContainer, ViewDialogShower { @Inject ControlsService service; @Inject ControlsEditController controlsEdit; @Inject ControlsSwitchController controlsSwitch; @Inject InterfaceService interfaceService; /** Controller edition buttons mapped by their in-view IDs. */ @LmlActor("edit[0," + (Configuration.PLAYERS_AMOUNT - 1) + "]") private ObjectMap<String, Button> editButtons; @Override public void doBeforeShow(final Window dialog) { final Array<Control> controls = service.getControls(); for (int index = 0; index < Configuration.PLAYERS_AMOUNT; index++) { refreshPlayerView(index, controls.get(index)); } } /** @param control belongs to the player. Should be called after the control is switched. * @param playerId ID of the player to refresh. */ public void refreshPlayerView(final int playerId, final Control control) { final String editId = "edit" + playerId; if (control.isActive()) { editButtons.get(editId).setDisabled(false); } else { editButtons.get(editId).setDisabled(true); } } @LmlAction("edit") public void editControls(final Actor actor) { final int playerId = Integer.parseInt(LmlUtilities.getActorId(actor).replace("edit", "")); controlsEdit.setControl(service.getControl(playerId)); interfaceService.showDialog(ControlsEditController.class); } @LmlAction("switch") public void switchControls(final Actor actor) { final int playerId = Integer.parseInt(LmlUtilities.getActorId(actor).replace("switch", "")); controlsSwitch.setPlayerId(playerId); interfaceService.showDialog(ControlsSwitchController.class); } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.controller.dialog", fileName = "ControlsEditController.java", content = """package ${project.basic.rootPackage}.controller.dialog; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.controllers.Controller; import com.badlogic.gdx.controllers.ControllerAdapter; import com.badlogic.gdx.controllers.ControllerListener; import com.badlogic.gdx.controllers.Controllers; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.Window; import com.badlogic.gdx.scenes.scene2d.utils.Layout; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectMap; import com.github.czyzby.autumn.mvc.component.ui.controller.ViewDialogShower; import com.github.czyzby.autumn.mvc.stereotype.ViewDialog; import com.github.czyzby.autumn.mvc.stereotype.ViewStage; import com.github.czyzby.kiwi.util.common.Strings; import com.github.czyzby.kiwi.util.gdx.scene2d.range.FloatRange; import com.github.czyzby.lml.annotation.LmlAction; import com.github.czyzby.lml.annotation.LmlActor; import com.github.czyzby.lml.parser.action.ActionContainer; import ${project.basic.rootPackage}.service.controls.Control; import ${project.basic.rootPackage}.service.controls.ControlListener; import ${project.basic.rootPackage}.service.controls.ControlType; import ${project.basic.rootPackage}.service.controls.impl.GamePadControl; import ${project.basic.rootPackage}.service.controls.impl.KeyboardControl; import com.kotcrab.vis.ui.widget.VisSelectBox; /** Allows to edit chosen controls. */ @ViewDialog(id = "edit", value = "ui/templates/dialogs/edit.lml", cacheInstance = true) public class ControlsEditController implements ActionContainer, ViewDialogShower { @ViewStage private Stage stage; private Control control; @LmlActor("mock") private Image mockUpEntity; @LmlActor("mainTable") private Table mainTable; @LmlActor("TOUCH;KEYBOARD;PAD") private ObjectMap<String, Actor> views; private TextButton checkedButton; private final MockUpdateAction updateAction = new MockUpdateAction(); // Keyboard widgets: @LmlActor("keyUp") private TextButton keyUp; @LmlActor("keyDown") private TextButton keyDown; @LmlActor("keyLeft") private TextButton keyLeft; @LmlActor("keyRight") private TextButton keyRight; @LmlActor("keyJump") private TextButton keyJump; private final Actor keyboardListener = new Actor(); // Game pad widgets: @LmlActor("padUp") private TextButton padUp; @LmlActor("padDown") private TextButton padDown; @LmlActor("padLeft") private TextButton padLeft; @LmlActor("padRight") private TextButton padRight; @LmlActor("padJump") private TextButton padJump; private final ControllerListener controllerListener; @LmlActor("invertX") private Button invertXButton; @LmlActor("invertY") private Button invertYButton; @LmlActor("invertXY") private Button invertXYButton; @LmlActor("controllers") private VisSelectBox<String> controllersSelect; private Array<Controller> controllers; public ControlsEditController() { // Allows to change current keyboard controls: keyboardListener.addListener(new InputListener() { @Override public boolean keyUp(final InputEvent event, final int keycode) { if (checkedButton == null) { keyboardListener.remove(); return false; } final KeyboardControl keyboardControl = (KeyboardControl) control; if (checkedButton == keyUp) { keyboardControl.setUp(keycode); } else if (checkedButton == keyDown) { keyboardControl.setDown(keycode); } else if (checkedButton == keyLeft) { keyboardControl.setLeft(keycode); } else if (checkedButton == keyRight) { keyboardControl.setRight(keycode); } else if (checkedButton == keyJump) { keyboardControl.setJump(keycode); } checkedButton.setText(Keys.toString(keycode)); checkedButton.setChecked(false); checkedButton = null; keyboardListener.remove(); return false; } }); // Allows to change controller shortcuts: controllerListener = new ControllerAdapter() { @Override public boolean buttonUp(final Controller controller, final int buttonIndex) { if (checkedButton == null) { controller.removeListener(controllerListener); return false; } final GamePadControl keyboardControl = (GamePadControl) control; if (checkedButton == padUp) { keyboardControl.setUp(buttonIndex); } else if (checkedButton == padDown) { keyboardControl.setDown(buttonIndex); } else if (checkedButton == padLeft) { keyboardControl.setLeft(buttonIndex); } else if (checkedButton == padRight) { keyboardControl.setRight(buttonIndex); } else if (checkedButton == padJump) { keyboardControl.setJump(buttonIndex); } checkedButton.setText(String.valueOf(buttonIndex)); checkedButton.setChecked(false); checkedButton = null; controller.removeListener(controllerListener); return false; } }; } /** @param control will be edited by this screen. */ public void setControl(final Control control) { this.control = control; } @Override public void doBeforeShow(final Window dialog) { attachListeners(); setCurrentControls(); changeView(); updateAction.reset(); mockUpEntity.setColor(Color.WHITE); mockUpEntity.addAction(Actions.forever(updateAction)); } private void attachListeners() { // Allowing controls to listen to input: final InputMultiplexer inputMultiplexer = new InputMultiplexer(); control.attachInputListener(inputMultiplexer); control.setControlListener(new ControlListener() { @Override public void jump() { mockUpEntity.addAction(Actions.sequence(Actions.fadeOut(0.1f), Actions.fadeIn(0.1f))); } }); inputMultiplexer.addProcessor(stage); Gdx.input.setInputProcessor(inputMultiplexer); } private void setCurrentControls() { if (control.getType() == ControlType.KEYBOARD) { final KeyboardControl keyboardControl = (KeyboardControl) control; keyUp.setText(Keys.toString(keyboardControl.getUp())); keyDown.setText(Keys.toString(keyboardControl.getDown())); keyLeft.setText(Keys.toString(keyboardControl.getLeft())); keyRight.setText(Keys.toString(keyboardControl.getRight())); keyJump.setText(Keys.toString(keyboardControl.getJump())); } else if (control.getType() == ControlType.PAD) { final GamePadControl gamePadControl = (GamePadControl) control; padUp.setText(String.valueOf(gamePadControl.getUp())); padDown.setText(String.valueOf(gamePadControl.getDown())); padLeft.setText(String.valueOf(gamePadControl.getLeft())); padRight.setText(String.valueOf(gamePadControl.getRight())); padJump.setText(String.valueOf(gamePadControl.getJump())); invertXButton.setChecked(gamePadControl.isInvertX()); invertYButton.setChecked(gamePadControl.isInvertY()); invertXYButton.setChecked(gamePadControl.isInvertXY()); // Allowing the player to choose controller device: controllersSelect.getItems().clear(); controllersSelect.getSelection().setMultiple(false); controllersSelect.getSelection().setRequired(true); controllers = Controllers.getControllers(); final String[] items = new String[controllers.size]; for (int index = 0; index < controllers.size; index++) { final Controller controller = controllers.get(index); items[index] = controller.getName().replaceAll(Strings.WHITESPACE_SPLITTER_REGEX, " "); } controllersSelect.setItems(items); final int controllerIndex = controllers.indexOf(gamePadControl.getController(), true); controllersSelect.setSelectedIndex(controllerIndex < 0 ? 0 : controllerIndex); } } private void changeView() { mainTable.clearChildren(); // Finding view relevant to the controls: final Actor view = views.get(control.getType().name()); mainTable.add(view).grow(); mainTable.pack(); } @LmlAction("hide") public void hide() { mockUpEntity.clearActions(); keyboardListener.remove(); if (checkedButton != null) { checkedButton.setChecked(false); checkedButton = null; } if (control.getType() == ControlType.PAD) { ((GamePadControl) control).getController().removeListener(controllerListener); } Gdx.input.setInputProcessor(stage); } @LmlAction("setKey") public void setKeyboardShortcut(final TextButton button) { if (button.isChecked()) { if (checkedButton != null) { checkedButton.setChecked(false); } checkedButton = button; stage.addActor(keyboardListener); stage.setKeyboardFocus(keyboardListener); } else { checkedButton = null; keyboardListener.remove(); } } @LmlAction("setPad") public void setGamePadShortcut(final TextButton button) { final GamePadControl gamePadControl = (GamePadControl) control; if (button.isChecked()) { if (checkedButton != null) { checkedButton.setChecked(false); } checkedButton = button; gamePadControl.getController().addListener(controllerListener); } else { checkedButton = null; gamePadControl.getController().removeListener(controllerListener); } } @LmlAction("changeController") public void changeController(final VisSelectBox<String> select) { if (select.getSelectedIndex() < 0) { return; } final Controller controller = controllers.get(select.getSelectedIndex()); ((GamePadControl) control).setController(controller); control.attachInputListener(null); } @LmlAction("invertX") public void setInvertX(final Button button) { ((GamePadControl) control).setInvertX(button.isChecked()); } @LmlAction("invertY") public void setInvertY(final Button button) { ((GamePadControl) control).setInvertY(button.isChecked()); } @LmlAction("invertXY") public void setInvertXY(final Button button) { ((GamePadControl) control).setInvertXY(button.isChecked()); } /** Updates position of mock up entity. */ private class MockUpdateAction extends Action { private final FloatRange x = new FloatRange(0f, 0.2f); // 0.2 is transition length (smoothness). private final FloatRange y = new FloatRange(0f, 0.2f); private float parentSize; private float size; private final Vector2 position = new Vector2(); @Override public void reset() { parentSize = ((Layout) mockUpEntity.getParent()).getPrefWidth(); size = mockUpEntity.getWidth(); x.setCurrentValue(getX() * (parentSize - size)); y.setCurrentValue(getY() * (parentSize - size)); act(0f); } @Override public boolean act(final float delta) { x.setTargetValue(getX() * (parentSize - size)); y.setTargetValue(getY() * (parentSize - size)); x.update(delta); y.update(delta); position.set(mockUpEntity.getParent().getX() + (parentSize - size) / 2f, mockUpEntity.getParent().getY() + (parentSize - size) / 2f); mockUpEntity.getParent().localToStageCoordinates(position); control.update(stage.getViewport(), position.x, position.y); mockUpEntity.setPosition(x.getCurrentValue(), y.getCurrentValue()); return false; } // X and Y are in range of [-1, 1] - converting to [0, 1]. private float getX() { return (control.getMovementDirection().x + 1f) / 2f; } private float getY() { return (control.getMovementDirection().y + 1f) / 2f; } } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.controller.dialog", fileName = "ControlsSwitchController.java", content = """package ${project.basic.rootPackage}.controller.dialog; import com.badlogic.gdx.controllers.Controller; import com.badlogic.gdx.controllers.Controllers; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.Window; import com.badlogic.gdx.utils.Array; import com.github.czyzby.autumn.annotation.Inject; import com.github.czyzby.autumn.mvc.component.ui.InterfaceService; import com.github.czyzby.autumn.mvc.component.ui.controller.ViewDialogShower; import com.github.czyzby.autumn.mvc.stereotype.ViewDialog; import com.github.czyzby.kiwi.util.gdx.GdxUtilities; import com.github.czyzby.kiwi.util.gdx.collection.GdxArrays; import com.github.czyzby.lml.annotation.LmlAction; import com.github.czyzby.lml.annotation.LmlActor; import com.github.czyzby.lml.parser.action.ActionContainer; import ${project.basic.rootPackage}.service.ControlsService; import ${project.basic.rootPackage}.service.controls.Control; import ${project.basic.rootPackage}.service.controls.ControlType; import ${project.basic.rootPackage}.service.controls.impl.GamePadControl; import ${project.basic.rootPackage}.service.controls.impl.InactiveControl; import ${project.basic.rootPackage}.service.controls.impl.KeyboardControl; import ${project.basic.rootPackage}.service.controls.impl.TouchControl; /** Allows to switch control types. */ @ViewDialog(id = "switch", value = "ui/templates/dialogs/switch.lml", cacheInstance = true) public class ControlsSwitchController implements ActionContainer, ViewDialogShower { @Inject private ControlsService service; @Inject private InterfaceService interfaceService; @Inject private ControlsController controlsController; @Inject private ControlsEditController editController; @LmlActor("PAD") private Button gamePadControlButton; private int playerId; /** @param playerId this screen will be used to choose controls for this player. */ public void setPlayerId(final int playerId) { this.playerId = playerId; } @Override public void doBeforeShow(final Window dialog) { gamePadControlButton.setDisabled(GdxArrays.isEmpty(Controllers.getControllers())); } @LmlAction("controls") public Iterable<ControlType> getControlTypes() { if (GdxUtilities.isRunningOnAndroid()) { // Keyboard controls on Android do not work well... return GdxArrays.newArray(ControlType.TOUCH, ControlType.PAD, ControlType.INACTIVE); } else if (GdxUtilities.isRunningOnIOS()) { // Controllers (pads) do not exactly work on iOS. return GdxArrays.newArray(ControlType.TOUCH, ControlType.INACTIVE); } // Desktop supports all controllers: return GdxArrays.newArray(ControlType.values()); } @LmlAction("TOUCH") public void setTouchControls() { changeControls(new TouchControl()); } @LmlAction("INACTIVE") public void setInactiveControls() { changeControls(new InactiveControl()); } @LmlAction("KEYBOARD") public void setKeyboardControls() { changeControls(new KeyboardControl()); } @LmlAction("PAD") public void setGamePadControls() { final Array<Controller> controllers = Controllers.getControllers(); if (GdxArrays.isEmpty(controllers)) { changeControls(new InactiveControl()); } else { changeControls(new GamePadControl(controllers.first())); } } private void changeControls(final Control control) { service.setControl(playerId, control); controlsController.refreshPlayerView(playerId, control); if (control.isActive()) { editController.setControl(control); interfaceService.showDialog(ControlsEditController.class); } } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.controller.dialog", fileName = "NotEnoughPlayersErrorController.java", content = """package ${project.basic.rootPackage}.controller.dialog; import com.github.czyzby.autumn.mvc.stereotype.ViewDialog; /** Shown when there are no players with active controls. */ @ViewDialog(id = "inactive", value = "ui/templates/dialogs/inactive.lml", cacheInstance = true) public class NotEnoughPlayersErrorController { }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.controller.dialog", fileName = "SettingsController.java", content = """package ${project.basic.rootPackage}.controller.dialog; import com.badlogic.gdx.Graphics.DisplayMode; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectSet; import com.github.czyzby.autumn.annotation.Inject; import com.github.czyzby.autumn.mvc.stereotype.ViewDialog; import com.github.czyzby.kiwi.util.gdx.collection.GdxArrays; import com.github.czyzby.kiwi.util.gdx.collection.GdxSets; import com.github.czyzby.lml.annotation.LmlAction; import com.github.czyzby.lml.parser.action.ActionContainer; import com.github.czyzby.lml.util.LmlUtilities; import ${project.basic.rootPackage}.service.FullscreenService; /** This is a settings dialog, which can be shown in any view by using "show:settings" LML action or - in Java code - * through InterfaceService.showDialog(Class) method. Thanks to the fact that it implements ActionContainer, its methods * will be available in the LML template. */ @ViewDialog(id = "settings", value = "ui/templates/dialogs/settings.lml", cacheInstance = true) public class SettingsController implements ActionContainer { @Inject private FullscreenService fullscreenService; /** @return array of serialized display modes' names. */ @LmlAction("displayModes") public Array<String> getDisplayModes() { final ObjectSet<String> alreadyAdded = GdxSets.newSet(); // Removes duplicates. final Array<String> displayModes = GdxArrays.newArray(); // Keeps display modes sorted. for (final DisplayMode mode : fullscreenService.getDisplayModes()) { final String modeName = fullscreenService.serialize(mode); if (alreadyAdded.contains(modeName)) { continue; // Same size already added. } displayModes.add(modeName); alreadyAdded.add(modeName); } return displayModes; } /** @param actor its ID must match name of a display mode. */ @LmlAction("setFullscreen") public void setFullscreenMode(final Actor actor) { final String modeName = LmlUtilities.getActorId(actor); final DisplayMode mode = fullscreenService.deserialize(modeName); fullscreenService.setFullscreen(mode); } /** Attempts to return to the original window size. */ @LmlAction("resetFullscreen") public void setWindowedMode() { fullscreenService.resetFullscreen(); } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.entity", fileName = "Player.java", content = """package ${project.basic.rootPackage}.entity; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.utils.viewport.Viewport; import ${project.basic.rootPackage}.service.controls.Control; import ${project.basic.rootPackage}.service.controls.ControlListener; /** Represents a single player. */ public class Player implements ControlListener { private static final float DELAY = 0.75f; // Jump delay in seconds. private static final float SPEED = 750f; // Movement force. Affected by delta time. private static final float JUMP = 1000f; // Jump force. private final Control control; private final Body body; private final Viewport viewport; private boolean jumped; private float timeSinceLastJump = DELAY; public Player(final Control control, final Body body, final Viewport viewport) { this.control = control; this.body = body; this.viewport = viewport; control.setControlListener(this); } /** @return controls object that listens to player input. */ public Control getControl() { return control; } /** @return Box2D body representing the player. */ public Body getBody() { return body; } /** @param delta time since last update. */ public void update(final float delta) { control.update(viewport, body.getPosition().x, body.getPosition().y); timeSinceLastJump += delta; final Vector2 movement = control.getMovementDirection(); if (jumped && timeSinceLastJump > DELAY) { timeSinceLastJump = 0f; if (movement.x == 0f && movement.y == 0f) { body.applyForceToCenter(0f, JUMP, true); } else { body.applyForceToCenter(movement.x * JUMP, movement.y * JUMP, true); } } body.setActive(true); body.applyForceToCenter(movement.x * SPEED * delta, movement.y * SPEED * delta, true); jumped = false; } @Override public void jump() { jumped = true; } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.service", fileName = "Box2DService.java", content = """package ${project.basic.rootPackage}.service; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.ChainShape; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.viewport.StretchViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.github.czyzby.autumn.annotation.Component; import com.github.czyzby.autumn.annotation.Destroy; import com.github.czyzby.autumn.annotation.Inject; import com.github.czyzby.kiwi.util.gdx.collection.GdxArrays; import ${project.basic.rootPackage}.${project.basic.mainClass}; import ${project.basic.rootPackage}.configuration.Configuration; import ${project.basic.rootPackage}.entity.Player; import ${project.basic.rootPackage}.service.controls.Control; /** Manages 2D physics engine. */ @Component public class Box2DService { private static final Vector2 GRAVITY = new Vector2(0f, -9.81f); // Box2D world gravity vector. private static final float STEP = 1f / 30f; // Length of a single Box2D step. private static final float WIDTH = ${project.basic.mainClass}.WIDTH / 10f; // Width of Box2D world. private static final float HEIGHT = ${project.basic.mainClass}.HEIGHT / 10f; // Height of Box2D world. private static final float SIZE = 3f; // Size of players. @Inject private ControlsService controlsService; private World world; private float timeSinceUpdate; private final Viewport viewport = new StretchViewport(WIDTH, HEIGHT); private final Array<Player> players = GdxArrays.newArray(); /** Call this method to (re)create Box2D world according to current settings. */ public void create() { dispose(); world = new World(GRAVITY, true); createWorldBounds(); final Array<Control> controls = controlsService.getControls(); for (int index = 0; index < Configuration.PLAYERS_AMOUNT; index++) { final Control control = controls.get(index); if (control.isActive()) { players.add(new Player(control, getPlayerBody(index), viewport)); } } } /** Creates Box2D bounds. */ private void createWorldBounds() { final BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyType.StaticBody; final ChainShape shape = new ChainShape(); shape.createLoop(new float[] { -WIDTH / 2f, -HEIGHT / 2f + SIZE * 2f, -WIDTH / 2f, HEIGHT / 2f, WIDTH / 2f, HEIGHT / 2f, WIDTH / 2f, -HEIGHT / 2f + SIZE * 2f }); final FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = shape; world.createBody(bodyDef).createFixture(fixtureDef); shape.dispose(); } /** @param index ID of the player. Affects body size and position. * @return a new player body. */ private Body getPlayerBody(final int index) { final BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyType.DynamicBody; bodyDef.fixedRotation = false; final PolygonShape shape = new PolygonShape(); switch (index) { case 0: bodyDef.position.set(-WIDTH / 2f + SIZE * 2f, HEIGHT / 4f); // Square. shape.setAsBox(SIZE, SIZE); break; case 1: bodyDef.position.set(0f, HEIGHT / 4f); // Hexagon. Ish. shape.set(new float[] { -SIZE, 0f, -SIZE / 2f, SIZE, SIZE / 2f, SIZE, SIZE, 0f, SIZE / 2f, -SIZE, -SIZE / 2f, -SIZE, -SIZE, 0f }); break; default: bodyDef.position.set(WIDTH / 2f - SIZE * 2f, HEIGHT / 4f); // Triangle. shape.set(new float[] { -SIZE, -SIZE, 0f, SIZE, SIZE, -SIZE, -SIZE, -SIZE }); } final FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = shape; fixtureDef.restitution = 0.3f; fixtureDef.density = 0.05f; final Body body = world.createBody(bodyDef); body.createFixture(fixtureDef); shape.dispose(); return body; } /** @param delta time passed since last update. Will be used to update Box2D world. */ public void update(final float delta) { timeSinceUpdate += delta; while (timeSinceUpdate > STEP) { timeSinceUpdate -= STEP; world.step(STEP, 8, 3); for (final Player player : players) { player.update(STEP); } } } /** @param inputMultiplexer will listen to player input events. */ public void initiateControls(final InputMultiplexer inputMultiplexer) { for (final Player player : players) { player.getControl().attachInputListener(inputMultiplexer); } } /** @param width new screen width. * @param height new screen height. */ public void resize(final int width, final int height) { viewport.update(width, height); } /** @return direct reference to current Box2D world. Might be null. */ public World getWorld() { return world; } /** @return viewport with game coordinates. */ public Viewport getViewport() { return viewport; } @Destroy public void dispose() { players.clear(); if (world != null) { world.dispose(); world = null; } } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.service", fileName = "ControlsService.java", content = """package ${project.basic.rootPackage}.service; import com.badlogic.gdx.utils.Array; import com.github.czyzby.autumn.annotation.Component; import com.github.czyzby.autumn.annotation.Destroy; import com.github.czyzby.autumn.annotation.Initiate; import com.github.czyzby.autumn.annotation.Inject; import com.github.czyzby.autumn.mvc.config.AutumnActionPriority; import com.github.czyzby.kiwi.util.gdx.collection.GdxArrays; import ${project.basic.rootPackage}.configuration.Configuration; import ${project.basic.rootPackage}.configuration.preferences.ControlsData; import ${project.basic.rootPackage}.configuration.preferences.ControlsPreference; import ${project.basic.rootPackage}.service.controls.Control; /** Manages players' controls. */ @Component public class ControlsService { @Inject private ControlsPreference preference; private final Array<Control> controls = new Array<Control>(); @Initiate public void readControlsFromPreferences() { final Array<ControlsData> controlsPreferences = preference.get(); for (final ControlsData data : controlsPreferences) { controls.add(data.type.create(data)); } } @Destroy(priority = AutumnActionPriority.TOP_PRIORITY) public void saveControlsInPreferences() { final Array<ControlsData> controlsData = GdxArrays.newArray(Configuration.PLAYERS_AMOUNT); for (final Control control : controls) { controlsData.add(control.toData()); } controlsData.size = Configuration.PLAYERS_AMOUNT; preference.set(controlsData); } /** @param playerId ID of the player to check. * @return true if the player ID is valid and the player has an active controller attached. */ public boolean isActive(final int playerId) { return GdxArrays.isIndexValid(controls, playerId) && controls.get(playerId).isActive(); } /** @param playerId ID of the player. * @return controller assigned to the player. */ public Control getControl(final int playerId) { return controls.get(playerId); } /** @param playerId ID of the player. * @param control will be assigned to the selected player. */ public void setControl(final int playerId, final Control control) { controls.set(playerId, control); } /** @return controllers assigned to all players. Order matches players' IDs. */ public Array<Control> getControls() { return controls; } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.service", fileName = "FullscreenService.java", content = """package ${project.basic.rootPackage}.service; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Graphics.DisplayMode; import com.github.czyzby.autumn.annotation.Component; import com.github.czyzby.kiwi.util.common.Strings; import ${project.basic.rootPackage}.${project.basic.mainClass}; /** Handles fullscreen-related operations. */ @Component public class FullscreenService { /** @return supported fullscreen display modes. Utility method. */ public DisplayMode[] getDisplayModes() { return Gdx.graphics.getDisplayModes(); } /** @param displayMode will be converted to string. * @return passed mode converted to a string. */ public String serialize(final DisplayMode displayMode) { return displayMode.width + "x" + displayMode.height; } /** @param displayMode serialized display mode. See {@link #serialize(DisplayMode)}. * @return mode instance or null with selected size is not supported. */ public DisplayMode deserialize(final String displayMode) { final String[] sizes = Strings.split(displayMode, 'x'); final int width = Integer.parseInt(sizes[0]); final int height = Integer.parseInt(sizes[1]); for (final DisplayMode mode : Gdx.graphics.getDisplayModes()) { if (mode.width == width && mode.height == height) { return mode; } } return null; } /** @param displayMode must support fullscreen mode. */ public void setFullscreen(final DisplayMode displayMode) { if (Gdx.graphics.setFullscreenMode(displayMode)) { // Explicitly trying to resize the application listener to fully support all platforms: Gdx.app.getApplicationListener().resize(displayMode.width, displayMode.height); } } /** Tries to set windowed mode with initial screen size. */ public void resetFullscreen() { if (Gdx.graphics.setWindowedMode(${project.basic.mainClass}.WIDTH, ${project.basic.mainClass}.HEIGHT)) { // Explicitly trying to resize the application listener to fully support all platforms: Gdx.app.getApplicationListener().resize(${project.basic.mainClass}.WIDTH, ${project.basic.mainClass}.HEIGHT); } } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.service.controls", fileName = "AbstractButtonControl.java", content = """package ${project.basic.rootPackage}.service.controls; import com.badlogic.gdx.utils.IntSet; import com.badlogic.gdx.utils.viewport.Viewport; import ${project.basic.rootPackage}.configuration.preferences.ControlsData; /** Abstract base for controls that use buttons, like keyboard keys or game pads buttons. */ public abstract class AbstractButtonControl extends AbstractControl { protected IntSet pressedButtons = new IntSet(4); protected int up; protected int down; protected int left; protected int right; protected int jump; /** Updates current movement according to button states. */ protected void updateMovement() { if (pressedButtons.size == 0) { stop(); } else if (isPressed(up)) { if (isPressed(left)) { // Up-left. movement.set(-COS, SIN); } else if (isPressed(right)) { // Up-right. movement.set(COS, SIN); } else { // Up. movement.set(0f, 1f); } } else if (isPressed(down)) { if (isPressed(left)) { // Down-left. movement.set(-COS, -SIN); } else if (isPressed(right)) { // Down-right. movement.set(COS, -SIN); } else { // Down. movement.set(0f, -1f); } } else if (isPressed(left)) { // Left. movement.set(-1f, 0f); } else if (isPressed(right)) { // Right. movement.set(1f, 0f); } else { stop(); } } @Override public void update(final Viewport gameViewport, final float gameX, final float gameY) { // Button controls usually do not need relative position of controlled entity. } /** @param key button code. * @return true if button is currently pressed. */ protected boolean isPressed(final int key) { return pressedButtons.contains(key); } @Override public ControlsData toData() { final ControlsData data = new ControlsData(getType()); data.up = up; data.down = down; data.left = left; data.right = right; data.jump = jump; return data; } @Override public void copy(final ControlsData data) { up = data.up; down = data.down; left = data.left; right = data.right; jump = data.jump; } @Override public void reset() { super.reset(); pressedButtons.clear(); } /** @return up movement button code. */ public int getUp() { return up; } /** @param up will become up movement button code. */ public void setUp(final int up) { pressedButtons.remove(this.up); updateMovement(); this.up = up; } /** @return down movement button code. */ public int getDown() { return down; } /** @param down will become down movement button code. */ public void setDown(final int down) { pressedButtons.remove(this.down); updateMovement(); this.down = down; } /** @return left movement button code. */ public int getLeft() { return left; } /** @param left will become left movement button code. */ public void setLeft(final int left) { pressedButtons.remove(this.left); updateMovement(); this.left = left; } /** @return right movement button code. */ public int getRight() { return right; } /** @param right will become right movement button code. */ public void setRight(final int right) { pressedButtons.remove(this.right); updateMovement(); this.right = right; } /** @return jump button code. */ public int getJump() { return jump; } /** @param jump will become jump button code. */ public void setJump(final int jump) { this.jump = jump; } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.service.controls", fileName = "AbstractControl.java", content = """package ${project.basic.rootPackage}.service.controls; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; /** Abstract base for all controls. */ public abstract class AbstractControl implements Control { /** Sin value at NE corner. */ protected static final float SIN = MathUtils.sin(MathUtils.atan2(1f, 1f)); /** Cos value at NE corner. */ protected static final float COS = MathUtils.cos(MathUtils.atan2(1f, 1f)); private ControlListener listener; protected Vector2 movement = new Vector2(); @Override public Vector2 getMovementDirection() { return movement; } @Override public void setControlListener(final ControlListener listener) { this.listener = listener; } /** @return should be notified about game events. */ protected ControlListener getListener() { return listener; } /** @param angle in radians. */ protected void updateMovementWithAngle(final float angle) { movement.x = MathUtils.cos(angle); movement.y = MathUtils.sin(angle); } /** Stops movement. */ protected void stop() { movement.set(0f, 0f); } @Override public boolean isActive() { return true; } @Override public void reset() { movement.set(0f, 0f); } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.service.controls", fileName = "Control.java", content = """package ${project.basic.rootPackage}.service.controls; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.viewport.Viewport; import ${project.basic.rootPackage}.configuration.preferences.ControlsData; /** Represents player entity controls. */ public interface Control { /** @param inputMultiplexer can be used to attach an input processor. */ void attachInputListener(InputMultiplexer inputMultiplexer); /** @param gameViewport current state of game viewport. Might be used to convert units. * @param gameX x position of controlled entity in game units. * @param gameY y position of controlled entity in game units. */ void update(Viewport gameViewport, float gameX, float gameY); /** @return current movement direction. Values should add up to [-1, 1]. */ Vector2 getMovementDirection(); /** @param listener should receive game events. */ void setControlListener(ControlListener listener); /** @return serialized controls values that can be saved and read from. */ ControlsData toData(); /** @param data saved controls values that should be read. */ void copy(ControlsData data); /** @return true if the player is active and can play with these controls. */ boolean isActive(); /** @return type of controls. */ ControlType getType(); /** Clears state variables. */ void reset(); }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.service.controls", fileName = "ControlListener.java", content = """package ${project.basic.rootPackage}.service.controls; /** Listens to game events. */ public interface ControlListener { /** Invoked when controller detects jump input event. */ void jump(); }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.service.controls", fileName = "ControlType.java", content = """package ${project.basic.rootPackage}.service.controls; import com.badlogic.gdx.controllers.Controller; import com.badlogic.gdx.controllers.Controllers; import com.badlogic.gdx.utils.Array; import com.github.czyzby.kiwi.util.gdx.collection.GdxArrays; import ${project.basic.rootPackage}.configuration.preferences.ControlsData; import ${project.basic.rootPackage}.service.controls.impl.GamePadControl; import ${project.basic.rootPackage}.service.controls.impl.InactiveControl; import ${project.basic.rootPackage}.service.controls.impl.KeyboardControl; import ${project.basic.rootPackage}.service.controls.impl.TouchControl; /** Represents all types of available input sources. */ public enum ControlType { TOUCH { @Override public Control create(final ControlsData data) { return new TouchControl(); } }, KEYBOARD { @Override public Control create(final ControlsData data) { final Control control = new KeyboardControl(); control.copy(data); return control; } }, PAD { @Override public Control create(final ControlsData data) { final Array<Controller> controllers = Controllers.getControllers(); if (GdxArrays.isEmpty(controllers) || !GdxArrays.isIndexValid(controllers, data.index)) { // Controller unavailable. Fallback to inactive. return new InactiveControl(); } final Control control = new GamePadControl(controllers.get(data.index)); control.copy(data); return control; } }, INACTIVE { @Override public Control create(final ControlsData data) { return new InactiveControl(); } }; /** @param data serialized controls. * @return deserialized controller. */ public abstract Control create(ControlsData data); }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.service.controls.impl", fileName = "GamePadControl.java", content = """package ${project.basic.rootPackage}.service.controls.impl; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.controllers.Controller; import com.badlogic.gdx.controllers.ControllerAdapter; import com.badlogic.gdx.controllers.ControllerListener; import com.badlogic.gdx.controllers.Controllers; import com.badlogic.gdx.controllers.PovDirection; import com.badlogic.gdx.math.MathUtils; import ${project.basic.rootPackage}.configuration.preferences.ControlsData; import ${project.basic.rootPackage}.service.controls.AbstractButtonControl; import ${project.basic.rootPackage}.service.controls.ControlType; /** Allows to control an entity with controller events. */ public class GamePadControl extends AbstractButtonControl { private static final float DEADZONE = 0.2f; /** Axis alignment. */ protected static final int X_LEFT = 0, X_RIGHT = 3, Y_LEFT = 1, Y_RIGHT = 2; /** Left becomes right. */ private boolean invertX; /** Up becomes down. */ private boolean invertY; /** Left becomes up. */ private boolean invertXY; protected float axisX; protected float axisY; private Controller controller; private int controllerIndex; private final ControllerListener controllerListener = new ControllerAdapter() { @Override public boolean axisMoved(final Controller controller, final int axisIndex, final float value) { if (isAssignedTo(controller)) { updateAxisValue(axisIndex, value); return true; } return false; } @Override public boolean buttonDown(final Controller controller, final int buttonIndex) { if (isAssignedTo(controller)) { if (buttonIndex == up || buttonIndex == down || buttonIndex == left || buttonIndex == right) { pressedButtons.add(buttonIndex); updateMovement(); return true; } else if (buttonIndex == jump) { getListener().jump(); return true; } return true; } return false; } @Override public boolean buttonUp(final Controller controller, final int buttonIndex) { if (isAssignedTo(controller)) { if (buttonIndex == up || buttonIndex == down || buttonIndex == left || buttonIndex == right) { pressedButtons.remove(buttonIndex); updateMovement(); return true; } return true; } return false; } @Override public boolean povMoved(final Controller controller, final int povIndex, final PovDirection direction) { if (isAssignedTo(controller)) { if (direction != null) { if (direction == PovDirection.center) { stop(); } else { movement.x = getX(direction); movement.y = getY(direction); } } return true; } return false; } }; public GamePadControl() { up = 0; down = 2; left = 3; right = 1; jump = 4; } /** @param controller will be used to control the entity. */ public GamePadControl(final Controller controller) { this(); this.controller = controller; } /** @return the device that this input processor is assigned to. */ public Controller getController() { return controller; } /** @param controller will be used to control the entity. */ public void setController(final Controller controller) { if (this.controller != null) { this.controller.removeListener(controllerListener); } this.controller = controller; if (controller != null) { controllerIndex = Controllers.getControllers().indexOf(controller, true); } } /** @param controller a {@link Controller} instance. Can be null. * @return true if this input processor is assigned to passed controller. */ public boolean isAssignedTo(final Controller controller) { return this.controller.equals(controller); } protected void updateAxisValue(final int axisIndex, float value) { if (isY(axisIndex)) { // Inverting Y coordinates. value = -value; } if (!invertXY && isX(axisIndex) || invertXY && isY(axisIndex)) { if (value > DEADZONE || value < -DEADZONE) { axisX = invertX ? -value : value; } else { axisX = 0f; } } else { if (value > DEADZONE || value < -DEADZONE) { axisY = invertY ? -value : value; } else { axisY = 0f; } } if (Float.compare(axisX, 0f) == 0 && Float.compare(axisY, 0f) == 0) { stop(); } else { updateMovementWithAngle(MathUtils.atan2(axisY, axisX)); } } protected float getX(final PovDirection direction) { final float x; if (invertXY) { // Checking Y axis (north=east, south=west): x = getAbsoluteY(direction); } else { // Checking X axis: x = getAbsoluteX(direction); } if (invertX) { return -x; } return x; } protected float getY(final PovDirection direction) { final float y; if (invertXY) { // Checking X axis (north=east, south=west): y = getAbsoluteX(direction); } else { // Checking Y axis: y = getAbsoluteY(direction); } if (invertY) { return -y; } return y; } protected float getAbsoluteX(final PovDirection direction) { if (direction == PovDirection.east) { return 1f; } else if (direction == PovDirection.northEast || direction == PovDirection.southEast) { return COS; } else if (direction == PovDirection.west) { return -1f; } else if (direction == PovDirection.northWest || direction == PovDirection.southWest) { return -COS; } return 0f; } protected float getAbsoluteY(final PovDirection direction) { if (direction == PovDirection.north) { return 1f; } else if (direction == PovDirection.northEast || direction == PovDirection.northWest) { return SIN; } else if (direction == PovDirection.south) { return -1f; } else if (direction == PovDirection.southWest || direction == PovDirection.southEast) { return -SIN; } else { return 0f; } } private static boolean isX(final int axisIndex) { return axisIndex == X_LEFT || axisIndex == X_RIGHT; } private static boolean isY(final int axisIndex) { return axisIndex == Y_LEFT || axisIndex == Y_RIGHT; } protected float getAxisAngle() { return MathUtils.atan2(axisY, axisX) * MathUtils.radiansToDegrees; } /** @return true if X movement is inverted. */ public boolean isInvertX() { return invertX; } /** @param invertX true to invert X movement. */ public void setInvertX(final boolean invertX) { this.invertX = invertX; } /** @return true if Y movement is inverted. */ public boolean isInvertY() { return invertY; } /** @param invertY true to invert Y movement. */ public void setInvertY(final boolean invertY) { this.invertY = invertY; } /** @return true if X and Y movement are inverted with each other. */ public boolean isInvertXY() { return invertXY; } /** @param invertXY true to invert X and Y movement with each other. */ public void setInvertXY(final boolean invertXY) { this.invertXY = invertXY; } @Override public void attachInputListener(final InputMultiplexer inputMultiplexer) { controller.removeListener(controllerListener); // Making sure listener is not added twice. controller.addListener(controllerListener); } @Override public ControlsData toData() { final ControlsData data = super.toData(); data.invertX = invertX; data.invertY = invertY; data.invertXY = invertXY; data.index = controllerIndex; return data; } @Override public void copy(final ControlsData data) { super.copy(data); invertX = data.invertX; invertY = data.invertY; invertXY = data.invertXY; } @Override public ControlType getType() { return ControlType.PAD; } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.service.controls.impl", fileName = "InactiveControl.java", content = """package ${project.basic.rootPackage}.service.controls.impl; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.viewport.Viewport; import ${project.basic.rootPackage}.configuration.preferences.ControlsData; import ${project.basic.rootPackage}.service.controls.Control; import ${project.basic.rootPackage}.service.controls.ControlListener; import ${project.basic.rootPackage}.service.controls.ControlType; /** Mock-up controls representing an inactive player. */ public class InactiveControl implements Control { @Override public boolean isActive() { return false; } @Override public ControlType getType() { return ControlType.INACTIVE; } @Override public void attachInputListener(final InputMultiplexer inputMultiplexer) { } @Override public void update(final Viewport gameViewport, final float gameX, final float gameY) { } @Override public Vector2 getMovementDirection() { throw new UnsupportedOperationException(); } @Override public void setControlListener(final ControlListener listener) { throw new UnsupportedOperationException(); } @Override public ControlsData toData() { return new ControlsData(getType()); } @Override public void copy(final ControlsData data) { } @Override public void reset() { } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.service.controls.impl", fileName = "KeyboardControl.java", content = """package ${project.basic.rootPackage}.service.controls.impl; import com.badlogic.gdx.Input.Keys; import ${project.basic.rootPackage}.service.controls.AbstractButtonControl; import ${project.basic.rootPackage}.service.controls.ControlType; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.InputMultiplexer; /** Allows to control an entity with keyboard events. */ public class KeyboardControl extends AbstractButtonControl { public KeyboardControl() { // Initial settings: up = Keys.UP; down = Keys.DOWN; left = Keys.LEFT; right = Keys.RIGHT; jump = Keys.SPACE; } @Override public void attachInputListener(final InputMultiplexer inputMultiplexer) { inputMultiplexer.addProcessor(new InputAdapter() { @Override public boolean keyDown(final int keycode) { if (keycode == up || keycode == down || keycode == left || keycode == right) { pressedButtons.add(keycode); updateMovement(); return true; } else if (keycode == jump) { getListener().jump(); return true; } return false; } @Override public boolean keyUp(final int keycode) { if (keycode == up || keycode == down || keycode == left || keycode == right) { pressedButtons.remove(keycode); updateMovement(); return true; } return false; } }); } @Override public ControlType getType() { return ControlType.KEYBOARD; } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.service.controls.impl", fileName = "TouchControl.java", content = """package ${project.basic.rootPackage}.service.controls.impl; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.viewport.Viewport; import ${project.basic.rootPackage}.configuration.preferences.ControlsData; import ${project.basic.rootPackage}.service.controls.AbstractControl; import ${project.basic.rootPackage}.service.controls.ControlType; /** Allows to control entity with touch events. */ public class TouchControl extends AbstractControl { private final Vector2 entityPosition = new Vector2(); private boolean isMoving; private float x; private float y; @Override public void attachInputListener(final InputMultiplexer inputMultiplexer) { inputMultiplexer.addProcessor(new InputAdapter() { @Override public boolean touchDown(final int screenX, final int screenY, final int pointer, final int button) { updateDirection(screenX, Gdx.graphics.getHeight() - screenY); isMoving = true; getListener().jump(); return false; } @Override public boolean touchDragged(final int screenX, final int screenY, final int pointer) { updateDirection(screenX, Gdx.graphics.getHeight() - screenY); return false; } @Override public boolean touchUp(final int screenX, final int screenY, final int pointer, final int button) { stop(); isMoving = false; return false; } }); } private void updateDirection(final float x, final float y) { this.x = x; this.y = y; } @Override public void update(final Viewport gameViewport, final float gameX, final float gameY) { gameViewport.project(entityPosition.set(gameX, gameY)); if (isMoving) { updateMovementWithAngle(MathUtils.atan2(y - entityPosition.y, x - entityPosition.x)); } } @Override public ControlsData toData() { return new ControlsData(getType()); // Touch controls require no shortcuts. } @Override public void copy(final ControlsData data) { // Touch controls require no shortcuts. } @Override public ControlType getType() { return ControlType.TOUCH; } }""")) } override fun getApplicationListenerContent(project: Project): String = """package ${project.basic.rootPackage}; /** This class serves only as the application scanning root. Any classes in its package (or any of the sub-packages) * with proper Autumn MVC annotations will be found, scanned and initiated. */ public class ${project.basic.mainClass} { /** Default application size. */ public static final int WIDTH = 450, HEIGHT = 600; }""" }
unlicense
f73d22991b20e476604fdf6b97592fd7
39.343
422
0.666758
4.406663
false
false
false
false
Balanzini/kotlin-example-master-detail
app/src/main/java/com/balanza/android/harrypotter/ui/characterlist/adapter/CharacterAdapter.kt
1
2774
package com.balanza.android.harrypotter.ui.characterlist.adapter import android.content.Context import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import com.balanza.android.harrypotter.R import com.balanza.android.harrypotter.domain.model.character.CharacterBasic import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.character_list_item.view.* import java.util.* /** * Created by balanza on 15/02/17. */ class CharacterAdapter( val listener: (CharacterBasic) -> Unit) : RecyclerView.Adapter<CharacterAdapter.CharacterHolder>() { private var characterList = ArrayList<CharacterBasic>() private var context: Context? = null private var positionSelected: Int = -1 private var clicked: Boolean = false override fun onBindViewHolder(holder: CharacterHolder, position: Int) { val characterInstance = characterList[position] holder.bind(characterInstance, clicked, positionSelected, position) { clicked = true positionSelected = position listener(it) notifyDataSetChanged() } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CharacterHolder { context = parent.context val view = LayoutInflater.from(parent.context).inflate(R.layout.character_list_item, parent, false) return CharacterHolder(view) } override fun getItemCount() = characterList.size fun setCharacters(charactersList: List<CharacterBasic>) { this.characterList.clear() this.characterList.addAll(charactersList) notifyDataSetChanged() } fun reset() { clicked = false notifyDataSetChanged() } class CharacterHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun ImageView.loadUrl(url: String) { Glide.with(context).load(url).centerCrop().into(iv_item_image) } fun bind(item: CharacterBasic, clicked: Boolean, positionSelected: Int, position: Int, listener: (CharacterBasic) -> Unit) = with(itemView) { tv_item_name.text = item.name tv_item_house.text = item.house.name iv_item_image.loadUrl(item.imageUrl) rl_item_background.setBackgroundResource(item.house.background) if (clicked) { v_shadow.visibility = View.VISIBLE val color: Int if (positionSelected === position) { color = context?.resources?.getColor(R.color.item_selected_shadow) ?: -1 } else { color = context?.resources?.getColor(R.color.item_shadow) ?: -1 } v_shadow.setBackgroundColor(color) } else { v_shadow.visibility = View.GONE } setOnClickListener { listener(item) } } } }
mit
b637632c720a9bed981e99cb65f5c321
29.833333
104
0.71305
4.24159
false
false
false
false
rock3r/detekt
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/DetektFacade.kt
1
4530
package io.gitlab.arturbosch.detekt.core import io.gitlab.arturbosch.detekt.api.Detektion import io.gitlab.arturbosch.detekt.api.FileProcessListener import io.gitlab.arturbosch.detekt.api.Finding import io.gitlab.arturbosch.detekt.api.Notification import io.gitlab.arturbosch.detekt.api.RuleSetProvider import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.PlainTextMessageRenderer import org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector import org.jetbrains.kotlin.cli.jvm.compiler.NoScopeRecordCliBindingTrace import org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM import org.jetbrains.kotlin.config.languageVersionSettings import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.declarations.FileBasedDeclarationProviderFactory class DetektFacade( private val detektor: Detektor, settings: ProcessingSettings, private val processors: List<FileProcessListener> ) { private val saveSupported = settings.autoCorrect private val inputPaths = settings.inputPaths private val classpath = settings.classpath private val environment = settings.environment private val compiler = KtTreeCompiler.instance(settings) fun run(): Detektion { val notifications = mutableListOf<Notification>() val findings = HashMap<String, List<Finding>>() val filesToAnalyze = inputPaths.flatMap(compiler::compile) val bindingContext = generateBindingContext(filesToAnalyze) processors.forEach { it.onStart(filesToAnalyze) } findings.mergeSmells(detektor.run(filesToAnalyze, bindingContext)) if (saveSupported) { KtFileModifier().saveModifiedFiles(filesToAnalyze) { notifications.add(it) } } val result = DetektResult(findings.toSortedMap()) processors.forEach { it.onFinish(filesToAnalyze, result) } return result } private fun generateBindingContext(filesForEnvironment: List<KtFile>): BindingContext { return if (classpath.isNotEmpty()) { val analyzer = AnalyzerWithCompilerReport( PrintingMessageCollector(System.err, DetektMessageRenderer, true), environment.configuration.languageVersionSettings ) analyzer.analyzeAndReport(filesForEnvironment) { TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( environment.project, filesForEnvironment, NoScopeRecordCliBindingTrace(), environment.configuration, environment::createPackagePartProvider, ::FileBasedDeclarationProviderFactory ) } analyzer.analysisResult.bindingContext } else { BindingContext.EMPTY } } private object DetektMessageRenderer : PlainTextMessageRenderer() { override fun getName() = "detekt message renderer" override fun getPath(location: CompilerMessageLocation) = location.path override fun render( severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation? ): String { if (!severity.isError) return "" return super.render(severity, message, location) } } companion object { fun create(settings: ProcessingSettings): DetektFacade { val providers = RuleSetLocator(settings).load() val processors = FileProcessorLocator(settings).load() return create(settings, providers, processors) } fun create(settings: ProcessingSettings, vararg providers: RuleSetProvider): DetektFacade { return create(settings, providers.toList(), emptyList()) } fun create(settings: ProcessingSettings, vararg processors: FileProcessListener): DetektFacade { return create(settings, emptyList(), processors.toList()) } fun create( settings: ProcessingSettings, providers: List<RuleSetProvider>, processors: List<FileProcessListener> ): DetektFacade { return DetektFacade(Detektor(settings, providers, processors), settings, processors) } } }
apache-2.0
3ffd4c94a38262ee744ae7b065995806
40.181818
104
0.708389
5.380048
false
false
false
false
IntershopCommunicationsAG/scmversion-gradle-plugin
src/main/kotlin/com/intershop/gradle/scm/utils/SimplePrefixConfig.kt
1
1935
/* * Copyright 2020 Intershop Communications AG. * * 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.intershop.gradle.scm.utils /** * Simple prefix configuration for * testing. */ class SimplePrefixConfig : IPrefixConfig { /** * Prefix for stabilization branches. * * @property stabilizationPrefix */ override var stabilizationPrefix: String = "SB" /** * Prefix for feature branches. * * @property featurePrefix */ override var featurePrefix: String = "FB" /** * Prefix for hotfix branches. * * @property hotfixPrefix */ override var hotfixPrefix: String = "HB" /** * Prefix for bugfix branches. * * @property bugfixPrefix */ override var bugfixPrefix: String = "BB" /** * Prefix for release tags. * * @property tagPrefix */ override var tagPrefix: String = "RELEASE" /** * Separator between prefix and version. * * @property prefixSeperator */ override var prefixSeperator: String = "_" /** * Separator between prefix and version for branches. * * @property branchPrefixSeperator */ override var branchPrefixSeperator: String? = null /** * Separator between prefix and version for tags. * * @property tagPrefixSeperator */ override var tagPrefixSeperator: String? = null }
apache-2.0
2fadc90e4ebc9f95162783aa891e783c
23.493671
75
0.647545
4.521028
false
false
false
false
LanternPowered/LanternServer
test-server/src/main/kotlin/org/lanternpowered/testserver/LANBroadcastPlugin.kt
1
2742
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.testserver import org.lanternpowered.api.Server import org.lanternpowered.api.event.lifecycle.StartedServerEvent import org.lanternpowered.api.event.lifecycle.StoppingServerEvent import org.lanternpowered.api.injector.inject import org.lanternpowered.api.logger.Logger import org.lanternpowered.api.text.serializer.LegacyTextSerializer import org.lanternpowered.api.plugin.Plugin import org.lanternpowered.api.event.Listener import java.io.IOException import java.net.DatagramPacket import java.net.DatagramSocket import java.net.InetAddress /** * A plugin which broadcasts the server to the LAN. This could * save you a few seconds of precious time. */ @Plugin("lan-broadcast") object LANBroadcastPlugin { private val logger: Logger = inject() private val server: Server = inject() private lateinit var socket: DatagramSocket @Listener fun onServerStarted(event: StartedServerEvent) { try { this.socket = DatagramSocket() } catch (ex: IOException) { this.logger.error("Failed to open socket, the LAN broadcast will NOT work.", ex) return } val thread = Thread(this::broadcast, "lan_broadcast") thread.isDaemon = true thread.start() this.logger.info("Started to broadcast the server on the LAN.") } @Listener fun onServerStopping(event: StoppingServerEvent) { this.socket.close() } private fun broadcast() { // Formatting codes are still supported by the LAN motd val motd = LegacyTextSerializer.serialize(this.server.motd) val port = this.server.boundAddress.get().port val message = "[MOTD]$motd[/MOTD][AD]$port[/AD]" val data = message.toByteArray(Charsets.UTF_8) val targetPort = 4445 val targetAddress = InetAddress.getByName("224.0.2.60") var errorLogged = false while (!this.socket.isClosed) { try { this.socket.send(DatagramPacket(data, data.size, targetAddress, targetPort)) errorLogged = false } catch (ex: IOException) { if (!errorLogged) { this.logger.error("Failed to broadcast server on the LAN.", ex) errorLogged = true } } // Sleep 1.5 seconds Thread.sleep(1500L) } } }
mit
840dffd855f2cb9bc4f636611a5f6ae5
30.517241
92
0.660102
4.311321
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/status/LanternStatusHelper.kt
1
1992
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.status import org.lanternpowered.api.profile.copyWithoutProperties import org.lanternpowered.api.util.collections.asNonNullList import org.lanternpowered.server.event.LanternEventFactory import org.lanternpowered.server.LanternServer import org.lanternpowered.server.profile.LanternGameProfile import org.spongepowered.api.event.server.ClientPingServerEvent import org.spongepowered.api.profile.GameProfile object LanternStatusHelper { /** * The maximum amount of players that are by default displayed in the status ping. */ private const val DEFAULT_MAX_PLAYERS_DISPLAYED = 12 @JvmStatic fun createPlayers(server: LanternServer): ClientPingServerEvent.Response.Players { // Get the online players val players = server.unsafePlayers val online = players.size val max = server.maxPlayers // Create a list with the players var playersList = players.toMutableList() // Randomize the players list playersList.shuffle() // Limit the maximum amount of displayed players if (playersList.size > DEFAULT_MAX_PLAYERS_DISPLAYED) { playersList = playersList.subList(0, DEFAULT_MAX_PLAYERS_DISPLAYED) } // Get all the game profiles and create a copy val gameProfiles: List<GameProfile> = playersList.asSequence() .map { player -> (player.profile as LanternGameProfile).copyWithoutProperties() } .toMutableList() .asNonNullList() return LanternEventFactory.createClientPingServerEventResponsePlayers(gameProfiles, max, online) } }
mit
003dba843b590f9a01a4f27c0833223f
36.603774
104
0.717871
4.611111
false
false
false
false
Tomorrowhi/THDemo
THDemo/app/src/main/java/com/tomorrowhi/thdemo/bean/MainFunctionBean.kt
1
307
package com.tomorrowhi.thdemo.bean class MainFunctionBean { var name: String = ""; var id: Int = 0; constructor(name: String, id: Int) { this.name = name this.id = id } override fun toString(): String { return "MainFunctionBean(name='$name', id=$id)" } }
apache-2.0
7b8c7c504a676765b642ebf542a2ed4e
17.117647
55
0.579805
3.654762
false
false
false
false
ChrisZhong/organization-model
chazm-model/src/main/kotlin/runtimemodels/chazm/model/notification/DefaultMediator.kt
2
6363
package runtimemodels.chazm.model.notification import runtimemodels.chazm.model.message.L import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.locks.StampedLock import javax.inject.Singleton import kotlin.collections.Map.Entry @Singleton internal open class DefaultMediator : Mediator { private val eventSubscribers: MutableMap<Class<*>, MutableMap<Subscriber, Method>> = ConcurrentHashMap() private val subscriberEvents: MutableMap<Subscriber, MutableMap<Class<*>, Method>> = ConcurrentHashMap() private val lock = StampedLock() val events: Set<Class<*>> get() { val stamp = lock.readLock() try { return eventSubscribers.keys } finally { lock.unlockRead(stamp) } } val subscribers: Set<Subscriber> get() { val stamp = lock.readLock() try { return subscriberEvents.keys } finally { lock.unlockRead(stamp) } } fun getSubscriberEvents(subscriber: Subscriber): Map<Class<*>, Method> { val stamp = lock.readLock() try { return subscriberEvents[subscriber]!!.toMap() } finally { lock.unlockRead(stamp) } } fun register(vararg subscribers: Subscriber) { subscribers.forEach(::register) } fun unregister(vararg subscribers: Subscriber) { subscribers.forEach(::unregister) } override fun <T : Any> post(event: T) { /* prevents multiple post from occurring simultaneously because it is possible for a subscriber to be notified of two or more events at the same time */ val set = get(event.javaClass) synchronized(this) { /* notifying all subscribers for this event can be performed in parallel because a subscriber can only subscribe at most once to the same event */ set.forEach { invoke(it.value, it.key, event) } } } override fun register(subscriber: Subscriber) { subscriber.javaClass.declaredMethods .filter { it.isAnnotationPresent(Subscribe::class.java) && it.parameterCount == 1 } .forEach { add(it, subscriber) } } override fun unregister(subscriber: Subscriber) { val stamp = lock.writeLock() try { if (subscriberEvents.containsKey(subscriber)) { val map = subscriberEvents.remove(subscriber)!! map.keys.forEach { val m = eventSubscribers[it]!! m.remove(subscriber) if (m.isEmpty()) { eventSubscribers.remove(it) } } } } finally { lock.unlockWrite(stamp) } } private operator fun get(type: Class<*>): Set<Entry<Subscriber, Method>> { val stamp = lock.readLock() try { if (eventSubscribers.containsKey(type)) { return eventSubscribers[type]!!.entries } } finally { lock.unlockRead(stamp) } return setOf() } private operator fun <T : Any> invoke(method: Method, subscriber: Subscriber, event: T) { try { method.invoke(subscriber, event) } catch (e: IllegalAccessException) { log.warn(L.UNABLE_TO_INVOKE.get(), subscriber.javaClass.name, method.name, event) val stamp = lock.writeLock() try { val m1 = eventSubscribers[event.javaClass]!! m1.remove(subscriber) if (m1.isEmpty()) { eventSubscribers.remove(event.javaClass) } val m2 = subscriberEvents[subscriber]!! m2.remove(event.javaClass) if (m2.isEmpty()) { subscriberEvents.remove(subscriber) } } finally { lock.unlockWrite(stamp) } } catch (e: IllegalArgumentException) { log.warn(L.UNABLE_TO_INVOKE.get(), subscriber.javaClass.name, method.name, event) val stamp = lock.writeLock() try { val m1 = eventSubscribers[event.javaClass]!! m1.remove(subscriber) if (m1.isEmpty()) { eventSubscribers.remove(event.javaClass) } val m2 = subscriberEvents[subscriber]!! m2.remove(event.javaClass) if (m2.isEmpty()) { subscriberEvents.remove(subscriber) } } finally { lock.unlockWrite(stamp) } } catch (e: InvocationTargetException) { log.warn(L.UNABLE_TO_INVOKE.get(), subscriber.javaClass.name, method.name, event) val stamp = lock.writeLock() try { val m1 = eventSubscribers[event.javaClass]!! m1.remove(subscriber) if (m1.isEmpty()) { eventSubscribers.remove(event.javaClass) } val m2 = subscriberEvents[subscriber]!! m2.remove(event.javaClass) if (m2.isEmpty()) { subscriberEvents.remove(subscriber) } } finally { lock.unlockWrite(stamp) } } } private fun add(method: Method, subscriber: Subscriber) { val type = method.parameterTypes[0] val stamp = lock.writeLock() try { val map = eventSubscribers.computeIfAbsent(type) { ConcurrentHashMap() } if (map.containsKey(subscriber)) { log.warn(L.SUBSCRIBER_ALREADY_REGISTERED.get(), subscriber, type) } else { log.info(L.SUBSCRIBER_REGISTERED.get(), subscriber, type, method) map[subscriber] = method subscriberEvents.computeIfAbsent(subscriber) { ConcurrentHashMap() }[type] = method } } finally { lock.unlockWrite(stamp) } } companion object { private val log = org.slf4j.LoggerFactory.getLogger(DefaultMediator::class.java) } }
apache-2.0
0175eb937f71cd575f51c29ecf526ffa
34.547486
160
0.555398
4.924923
false
false
false
false
valsinats42/meditate
mobile/src/main/java/me/stanislav_nikolov/meditate/db/DbMeditationSession.kt
1
755
package me.stanislav_nikolov.meditate.db import io.realm.RealmObject import io.realm.annotations.PrimaryKey import io.realm.annotations.RealmClass import me.stanislav_nikolov.meditate.toDateTime import java.util.* /** * Created by stanley on 12.09.15. */ @RealmClass open class DbMeditationSession : RealmObject() { @PrimaryKey open var uuid: String? = null open var startTime: Date? = null open var endTime: Date? = null open var initialDurationSeconds: Int = 0 open var comment: String? = null } fun DbMeditationSession.getStartDateTime() = startTime!!.toDateTime() fun DbMeditationSession.getEndDateTime() = endTime!!.toDateTime() fun DbMeditationSession.getDuration() = getStartDateTime().numSecondsFrom(getEndDateTime())
mit
85c793b2d4512ccfd890d6c75e66ee43
30.458333
91
0.764238
3.737624
false
false
false
false
zaviyalov/dialog
backend/src/main/kotlin/com/github/zaviyalov/dialog/controller/BasalRateController.kt
1
3216
package com.github.zaviyalov.dialog.controller import com.github.zaviyalov.dialog.common.Paths import com.github.zaviyalov.dialog.exception.UnknownUserException import com.github.zaviyalov.dialog.model.BasalRate import com.github.zaviyalov.dialog.service.AppUserManagementService import com.github.zaviyalov.dialog.service.BasalRateService import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.domain.Pageable import org.springframework.data.domain.Sort import org.springframework.data.web.PageableDefault import org.springframework.http.ResponseEntity import org.springframework.security.core.Authentication import org.springframework.web.bind.annotation.* @RestController @RequestMapping(Paths.BASAL_RATE_CONTROLLER) class BasalRateController @Autowired constructor( private val basalRateService: BasalRateService, userService: AppUserManagementService ) : AbstractController(userService) { @GetMapping("/{id}") @Throws(UnknownUserException::class) fun findById(@PathVariable id: String, auth: Authentication): ResponseEntity<BasalRate> { val rate = basalRateService.findByIdAndUser(id, getUser(auth)) return rate?.let { ResponseEntity.ok(it) } ?: ResponseEntity.notFound().build() } @GetMapping @Throws(UnknownUserException::class) fun findAll( @PageableDefault(sort = arrayOf("dateTime"), direction = Sort.Direction.DESC) pageable: Pageable?, auth: Authentication ): ResponseEntity<List<BasalRate>> { val list = basalRateService.findAllByUser(getUser(auth), pageable) return ResponseEntity.ok(list) } @PostMapping @Throws(UnknownUserException::class) fun insert(@RequestBody basalRate: BasalRate, auth: Authentication): ResponseEntity<BasalRate> { return when (getUser(auth)) { basalRate.user -> ResponseEntity.ok(basalRateService.insert(basalRate)) else -> ResponseEntity.badRequest().build() } } @PutMapping @Throws(UnknownUserException::class) fun update(@RequestBody basalRate: BasalRate, auth: Authentication): ResponseEntity<BasalRate> { return when (getUser(auth)) { basalRate.user -> ResponseEntity.ok(basalRateService.save(basalRate)) else -> ResponseEntity.badRequest().build() } } @DeleteMapping @Throws(UnknownUserException::class) fun delete(@RequestBody basalRate: BasalRate, auth: Authentication): ResponseEntity<Void> { return when (getUser(auth)) { basalRate.user -> { basalRateService.delete(basalRate) ResponseEntity.ok().build() } else -> ResponseEntity.badRequest().build() } } @DeleteMapping("/{id}") @Throws(UnknownUserException::class) fun deleteById(@PathVariable id: String, auth: Authentication): ResponseEntity<Void> { val entry = basalRateService.findByIdAndUser(id, getUser(auth)) return when (entry) { null -> ResponseEntity.notFound().build() else -> { basalRateService.delete(entry) ResponseEntity.ok().build() } } } }
bsd-3-clause
37cbdb0c11039b9df1d8159566762158
38.219512
106
0.703047
4.600858
false
false
false
false
Shoebill/streamer-wrapper
src/main/java/net/gtaun/shoebill/streamer/data/DynamicCheckpoint.kt
1
1853
package net.gtaun.shoebill.streamer.data import net.gtaun.shoebill.entities.Destroyable import net.gtaun.shoebill.entities.Player import net.gtaun.shoebill.data.Radius import net.gtaun.shoebill.streamer.Functions import java.util.* /** * Created by marvin on 29.04.17 in project streamer-wrapper. * Copyright (c) 2017 Marvin Haschker. All rights reserved. */ open class DynamicCheckpoint internal constructor(id: Int, val location: Radius, val player: Player?, val streamDistance: Float, val dynamicArea: DynamicArea?, val priority: Int) : Destroyable { var id: Int = id internal set get override fun destroy() { if (isDestroyed) return Functions.destroyDynamicCp(this) objects.remove(this) id = -1 } override val isDestroyed: Boolean get() = !Functions.isValidDynamicCp(this) companion object { @JvmField val DEFAULT_STREAM_DISTANCE = 200f // Corresponds to STREAMER_CP_SD in streamer.inc private var objects = mutableListOf<DynamicCheckpoint>() @JvmStatic fun get(): Set<DynamicCheckpoint> = HashSet(objects) @JvmStatic operator fun get(id: Int): DynamicCheckpoint? = objects.find { it.id == id } @JvmStatic @JvmOverloads fun create(location: Radius, player: Player? = null, streamDistance: Float = DEFAULT_STREAM_DISTANCE, area: DynamicArea? = null, priority: Int = 0): DynamicCheckpoint { val playerId = player?.id ?: -1 val areaId = area?.id ?: -1 val checkpoint = Functions.createDynamicCp(location, playerId, streamDistance, areaId, priority) objects.add(checkpoint) return checkpoint } } }
agpl-3.0
f31bdf5f98d830fb71810e4dd28d1241
31.526316
109
0.627091
4.564039
false
false
false
false
crunchersaspire/worshipsongs-android
app/src/main/java/org/worshipsongs/domain/AuthorSong.kt
3
522
package org.worshipsongs.domain import org.apache.commons.lang3.builder.ToStringBuilder /** * Created by Seenivasan on 3/24/2015. */ class AuthorSong { var authorId: Int = 0 var songId: Int = 0 var song: Song? = null var author: Author? = null override fun toString(): String { val stringBuilder = ToStringBuilder(this) stringBuilder.append("authorname", author!!.name) stringBuilder.append("song title", song!!.title) return stringBuilder.toString() } }
gpl-3.0
8305efa423c175bc4adb7b19b4dc0809
20.75
57
0.66092
4.015385
false
false
false
false
jingcai-wei/android-news
app/src/main/java/com/sky/android/news/ui/main/story/StoryAdapter.kt
1
5439
/* * Copyright (c) 2020 The sky 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.sky.android.news.ui.main.story import android.annotation.SuppressLint import android.content.Context import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bigkoo.convenientbanner.ConvenientBanner import com.bigkoo.convenientbanner.listener.OnItemClickListener import com.bumptech.glide.Glide import com.hi.dhl.binding.viewbind import com.sky.android.core.adapter.BaseRecyclerAdapter import com.sky.android.core.adapter.BaseRecyclerHolder import com.sky.android.core.adapter.SimpleRecyclerAdapter import com.sky.android.news.R import com.sky.android.news.data.model.* import com.sky.android.news.databinding.ItemNoteStoryBinding import com.sky.android.news.databinding.ItemStoryListBinding import com.sky.android.news.databinding.ItemTopStoryBinding import java.text.SimpleDateFormat /** * Created by sky on 17-9-28. */ class StoryAdapter(context: Context) : SimpleRecyclerAdapter<BaseViewType>(context) { @SuppressLint("SimpleDateFormat") private val dateFormat = SimpleDateFormat("yyyyMMdd") @SuppressLint("SimpleDateFormat") private val dateFormat2 = SimpleDateFormat("MM月dd日 E") override fun onCreateView(layoutInflater: LayoutInflater, viewGroup: ViewGroup?, viewType: Int): View { return when(viewType) { 0 -> layoutInflater.inflate(R.layout.item_top_story, viewGroup, false) 1 -> layoutInflater.inflate(R.layout.item_story_list, viewGroup, false) else -> layoutInflater.inflate(R.layout.item_note_story, viewGroup, false) } } override fun onCreateViewHolder(view: View, viewType: Int): BaseRecyclerHolder<BaseViewType> { return when(viewType) { 0 -> TopStoryHolder(view, this) 1 -> StoryItemHolder(view, this) else -> NoteStoryHolder(view, this) } } override fun getItemViewType(position: Int): Int = getItem(position).viewType inner class NoteStoryHolder(itemView: View, adapter: BaseRecyclerAdapter<BaseViewType>) : BaseRecyclerHolder<BaseViewType>(itemView, adapter) { private val binding: ItemNoteStoryBinding by viewbind() override fun onBind(position: Int, viewType: Int) { val item = getItem(position) as NodeItemModel val date = dateFormat.parse(item.data) binding.tvNote.text = if (!TextUtils.isEmpty(item.node)) item.node else dateFormat2.format(date) } } inner class TopStoryHolder(itemView: View, adapter: BaseRecyclerAdapter<BaseViewType>) : BaseRecyclerHolder<BaseViewType>(itemView, adapter) { private val binding: ItemTopStoryBinding by viewbind() lateinit var convenientBanner: ConvenientBanner<TopStoryItemModel> override fun onInitialize() { convenientBanner = binding.convenientBanner as ConvenientBanner<TopStoryItemModel> convenientBanner.setPageIndicator( intArrayOf(R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused)) convenientBanner.setPageIndicatorAlign( ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT) convenientBanner.setOnItemClickListener { val item = getItem(adapterPosition) as TopStoryListModel callItemEvent(1, itemView, adapterPosition, item.topStories[it]) } } override fun onBind(position: Int, viewType: Int) { val item = getItem(position) as TopStoryListModel convenientBanner.setPages(BannerHolderCreator(), item.topStories) convenientBanner.notifyDataSetChanged() } override fun onAttachedToWindow() { super.onAttachedToWindow() // 开始滚动 convenientBanner.startTurning(5000) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() // 停止滚动 convenientBanner.stopTurning() } } inner class StoryItemHolder(itemView: View, adapter: BaseRecyclerAdapter<BaseViewType>) : BaseRecyclerHolder<BaseViewType>(itemView, adapter) { private val binding: ItemStoryListBinding by viewbind() override fun onInitialize() { binding.cardZhihuItem.setOnClickListener { // 回调点击事件 callItemEvent(it, adapterPosition) } } override fun onBind(position: Int, viewType: Int) { val item = getItem(position) as StoryItemModel itemView.apply { Glide.with(context) .load(item.images[0]) .into(binding.ivImage) binding.tvTitle.text = item.title } } } }
apache-2.0
83cd53d5b6afbf32fc1c1ce1ad3512d8
35.540541
108
0.686333
4.613481
false
false
false
false
FHannes/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/JavaAbstractUElement.kt
2
1846
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiExpression import com.intellij.psi.PsiType import org.jetbrains.uast.UAnnotation import org.jetbrains.uast.UElement import org.jetbrains.uast.UExpression import org.jetbrains.uast.java.internal.JavaUElementWithComments abstract class JavaAbstractUElement : JavaUElementWithComments { override fun equals(other: Any?): Boolean { if (other !is UElement || other.javaClass != this.javaClass) return false return this.psi == other.psi } override fun asSourceString(): String { return this.psi?.text ?: super<JavaUElementWithComments>.asSourceString() } override fun toString() = asRenderString() } abstract class JavaAbstractUExpression : JavaAbstractUElement(), UExpression { override fun evaluate(): Any? { val project = psi?.project ?: return null return JavaPsiFacade.getInstance(project).constantEvaluationHelper.computeConstantExpression(psi) } override val annotations: List<UAnnotation> get() = emptyList() override fun getExpressionType(): PsiType? { val expression = psi as? PsiExpression ?: return null return expression.type } }
apache-2.0
7a2fe9dfa8d91ce8a8dd89930046e2b1
33.849057
105
0.73727
4.661616
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-android
superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/ui/banner/CustomWebView.kt
1
3509
@file:Suppress("RedundantVisibilityModifier", "unused") package tv.superawesome.sdk.publisher.common.ui.banner import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.graphics.Color import android.os.Build import android.util.AttributeSet import android.util.Log import android.webkit.WebResourceError import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient @SuppressLint("SetJavaScriptEnabled") public class CustomWebView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : WebView(context, attrs, defStyleAttr) { interface Listener { fun webViewOnStart() fun webViewOnError() fun webViewOnClick(url: String) } var listener: Listener? = null // boolean holding whether the web view has finished loading or not private var finishedLoading = false init { setBackgroundColor(Color.TRANSPARENT) isVerticalScrollBarEnabled = false isHorizontalScrollBarEnabled = false scrollBarStyle = SCROLLBARS_OUTSIDE_OVERLAY isFocusableInTouchMode = false if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { settings.mediaPlaybackRequiresUserGesture = false } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setWebContentsDebuggingEnabled(true) } settings.javaScriptEnabled = true webViewClient = object : WebViewClient() { override fun onReceivedError( view: WebView?, request: WebResourceRequest?, error: WebResourceError? ) { super.onReceivedError(view, request, error) listener?.webViewOnError() } override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean { if (finishedLoading) { val fullUrl = url ?: return false if (fullUrl.contains("sa-beta-ads-uploads-superawesome.netdna-ssl.com") && fullUrl.contains("/iframes") ) { return false } listener?.webViewOnClick(fullUrl) return true } else { return false } } @Suppress("DEPRECATION") override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) { super.onPageStarted(view, url, favicon) if (shouldOverrideUrlLoading(view, url)) { view?.stopLoading() } } override fun onPageFinished(view: WebView?, url: String?) { super.onPageFinished(view, url) finishedLoading = true listener?.webViewOnStart() } } } override fun destroy() { super.destroy() listener = null Log.i("WebView", "WebView destroy()") } public fun loadHTML(base: String, html: String) { val baseHtml = "<html><header><meta name='viewport' content='width=device-width'/><style>html, body, div { margin: 0px; padding: 0px; } html, body { width: 100%; height: 100%; }</style></header><body>$html</body></html>" loadDataWithBaseURL(base, baseHtml, "text/html", "UTF-8", null) } }
lgpl-3.0
3b16b8e6e1aa3e9f5dd6e8186859b23a
34.444444
217
0.599601
5.056196
false
false
false
false
TeamAmaze/AmazeFileManager
app/src/main/java/com/amaze/filemanager/filesystem/root/ListFilesCommand.kt
1
10331
/* * Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.filesystem.root import androidx.preference.PreferenceManager import com.amaze.filemanager.R import com.amaze.filemanager.application.AppConfig import com.amaze.filemanager.exceptions.ShellCommandInvalidException import com.amaze.filemanager.fileoperations.exceptions.ShellNotRunningException import com.amaze.filemanager.fileoperations.filesystem.OpenMode import com.amaze.filemanager.fileoperations.filesystem.root.NativeOperations import com.amaze.filemanager.filesystem.HybridFileParcelable import com.amaze.filemanager.filesystem.RootHelper import com.amaze.filemanager.filesystem.files.FileUtils import com.amaze.filemanager.filesystem.root.base.IRootCommand import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.File object ListFilesCommand : IRootCommand() { private val log: Logger = LoggerFactory.getLogger(ListFilesCommand::class.java) /** * list files in given directory and invoke callback */ fun listFiles( path: String, root: Boolean, showHidden: Boolean, openModeCallback: (openMode: OpenMode) -> Unit, onFileFoundCallback: (file: HybridFileParcelable) -> Unit ) { val mode: OpenMode if (root && FileUtils.isRunningAboveStorage(path)) { // we're rooted and we're trying to load file with superuser // we're at the root directories, superuser is required! val result = executeRootCommand(path, showHidden) result.first.forEach { if (!it.contains("Permission denied")) { parseStringForHybridFile( rawFile = it, path = path, isStat = !result.second ) ?.let(onFileFoundCallback) } } mode = OpenMode.ROOT openModeCallback(mode) } else if (FileUtils.canListFiles(File(path))) { // we're taking a chance to load files using basic java filesystem getFilesList(path, showHidden, onFileFoundCallback) mode = OpenMode.FILE } else { // we couldn't load files using native java filesystem callbacks // maybe the access is not allowed due to android system restrictions, we'll see later mode = OpenMode.FILE } openModeCallback(mode) } /** * Get open mode for path if it's a root path or normal storage */ fun getOpenMode( path: String, root: Boolean ): OpenMode { val mode: OpenMode = if (root && FileUtils.isRunningAboveStorage(path)) { OpenMode.ROOT } else { OpenMode.FILE } return mode } /** * executes list files root command directory and return each line item * returns pair with first denoting the result array and second if run with ls (true) or stat (false) */ @Throws(ShellNotRunningException::class) fun executeRootCommand( path: String, showHidden: Boolean, retryWithLs: Boolean = false ): Pair<List<String>, Boolean> { try { /** * If path is root keep command `stat -c *` * Else keep `stat -c /path/file/\*` */ var appendedPath = path val sanitizedPath = RootHelper.getCommandLineString(appendedPath) appendedPath = when (path) { "/" -> sanitizedPath.replace("/", "") else -> sanitizedPath.plus("/") } val command = "stat -c '%A %h %G %U %B %Y %N' " + "$appendedPath*" + (if (showHidden) " $appendedPath.* " else "") val enforceLegacyFileListing: Boolean = PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .getBoolean( PreferencesConstants.PREFERENCE_ROOT_LEGACY_LISTING, false ) // #3476: Check current working dir, change back to / before proceeding runShellCommand("pwd").run { if (out.first() != "/") { runShellCommand("cd /") } } return if (!retryWithLs && !enforceLegacyFileListing) { log.info("Using stat for list parsing") Pair( first = runShellCommandToList(command).map { it.replace(appendedPath, "") }, second = enforceLegacyFileListing ) } else { log.info("Using ls for list parsing") Pair( first = runShellCommandToList( "ls -l " + (if (showHidden) "-a " else "") + "\"$sanitizedPath\"" ), second = if (retryWithLs) { true } else { enforceLegacyFileListing } ) } } catch (invalidCommand: ShellCommandInvalidException) { log.warn("Command not found - ${invalidCommand.message}") return if (retryWithLs) { Pair(first = emptyList(), second = true) } else { executeRootCommand(path, showHidden, true) } } catch (exception: ShellNotRunningException) { log.warn("failed to execute root command", exception) return Pair(first = emptyList(), second = false) } } private fun isDirectory(path: HybridFileParcelable): Boolean { return path.permission.startsWith("d") || File(path.path).isDirectory } /** * Loads files in a path using basic filesystem callbacks * * @param path the path */ private fun getFilesList( path: String, showHidden: Boolean, listener: (HybridFileParcelable) -> Unit ): ArrayList<HybridFileParcelable> { val pathFile = File(path) val files = ArrayList<HybridFileParcelable>() if (pathFile.exists() && pathFile.isDirectory) { val filesInPathFile = pathFile.listFiles() if (filesInPathFile != null) { filesInPathFile.forEach { currentFile -> var size: Long = 0 if (!currentFile.isDirectory) size = currentFile.length() HybridFileParcelable( currentFile.path, RootHelper.parseFilePermission(currentFile), currentFile.lastModified(), size, currentFile.isDirectory ).let { baseFile -> baseFile.name = currentFile.name baseFile.mode = OpenMode.FILE if (showHidden) { files.add(baseFile) listener(baseFile) } else { if (!currentFile.isHidden) { files.add(baseFile) listener(baseFile) } } } } } else { log.error("Error listing files at [$path]. Access permission denied?") AppConfig.getInstance().run { AppConfig.toast(this, this.getString(R.string.error_permission_denied)) } } } return files } /** * Parses listing command result for HybridFile */ private fun parseStringForHybridFile( rawFile: String, path: String, isStat: Boolean ): HybridFileParcelable? { return FileUtils.parseName( if (isStat) rawFile.replace( "('|`)".toRegex(), "" ) else rawFile, isStat )?.apply { this.mode = OpenMode.ROOT this.name = this.path if (path != "/") { this.path = path + "/" + this.path } else { // root of filesystem, don't concat another '/' this.path = path + this.path } if (this.link.trim { it <= ' ' }.isNotEmpty()) { if (isStat) { isDirectory(this).let { this.isDirectory = it if (it) { // stat command symlink includes time stamp at the end // also, stat follows symlink by default if listing is invoked on it // so we don't need link for stat this.link = "" } } } else { NativeOperations.isDirectory(this.link).let { this.isDirectory = it } } } else { this.isDirectory = isDirectory(this) } } } data class ExecuteRootCommandResult(val lines: List<String>, val forcedLs: Boolean) }
gpl-3.0
e4f03573347a7dc3d0ca77d1ab35b20e
37.838346
107
0.539444
5.217677
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/preferences/fragments/Advanced.kt
1
7568
package org.tasks.preferences.fragments import android.app.Activity import android.content.Intent import android.os.Bundle import androidx.lifecycle.lifecycleScope import androidx.preference.Preference import androidx.preference.SwitchPreferenceCompat import com.todoroo.astrid.dao.Database import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import org.tasks.LocalBroadcastManager import org.tasks.PermissionUtil import org.tasks.R import org.tasks.caldav.VtodoCache import org.tasks.calendars.CalendarEventProvider import org.tasks.data.TaskDao import org.tasks.etebase.EtebaseLocalCache import org.tasks.extensions.Context.toast import org.tasks.files.FileHelper import org.tasks.injection.InjectingPreferenceFragment import org.tasks.preferences.FragmentPermissionRequestor import org.tasks.preferences.PermissionChecker import org.tasks.preferences.PermissionRequestor import org.tasks.preferences.Preferences import org.tasks.scheduling.CalendarNotificationIntentService import javax.inject.Inject private const val REQUEST_CODE_FILES_DIR = 10000 @AndroidEntryPoint class Advanced : InjectingPreferenceFragment() { @Inject lateinit var preferences: Preferences @Inject lateinit var database: Database @Inject lateinit var taskDao: TaskDao @Inject lateinit var calendarEventProvider: CalendarEventProvider @Inject lateinit var permissionRequester: FragmentPermissionRequestor @Inject lateinit var permissionChecker: PermissionChecker @Inject lateinit var localBroadcastManager: LocalBroadcastManager @Inject lateinit var vtodoCache: VtodoCache private lateinit var calendarReminderPreference: SwitchPreferenceCompat override fun getPreferenceXml() = R.xml.preferences_advanced override suspend fun setupPreferences(savedInstanceState: Bundle?) { findPreference(R.string.p_use_paged_queries) .setOnPreferenceChangeListener { _: Preference?, _: Any? -> localBroadcastManager.broadcastRefresh() true } findPreference(R.string.EPr_manage_delete_completed_gcal) .setOnPreferenceClickListener { deleteCompletedEvents() false } findPreference(R.string.EPr_manage_delete_all_gcal) .setOnPreferenceClickListener { deleteAllCalendarEvents() false } findPreference(R.string.EPr_reset_preferences) .setOnPreferenceClickListener { resetPreferences() false } findPreference(R.string.EPr_delete_task_data) .setOnPreferenceClickListener { deleteTaskData() false } findPreference(R.string.p_attachment_dir) .setOnPreferenceClickListener { FileHelper.newDirectoryPicker( this, REQUEST_CODE_FILES_DIR, preferences.attachmentsDirectory ) false } updateAttachmentDirectory() calendarReminderPreference = findPreference(R.string.p_calendar_reminders) as SwitchPreferenceCompat initializeCalendarReminderPreference() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_CODE_FILES_DIR) { if (resultCode == Activity.RESULT_OK) { val uri = data!!.data!! requireContext().contentResolver .takePersistableUriPermission( uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION ) preferences.setUri(R.string.p_attachment_dir, uri) updateAttachmentDirectory() } } else { super.onActivityResult(requestCode, resultCode, data) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String?>, grantResults: IntArray ) { if (requestCode == PermissionRequestor.REQUEST_CALENDAR) { if (PermissionUtil.verifyPermissions(grantResults)) { calendarReminderPreference.isChecked = true } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } private fun initializeCalendarReminderPreference() { calendarReminderPreference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> if (newValue == null) { false } else if (!(newValue as Boolean)) { true } else if (permissionRequester.requestCalendarPermissions()) { CalendarNotificationIntentService.enqueueWork(context) true } else { false } } calendarReminderPreference.isChecked = calendarReminderPreference.isChecked && permissionChecker.canAccessCalendars() } private fun updateAttachmentDirectory() { findPreference(R.string.p_attachment_dir).summary = FileHelper.uri2String(preferences.attachmentsDirectory) } private fun deleteCompletedEvents() { dialogBuilder .newDialog() .setMessage(R.string.EPr_manage_delete_completed_gcal_message) .setPositiveButton(R.string.ok) { _, _ -> performAction(R.string.EPr_manage_delete_gcal_status) { calendarEventProvider.deleteEvents(taskDao.getCompletedCalendarEvents()) taskDao.clearCompletedCalendarEvents() } } .setNegativeButton(R.string.cancel, null) .show() } private fun deleteAllCalendarEvents() { dialogBuilder .newDialog() .setMessage(R.string.EPr_manage_delete_all_gcal_message) .setPositiveButton(R.string.ok) { _, _ -> performAction( R.string.EPr_manage_delete_gcal_status) { calendarEventProvider.deleteEvents(taskDao.getAllCalendarEvents()) taskDao.clearAllCalendarEvents() } } .setNegativeButton(R.string.cancel, null) .show() } private fun performAction(message: Int, callable: suspend () -> Int) = lifecycleScope.launch { context?.toast(message, callable()) } private fun resetPreferences() { dialogBuilder .newDialog() .setMessage(R.string.EPr_reset_preferences_warning) .setPositiveButton(R.string.EPr_reset_preferences) { _, _ -> preferences.reset() restart() } .setNegativeButton(R.string.cancel, null) .show() } private fun deleteTaskData() { dialogBuilder .newDialog() .setMessage(R.string.EPr_delete_task_data_warning) .setPositiveButton(R.string.EPr_delete_task_data) { _, _ -> val context = requireContext() context.deleteDatabase(database.name) vtodoCache.clear() EtebaseLocalCache.clear(context) restart() } .setNegativeButton(R.string.cancel, null) .show() } }
gpl-3.0
0932e67a5b47edfb4ada2bb347b1966c
35.917073
103
0.626057
5.480087
false
false
false
false
rcgroot/open-gpstracker-ng
studio/wear/src/main/java/nl/sogeti/android/gpstracker/v2/wear/databinding/WearBindingAdapters.kt
1
4974
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: René de Groot ** Copyright: (c) 2017 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.v2.wear.databinding import androidx.databinding.BindingAdapter import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import android.text.SpannableString import android.text.style.RelativeSizeSpan import android.widget.ImageView import android.widget.TextView import nl.sogeti.android.gpstracker.v2.sharedwear.util.LocaleProvider import nl.sogeti.android.gpstracker.v2.sharedwear.util.StatisticsFormatter import nl.sogeti.android.gpstracker.v2.sharedwear.util.TimeSpanCalculator import nl.sogeti.android.gpstracker.v2.wear.Control import nl.sogeti.android.gpstracker.v2.wear.R class WearBindingAdapters { private val statisticsFormatting by lazy { StatisticsFormatter(LocaleProvider(), TimeSpanCalculator()) } @BindingAdapter("android:src") fun setImageResource(imageView: ImageView, resId: Int) { imageView.setImageResource(resId) } @BindingAdapter("android:src") fun setControl(view: ImageView, control: Control?) { val id = control?.iconId if (id != null) { view.setImageResource(id) view.isEnabled = control.enabled view.alpha = if (control.enabled) 1.0F else 0.5F } else { view.setImageDrawable(null) view.isEnabled = false view.alpha = 0.5F } } @BindingAdapter("enabled") fun setEnables(view: androidx.swiperefreshlayout.widget.SwipeRefreshLayout, enabled: Boolean) { view.isEnabled = enabled } @BindingAdapter("duration") fun setDuration(textView: TextView, timeStamp: Long?) { if (timeStamp == null || timeStamp <= 0L) { textView.text = textView.context.getText(R.string.empty_dash) } else { textView.text = statisticsFormatting.convertSpanToCompactDuration(textView.context, timeStamp) .replace(' ', '\n') .asSmallLetterSpans() } } @BindingAdapter("distance") fun setDistance(textView: TextView, distance: Float?) { if (distance == null || distance <= 0L) { textView.text = textView.context.getText(R.string.empty_dash) } else { textView.text = statisticsFormatting.convertMetersToDistance(textView.context, distance) .replace(' ', '\n') .asSmallLetterSpans() } } @BindingAdapter("speed", "inverse") fun setSpeed(textView: TextView, speed: Float?, inverse: Boolean?) { if (speed == null || speed <= 0L) { textView.text = textView.context.getText(R.string.empty_dash) } else { textView.text = statisticsFormatting.convertMeterPerSecondsToSpeed(textView.context, speed, inverse ?: false) .replace(' ', '\n') .asSmallLetterSpans() } } private fun String.asSmallLetterSpans(): SpannableString { val spannable = SpannableString(this) var start: Int? = null for (i in 0 until this.length) { if (!this[i].isDigit() && start == null) { start = i } if (this[i].isDigit() && start != null) { spannable.setSpan(RelativeSizeSpan(0.5f), start, i, 0) start = null } } if (start != null) { spannable.setSpan(RelativeSizeSpan(0.5f), start, this.length, 0) } return spannable } }
gpl-3.0
ce9d6a8716e73c2f3eb555358b988ab4
38.784
121
0.610095
4.638993
false
false
false
false
goodwinnk/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/inference.kt
1
4347
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.processors.inference import com.intellij.psi.* import com.intellij.psi.util.PsiUtil.extractIterableTypeParameter import com.intellij.util.ArrayUtil import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult import org.jetbrains.plugins.groovy.lang.psi.api.SpreadState import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrEnumConstant import org.jetbrains.plugins.groovy.lang.psi.impl.GrMapType import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil.getQualifierType import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint import java.util.* fun getTopLevelType(expression: GrExpression): PsiType? { if (expression is GrMethodCall) { val resolved = expression.advancedResolve() (resolved as? GroovyMethodResult)?.candidate?.let { val session = GroovyInferenceSessionBuilder(expression.invokedExpression as GrReferenceExpression, it) .resolveMode(false) .build() return session.inferSubst().substitute(PsiUtil.getSmartReturnType(it.method)) } } if (expression is GrClosableBlock) { return TypesUtil.createTypeByFQClassName(GroovyCommonClassNames.GROOVY_LANG_CLOSURE, expression) } return expression.type } fun getTopLevelTypeCached(expression: GrExpression): PsiType? { return GroovyPsiManager.getInstance(expression.project).getTopLevelType(expression) } fun buildQualifier(ref: GrReferenceExpression, state: ResolveState): Argument { val qualifierExpression = ref.qualifierExpression val spreadState = state[SpreadState.SPREAD_STATE] if (qualifierExpression != null && spreadState == null) { return Argument(null, qualifierExpression) } val resolvedThis = state[ClassHint.THIS_TYPE] if (resolvedThis != null) { return Argument(resolvedThis, null) } val type = getQualifierType(ref) when { spreadState == null -> return Argument(type, null) type == null -> return Argument(null, null) else -> return Argument(extractIterableTypeParameter(type, false), null) } } fun buildArguments(place: PsiElement): List<Argument> { val parent = place as? GrEnumConstant ?: place.parent if (parent is GrCall) { val result = ArrayList<Argument>() val namedArgs = parent.namedArguments val expressions = parent.expressionArguments val closures = parent.closureArguments if (namedArgs.isNotEmpty()) { val context = namedArgs[0] result.add(Argument(GrMapType.createFromNamedArgs(context, namedArgs), null)) } val argExp = ArrayUtil.mergeArrays(expressions, closures) result.addAll(argExp.map { exp -> Argument(null, exp) }) return result } val argumentTypes = PsiUtil.getArgumentTypes(place, false, null) ?: return emptyList() return argumentTypes.map { t -> Argument(t, null) } } fun buildTopLevelArgumentTypes(place: PsiElement): Array<PsiType?> { return buildArguments(place).map { (type, expression) -> if (expression != null) { getTopLevelTypeCached(expression) } else { if (type is GrMapType) { TypesUtil.createTypeByFQClassName(CommonClassNames.JAVA_UTIL_MAP, place) } else { type } } }.toTypedArray() } fun PsiSubstitutor.putAll(parameters: Array<out PsiTypeParameter>, arguments: Array<out PsiType>): PsiSubstitutor { if (arguments.size != parameters.size) return this return parameters.zip(arguments).fold(this) { acc, (param, arg) -> acc.put(param, arg) } }
apache-2.0
08987f31315ee1c29fb66065f9ace0c3
38.518182
140
0.764435
4.183831
false
false
false
false
nextcloud/android
app/src/main/java/com/nextcloud/client/media/PlayerServiceConnection.kt
1
4822
/** * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2019 Chris Narkiewicz <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.media import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Build import android.os.IBinder import android.widget.MediaController import com.nextcloud.client.account.User import com.owncloud.android.datamodel.OCFile import java.lang.IllegalStateException @Suppress("TooManyFunctions") // implementing large interface class PlayerServiceConnection(private val context: Context) : MediaController.MediaPlayerControl { var isConnected: Boolean = false private set private var binder: PlayerService.Binder? = null fun bind() { val intent = Intent(context, PlayerService::class.java) context.bindService(intent, connection, Context.BIND_AUTO_CREATE) } fun unbind() { if (isConnected) { binder = null isConnected = false context.unbindService(connection) } } fun start(user: User, file: OCFile, playImmediately: Boolean, position: Long) { val i = Intent(context, PlayerService::class.java) i.putExtra(PlayerService.EXTRA_USER, user) i.putExtra(PlayerService.EXTRA_FILE, file) i.putExtra(PlayerService.EXTRA_AUTO_PLAY, playImmediately) i.putExtra(PlayerService.EXTRA_START_POSITION_MS, position) i.action = PlayerService.ACTION_PLAY startForegroundService(i) } fun stop(file: OCFile) { val i = Intent(context, PlayerService::class.java) i.putExtra(PlayerService.EXTRA_FILE, file) i.action = PlayerService.ACTION_STOP_FILE try { context.startService(i) } catch (ex: IllegalStateException) { // https://developer.android.com/about/versions/oreo/android-8.0-changes#back-all // ignore it - the service is not running and does not need to be stopped } } fun stop() { val i = Intent(context, PlayerService::class.java) i.action = PlayerService.ACTION_STOP try { context.startService(i) } catch (ex: IllegalStateException) { // https://developer.android.com/about/versions/oreo/android-8.0-changes#back-all // ignore it - the service is not running and does not need to be stopped } } private val connection = object : ServiceConnection { override fun onServiceDisconnected(name: ComponentName?) { isConnected = false binder = null } override fun onServiceConnected(name: ComponentName?, localBinder: IBinder?) { binder = localBinder as PlayerService.Binder isConnected = true } } // region Media controller override fun isPlaying(): Boolean { return binder?.player?.isPlaying ?: false } override fun canSeekForward(): Boolean { return binder?.player?.canSeekForward() ?: false } override fun getDuration(): Int { return binder?.player?.duration ?: 0 } override fun pause() { binder?.player?.pause() } override fun getBufferPercentage(): Int { return binder?.player?.bufferPercentage ?: 0 } override fun seekTo(pos: Int) { binder?.player?.seekTo(pos) } override fun getCurrentPosition(): Int { return binder?.player?.currentPosition ?: 0 } override fun canSeekBackward(): Boolean { return binder?.player?.canSeekBackward() ?: false } override fun start() { binder?.player?.start() } override fun getAudioSessionId(): Int { return 0 } override fun canPause(): Boolean { return binder?.player?.canPause() ?: false } // endregion private fun startForegroundService(i: Intent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(i) } else { context.startService(i) } } }
gpl-2.0
53b3edbeb709f7b92e38980b842a5bfd
30.311688
98
0.660514
4.623202
false
false
false
false
goodwinnk/intellij-community
platform/credential-store/src/PasswordSafeImpl.kt
1
6063
// 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. @file:Suppress("PackageDirectoryMismatch") package com.intellij.ide.passwordSafe.impl import com.intellij.credentialStore.* import com.intellij.ide.passwordSafe.PasswordSafe import com.intellij.ide.passwordSafe.PasswordStorage import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.SettingsSavingComponent import com.intellij.openapi.diagnostic.runAndLogException import org.jetbrains.annotations.TestOnly import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.runAsync import java.nio.file.Paths private fun computeProvider(settings: PasswordSafeSettings): CredentialStore { if (settings.providerType == ProviderType.MEMORY_ONLY || (ApplicationManager.getApplication()?.isUnitTestMode == true)) { return KeePassCredentialStore(memoryOnly = true) } else if (settings.providerType == ProviderType.KEEPASS) { val dbFile = settings.state.keepassDb?.let { LOG.runAndLogException { Paths.get(it) } } return KeePassCredentialStore(dbFile = dbFile) } else { return createPersistentCredentialStore() } } class PasswordSafeImpl @JvmOverloads constructor(val settings: PasswordSafeSettings /* public - backward compatibility */, provider: CredentialStore? = null) : PasswordSafe(), SettingsSavingComponent { override var isRememberPasswordByDefault: Boolean get() = settings.state.isRememberPasswordByDefault set(value) { settings.state.isRememberPasswordByDefault = value } private var _currentProvider: Lazy<CredentialStore> = if (provider == null) lazy { computeProvider(settings) } else lazyOf(provider) internal var currentProvider: CredentialStore get() = _currentProvider.value set(value) { _currentProvider = lazyOf(value) } // it is helper storage to support set password as memory-only (see setPassword memoryOnly flag) private val memoryHelperProvider = lazy { KeePassCredentialStore(emptyMap(), memoryOnly = true) } override val isMemoryOnly: Boolean get() = settings.providerType == ProviderType.MEMORY_ONLY override fun get(attributes: CredentialAttributes): Credentials? { val value = currentProvider.get(attributes) if ((value == null || value.password.isNullOrEmpty()) && memoryHelperProvider.isInitialized()) { // if password was set as `memoryOnly` memoryHelperProvider.value.get(attributes)?.let { if (!it.isEmpty()) { return it } } } return value } override fun set(attributes: CredentialAttributes, credentials: Credentials?) { currentProvider.set(attributes, credentials) if (attributes.isPasswordMemoryOnly && !credentials?.password.isNullOrEmpty()) { // we must store because otherwise on get will be no password memoryHelperProvider.value.set(attributes.toPasswordStoreable(), credentials) } else if (memoryHelperProvider.isInitialized()) { memoryHelperProvider.value.set(attributes, null) } } override fun set(attributes: CredentialAttributes, credentials: Credentials?, memoryOnly: Boolean) { if (memoryOnly) { memoryHelperProvider.value.set(attributes.toPasswordStoreable(), credentials) // remove to ensure that on getPassword we will not return some value from default provider currentProvider.set(attributes, null) } else { set(attributes, credentials) } } // maybe in the future we will use native async, so, this method added here instead "if need, just use runAsync in your code" override fun getAsync(attributes: CredentialAttributes): Promise<Credentials?> = runAsync { get(attributes) } override fun save() { val provider = _currentProvider if (provider.isInitialized()) { (provider.value as? KeePassCredentialStore)?.save() } } fun clearPasswords() { LOG.info("Passwords cleared", Error()) try { if (memoryHelperProvider.isInitialized()) { memoryHelperProvider.value.clear() } } finally { (currentProvider as? KeePassCredentialStore)?.clear() } ApplicationManager.getApplication().messageBus.syncPublisher(PasswordSafeSettings.TOPIC).credentialStoreCleared() } override fun isPasswordStoredOnlyInMemory(attributes: CredentialAttributes, credentials: Credentials): Boolean { if (isMemoryOnly || credentials.password.isNullOrEmpty()) { return true } if (!memoryHelperProvider.isInitialized()) { return false } return memoryHelperProvider.value.get(attributes)?.let { !it.password.isNullOrEmpty() } ?: false } // public - backward compatibility @Suppress("unused", "DeprecatedCallableAddReplaceWith") @Deprecated("Do not use it") val masterKeyProvider: CredentialStore get() = currentProvider @Suppress("unused") @Deprecated("Do not use it") // public - backward compatibility val memoryProvider: PasswordStorage get() = memoryHelperProvider.value } internal fun createPersistentCredentialStore(existing: KeePassCredentialStore? = null, convertFileStore: Boolean = false): PasswordStorage { LOG.runAndLogException { for (factory in CredentialStoreFactory.CREDENTIAL_STORE_FACTORY.extensions) { val store = factory.create() ?: continue if (convertFileStore) { LOG.runAndLogException { val fileStore = KeePassCredentialStore() fileStore.copyTo(store) fileStore.clear() fileStore.save() } } return store } } existing?.let { it.memoryOnly = false return it } return KeePassCredentialStore() } @TestOnly internal fun createKeePassStore(file: String): PasswordSafe = PasswordSafeImpl( PasswordSafeSettings().apply { loadState(PasswordSafeSettings.State().apply { providerType = ProviderType.KEEPASS; keepassDb = file }) }, KeePassCredentialStore(dbFile = Paths.get(file)))
apache-2.0
9554e3ee9445d8bfcd16283b65df9ece
35.751515
141
0.725878
4.766509
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/forge/ForgeModuleType.kt
1
1745
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.forge import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.AbstractModuleType import com.demonwav.mcdev.platform.PlatformType import com.demonwav.mcdev.platform.forge.util.ForgeConstants import com.demonwav.mcdev.util.SemanticVersion import com.intellij.psi.PsiClass object ForgeModuleType : AbstractModuleType<ForgeModule>("", "") { private const val ID = "FORGE_MODULE_TYPE" private val IGNORED_ANNOTATIONS = listOf( ForgeConstants.MOD_ANNOTATION, ForgeConstants.EVENT_HANDLER_ANNOTATION, ForgeConstants.SUBSCRIBE_EVENT_ANNOTATION, ForgeConstants.EVENTBUS_SUBSCRIBE_EVENT_ANNOTATION ) private val LISTENER_ANNOTATIONS = listOf( ForgeConstants.EVENT_HANDLER_ANNOTATION, ForgeConstants.SUBSCRIBE_EVENT_ANNOTATION, ForgeConstants.EVENTBUS_SUBSCRIBE_EVENT_ANNOTATION ) override val platformType = PlatformType.FORGE override val icon = PlatformAssets.FORGE_ICON override val id = ID override val ignoredAnnotations = IGNORED_ANNOTATIONS override val listenerAnnotations = LISTENER_ANNOTATIONS override val isEventGenAvailable = true override fun generateModule(facet: MinecraftFacet) = ForgeModule(facet) override fun getDefaultListenerName(psiClass: PsiClass): String = defaultNameForSubClassEvents(psiClass) val FG23_MC_VERSION = SemanticVersion.release(1, 12) val FG3_MC_VERSION = SemanticVersion.release(1, 13) val FG3_FORGE_VERSION = SemanticVersion.release(14, 23, 5, 2851) }
mit
317c3ae1af85b943faa9895af7068706
33.9
108
0.762751
4.340796
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/tiled/TiledMapReader.kt
1
23336
package com.soywiz.korge.tiled import com.soywiz.kds.* import com.soywiz.kds.iterators.* import com.soywiz.klock.* import com.soywiz.kmem.* import com.soywiz.korge.tiled.TiledMap.* import com.soywiz.korge.tiled.TiledMap.Image import com.soywiz.korge.view.* import com.soywiz.korge.view.tiles.* import com.soywiz.korim.atlas.* import com.soywiz.korim.bitmap.* import com.soywiz.korim.color.* import com.soywiz.korim.format.* import com.soywiz.korio.compression.* import com.soywiz.korio.compression.deflate.* import com.soywiz.korio.file.* import com.soywiz.korio.lang.* import com.soywiz.korio.serialization.xml.* import com.soywiz.korma.geom.* import com.soywiz.korma.geom.shape.* import com.soywiz.krypto.encoding.* import kotlin.collections.set suspend fun VfsFile.readTiledMap( hasTransparentColor: Boolean = false, transparentColor: RGBA = Colors.FUCHSIA, createBorder: Int = 1, atlas: MutableAtlasUnit? = null ): TiledMap { val folder = this.parent.jail() val data = readTiledMapData() val tiledTilesets = arrayListOf<TiledTileset>() data.tilesets.fastForEach { tileset -> tiledTilesets += tileset.toTiledSet(folder, hasTransparentColor, transparentColor, createBorder, atlas = atlas) } return TiledMap(data, tiledTilesets) } suspend fun VfsFile.readTiledSet( firstgid: Int = 1, hasTransparentColor: Boolean = false, transparentColor: RGBA = Colors.FUCHSIA, createBorder: Int = 1, atlas: MutableAtlasUnit? = null, ): TiledTileset { return readTileSetData(firstgid).toTiledSet(this.parent, hasTransparentColor, transparentColor, createBorder, atlas) } suspend fun VfsFile.readTiledSetData(firstgid: Int = 1): TileSetData { return parseTileSetData(this.readXml(), firstgid, this.baseName) } @Deprecated("Use readTiledSetData", ReplaceWith("readTiledSetData(firstgid)")) suspend fun VfsFile.readTileSetData(firstgid: Int = 1): TileSetData = readTiledSetData(firstgid) suspend fun TileSetData.toTiledSet( folder: VfsFile, hasTransparentColor: Boolean = false, transparentColor: RGBA = Colors.FUCHSIA, createBorder: Int = 1, atlas: MutableAtlasUnit? = null ): TiledTileset { val atlas = when { atlas != null -> atlas createBorder > 0 -> MutableAtlas(2048, border = createBorder.clamp(1, 4)) else -> null } val tileset = this var bmp = try { when (tileset.image) { is Image.Embedded -> TODO() is Image.External -> folder[tileset.image.source].readBitmapOptimized() .let { if (atlas != null) it.toBMP32IfRequired() else it } null -> Bitmap32(0, 0) } } catch (e: Throwable) { e.printStackTrace() Bitmap32(tileset.width, tileset.height) } // @TODO: Preprocess this, so in JS we don't have to do anything! if (hasTransparentColor) { bmp = bmp.toBMP32() for (n in 0 until bmp.area) { if (bmp.data[n] == transparentColor) bmp.data[n] = Colors.TRANSPARENT_BLACK } } val collisionsMap = IntMap<TileShapeInfo>() tileset.tiles.fastForEach { tile -> val collisionType = HitTestDirectionFlags.fromString(tile.type, HitTestDirectionFlags.NONE) val vectorPaths = fastArrayListOf<TileShapeInfo>() if (tile.objectGroup != null) { tile.objectGroup.objects.fastForEach { vectorPaths.add( TileShapeInfoImpl( HitTestDirectionFlags.fromString(it.type), it.toShape2dNoTransformed(), it.getTransform(), //it.toVectorPath() ) ) } } //println("tile.objectGroup=${tile.objectGroup}") collisionsMap[tile.id] = object : TileShapeInfo { override fun hitTestAny(x: Double, y: Double, direction: HitTestDirection): Boolean { if (vectorPaths.isNotEmpty()) { vectorPaths.fastForEach { if (it.hitTestAny(x, y, direction)) return true } } return collisionType.matches(direction) } override fun hitTestAny(shape2d: Shape2d, matrix: Matrix, direction: HitTestDirection): Boolean { if (vectorPaths.isNotEmpty()) { vectorPaths.fastForEach { if (it.hitTestAny(shape2d, matrix, direction)) return true } } return collisionType.matches(direction) } override fun toString(): String = "HitTestable[id=${tile.id}]($vectorPaths)" } } val ptileset = when { atlas != null -> { val tileSet = TileSet(bmp.slice(), tileset.tileWidth, tileset.tileHeight, tileset.columns, tileset.tileCount, collisionsMap) val map = IntMap<TileSetTileInfo>() tileSet.infos.fastForEachWithIndex { index, value -> if (value != null) { val tile = tileset.tilesById[value.id] map[index] = value.copy( slice = atlas.add(value.slice, Unit).slice, frames = (tile?.frames ?: emptyList()).map { TileSetAnimationFrame(it.tileId, it.duration.milliseconds) } ) } } TileSet(map, tileset.tileWidth, tileset.tileHeight, collisionsMap) } //createBorder > 0 -> { // bmp = bmp.toBMP32() // if (tileset.spacing >= createBorder) { // // There is already separation between tiles, use it as it is // val slices = TileSet.extractBmpSlices( // bmp, // tileset.tileWidth, // tileset.tileHeight, // tileset.columns, // tileset.tileCount, // tileset.spacing, // tileset.margin // ).mapIndexed { index, bitmapSlice -> TileSetTileInfo(index, bitmapSlice) } // TileSet(slices, tileset.tileWidth, tileset.tileHeight, collisionsMap) // } else { // // No separation between tiles: create a new Bitmap adding that separation // val bitmaps = if (bmp.width != 0 && bmp.height != 0) { // TileSet.extractBmpSlices( // bmp, // tileset.tileWidth, // tileset.tileHeight, // tileset.columns, // tileset.tileCount, // tileset.spacing, // tileset.margin // ) // } else if (tileset.tiles.isNotEmpty()) { // tileset.tiles.map { // when (it.image) { // is Image.Embedded -> TODO() // is Image.External -> { // val file = folder[it.image.source] // file.readBitmapOptimized().toBMP32().slice(name = file.baseName) // } // else -> Bitmap32(0, 0).slice() // } // } // } else { // emptyList() // } // TileSet.fromBitmapSlices(tileset.tileWidth, tileset.tileHeight, bitmaps, border = createBorder, mipmaps = false, collisionsMap = collisionsMap) // } //} else -> { TileSet(bmp.slice(), tileset.tileWidth, tileset.tileHeight, tileset.columns, tileset.tileCount, collisionsMap) } } val tiledTileset = TiledTileset( tileset = ptileset, data = tileset, firstgid = tileset.firstgid ) return tiledTileset } suspend fun VfsFile.readTiledMapData(): TiledMapData { val file = this val folder = this.parent.jail() val tiledMap = TiledMapData() val mapXml = file.readXml() if (mapXml.nameLC != "map") error("Not a TiledMap XML TMX file starting with <map>") //TODO: Support different orientations val orientation = mapXml.getString("orientation") tiledMap.orientation = when (orientation) { "orthogonal" -> TiledMap.Orientation.ORTHOGONAL "staggered" -> TiledMap.Orientation.STAGGERED else -> unsupported("Orientation \"$orientation\" is not supported") } val renderOrder = mapXml.getString("renderorder") tiledMap.renderOrder = when (renderOrder) { "right-down" -> RenderOrder.RIGHT_DOWN "right-up" -> RenderOrder.RIGHT_UP "left-down" -> RenderOrder.LEFT_DOWN "left-up" -> RenderOrder.LEFT_UP else -> RenderOrder.RIGHT_DOWN } tiledMap.compressionLevel = mapXml.getInt("compressionlevel") ?: -1 tiledMap.width = mapXml.getInt("width") ?: 0 tiledMap.height = mapXml.getInt("height") ?: 0 tiledMap.tilewidth = mapXml.getInt("tilewidth") ?: 32 tiledMap.tileheight = mapXml.getInt("tileheight") ?: 32 tiledMap.hexSideLength = mapXml.getInt("hexsidelength") val staggerAxis = mapXml.getString("staggeraxis") tiledMap.staggerAxis = when (staggerAxis) { "x" -> StaggerAxis.X "y" -> StaggerAxis.Y else -> null } val staggerIndex = mapXml.getString("staggerindex") tiledMap.staggerIndex = when (staggerIndex) { "even" -> StaggerIndex.EVEN "odd" -> StaggerIndex.ODD else -> null } tiledMap.backgroundColor = mapXml.getString("backgroundcolor")?.let { colorFromARGB(it, Colors.TRANSPARENT_BLACK) } val nextLayerId = mapXml.getInt("nextlayerid") val nextObjectId = mapXml.getInt("nextobjectid") tiledMap.infinite = mapXml.getInt("infinite") == 1 mapXml.child("properties")?.parseProperties()?.let { tiledMap.properties.putAll(it) } tilemapLog.trace { "tilemap: width=${tiledMap.width}, height=${tiledMap.height}, tilewidth=${tiledMap.tilewidth}, tileheight=${tiledMap.tileheight}" } tilemapLog.trace { "tilemap: $tiledMap" } val elements = mapXml.allChildrenNoComments tilemapLog.trace { "tilemap: elements=${elements.size}" } tilemapLog.trace { "tilemap: elements=$elements" } elements.fastForEach { element -> when (element.nameLC) { "tileset" -> { tilemapLog.trace { "tileset" } val firstgid = element.int("firstgid", 1) val sourcePath = element.getString("source") val tileset = if (sourcePath != null) folder[sourcePath].readXml() else element tiledMap.tilesets += parseTileSetData(tileset, firstgid, sourcePath) } "layer" -> { val layer = element.parseTileLayer(tiledMap.infinite) tiledMap.allLayers += layer } "objectgroup" -> { val layer = element.parseObjectLayer() tiledMap.allLayers += layer } "imagelayer" -> { val layer = element.parseImageLayer() tiledMap.allLayers += layer } "group" -> { val layer = element.parseGroupLayer(tiledMap.infinite) tiledMap.allLayers += layer } "editorsettings" -> { val chunkSize = element.child("chunksize") tiledMap.editorSettings = EditorSettings( chunkWidth = chunkSize?.int("width", 16) ?: 16, chunkHeight = chunkSize?.int("height", 16) ?: 16 ) } } } tiledMap.nextLayerId = nextLayerId ?: run { var maxLayerId = 0 for (layer in tiledMap.allLayers) { if (layer.id > maxLayerId) maxLayerId = layer.id } maxLayerId + 1 } tiledMap.nextObjectId = nextObjectId ?: run { var maxObjectId = 0 for (objects in tiledMap.objectLayers) { for (obj in objects.objects) { if (obj.id > maxObjectId) maxObjectId = obj.id } } maxObjectId + 1 } return tiledMap } fun parseTileSetData(tileset: Xml, firstgid: Int, tilesetSource: String? = null): TileSetData { val alignment = tileset.str("objectalignment", "unspecified") val objectAlignment = ObjectAlignment.values().find { it.value == alignment } ?: ObjectAlignment.UNSPECIFIED val tileOffset = tileset.child("tileoffset") return TileSetData( name = tileset.str("name"), firstgid = firstgid, tileWidth = tileset.int("tilewidth"), tileHeight = tileset.int("tileheight"), tileCount = tileset.int("tilecount", 0), spacing = tileset.int("spacing", 0), margin = tileset.int("margin", 0), columns = tileset.int("columns", 0), image = tileset.child("image")?.parseImage(), tileOffsetX = tileOffset?.int("x") ?: 0, tileOffsetY = tileOffset?.int("y") ?: 0, grid = tileset.child("grid")?.parseGrid(), tilesetSource = tilesetSource, objectAlignment = objectAlignment, terrains = tileset.children("terraintypes").children("terrain").map { it.parseTerrain() }, wangsets = tileset.children("wangsets").children("wangset").map { it.parseWangSet() }, properties = tileset.child("properties")?.parseProperties() ?: mapOf(), tiles = tileset.children("tile").map { it.parseTile() } ) } private fun Xml.parseTile(): TileData { val tile = this fun Xml.parseFrame(): AnimationFrameData { return AnimationFrameData(this.int("tileid"), this.int("duration")) } return TileData( id = tile.int("id"), type = tile.strNull("type"), terrain = tile.str("terrain").takeIf { it.isNotEmpty() }?.split(',')?.map { it.toIntOrNull() }, probability = tile.double("probability"), image = tile.child("image")?.parseImage(), properties = tile.child("properties")?.parseProperties() ?: mapOf(), objectGroup = tile.child("objectgroup")?.parseObjectLayer(), frames = tile.child("animation")?.children("frame")?.map { it.parseFrame() } ) } private fun Xml.parseTerrain(): TerrainData { return TerrainData( name = str("name"), tile = int("tile"), properties = parseProperties() ) } private fun Xml.parseWangSet(): WangSet { fun Xml.parseWangColor(): WangSet.WangColor { val wangcolor = this return WangSet.WangColor( name = wangcolor.str("name"), color = Colors[wangcolor.str("color")], tileId = wangcolor.int("tile"), probability = wangcolor.double("probability") ) } fun Xml.parseWangTile(): WangSet.WangTile { val wangtile = this val hflip = wangtile.str("hflip") val vflip = wangtile.str("vflip") val dflip = wangtile.str("dflip") return WangSet.WangTile( tileId = wangtile.int("tileid"), wangId = wangtile.int("wangid"), hflip = hflip == "1" || hflip == "true", vflip = vflip == "1" || vflip == "true", dflip = dflip == "1" || dflip == "true" ) } val wangset = this return WangSet( name = wangset.str("name"), tileId = wangset.int("tile"), properties = wangset.parseProperties(), cornerColors = wangset.children("wangcornercolor").map { it.parseWangColor() }, edgeColors = wangset.children("wangedgecolor").map { it.parseWangColor() }, wangtiles = wangset.children("wangtile").map { it.parseWangTile() } ) } private fun Xml.parseGrid(): Grid { val grid = this val orientation = grid.str("orientation") return Grid( cellWidth = grid.int("width"), cellHeight = grid.int("height"), orientation = Grid.Orientation.values().find { it.value == orientation } ?: Grid.Orientation.ORTHOGONAL ) } private fun Xml.parseCommonLayerData(layer: Layer) { val element = this layer.id = element.int("id") layer.name = element.str("name") layer.opacity = element.double("opacity", 1.0) layer.visible = element.int("visible", 1) == 1 layer.locked = element.int("locked", 0) == 1 layer.tintColor = element.strNull("tintcolor")?.let { colorFromARGB(it, Colors.WHITE) } layer.offsetx = element.double("offsetx") layer.offsety = element.double("offsety") element.child("properties")?.parseProperties()?.let { layer.properties.putAll(it) } } private fun Xml.parseTileLayer(infinite: Boolean): Layer.Tiles { val layer = Layer.Tiles() parseCommonLayerData(layer) val element = this val width = element.int("width") val height = element.int("height") val data = element.child("data") val map: Bitmap32 val encoding: Encoding val compression: Compression if (data == null) { map = Bitmap32(width, height) encoding = Encoding.CSV compression = Compression.NO } else { val enc = data.strNull("encoding") val com = data.strNull("compression") encoding = Encoding.values().find { it.value == enc } ?: Encoding.XML compression = Compression.values().find { it.value == com } ?: Compression.NO val count = width * height fun Xml.encodeGids(): IntArray = when (encoding) { Encoding.XML -> { // @TODO: Bug on Kotlin-JS 1.4.0 release //children("tile").map { it.uint("gid").toInt() }.toIntArray() children("tile").map { it.double("gid").toInt() }.toIntArray() } Encoding.CSV -> { // @TODO: Bug on Kotlin-JS 1.4.0 release //text.replace(spaces, "").split(',').map { it.toUInt().toInt() }.toIntArray() text.replace(spaces, "").split(',').map { it.toDouble().toInt() }.toIntArray() } Encoding.BASE64 -> { val rawContent = text.trim().fromBase64() val content = when (compression) { Compression.NO -> rawContent Compression.GZIP -> rawContent.uncompress(GZIP) Compression.ZLIB -> rawContent.uncompress(ZLib) //TODO: support "zstd" compression //Data.Compression.ZSTD -> rawContent.uncompress(ZSTD) else -> invalidOp("Unknown compression '$compression'") } //TODO: read UIntArray content.readIntArrayLE(0, count) } } val tiles: IntArray if (infinite) { tiles = IntArray(count) data.children("chunk").forEach { chunk -> val offsetX = chunk.int("x") val offsetY = chunk.int("y") val cwidth = chunk.int("width") val cheight = chunk.int("height") chunk.encodeGids().forEachIndexed { i, gid -> val x = offsetX + i % cwidth val y = offsetY + i / cwidth tiles[x + y * (offsetX + cwidth)] = gid } } } else { tiles = data.encodeGids() } map = Bitmap32(width, height, RgbaArray(tiles)) } layer.map = map layer.encoding = encoding layer.compression = compression return layer } private fun Xml.parseObjectLayer(): Layer.Objects { val layer = Layer.Objects() parseCommonLayerData(layer) val element = this val order = element.str("draworder", "topdown") layer.color = colorFromARGB(element.str("color"), Colors["#a0a0a4"]) layer.drawOrder = Object.DrawOrder.values().find { it.value == order } ?: Object.DrawOrder.TOP_DOWN for (obj in element.children("object")) { val objInstance = Object( id = obj.int("id"), gid = obj.intNull("gid"), name = obj.str("name"), type = obj.str("type"), bounds = obj.run { Rectangle(double("x"), double("y"), double("width"), double("height")) }, rotation = obj.double("rotation"), visible = obj.int("visible", 1) != 0 //TODO: support object templates //templatePath = obj.strNull("template") ) obj.child("properties")?.parseProperties()?.let { objInstance.properties.putAll(it) } fun Xml.readPoints() = str("points").split(spaces).map { xy -> val parts = xy.split(',').map { it.trim().toDoubleOrNull() ?: 0.0 } Point(parts[0], parts[1]) } val ellipse = obj.child("ellipse") val point = obj.child("point") val polygon = obj.child("polygon") val polyline = obj.child("polyline") val text = obj.child("text") val objectShape: Object.Shape = when { ellipse != null -> Object.Shape.Ellipse(objInstance.bounds.width, objInstance.bounds.height) point != null -> Object.Shape.PPoint polygon != null -> Object.Shape.Polygon(polygon.readPoints()) polyline != null -> Object.Shape.Polyline(polyline.readPoints()) text != null -> Object.Shape.Text( fontFamily = text.str("fontfamily", "sans-serif"), pixelSize = text.int("pixelsize", 16), wordWrap = text.int("wrap", 0) == 1, color = colorFromARGB(text.str("color"), Colors.BLACK), bold = text.int("bold") == 1, italic = text.int("italic") == 1, underline = text.int("underline") == 1, strikeout = text.int("strikeout") == 1, kerning = text.int("kerning", 1) == 1, hAlign = text.str("halign", "left").let { align -> TextHAlignment.values().find { it.value == align } ?: TextHAlignment.LEFT }, vAlign = text.str("valign", "top").let { align -> TextVAlignment.values().find { it.value == align } ?: TextVAlignment.TOP } ) else -> Object.Shape.Rectangle(objInstance.bounds.width, objInstance.bounds.height) } objInstance.objectShape = objectShape layer.objects.add(objInstance) } return layer } private fun Xml.parseImageLayer(): Layer.Image { val layer = Layer.Image() parseCommonLayerData(layer) layer.image = child("image")?.parseImage() return layer } private fun Xml.parseGroupLayer(infinite: Boolean): Layer.Group { val layer = Layer.Group() parseCommonLayerData(layer) allChildrenNoComments.fastForEach { element -> when (element.nameLC) { "layer" -> { val tileLayer = element.parseTileLayer(infinite) layer.layers += tileLayer } "objectgroup" -> { val objectLayer = element.parseObjectLayer() layer.layers += objectLayer } "imagelayer" -> { val imageLayer = element.parseImageLayer() layer.layers += imageLayer } "group" -> { val groupLayer = element.parseGroupLayer(infinite) layer.layers += groupLayer } } } return layer } private fun Xml.parseImage(): Image? { val image = this val width = image.int("width") val height = image.int("height") val trans = image.str("trans") val transparent = when { trans.isEmpty() -> null trans.startsWith("#") -> Colors[trans] else -> Colors["#$trans"] } val source = image.str("source") return if (source.isNotEmpty()) { Image.External( source = source, width = width, height = height, transparent = transparent ) } else { val data = image.child("data") ?: return null val enc = data.strNull("encoding") val com = data.strNull("compression") val encoding = Encoding.values().find { it.value == enc } ?: Encoding.XML val compression = Compression.values().find { it.value == com } ?: Compression.NO //TODO: read embedded image (png, jpg, etc.) and convert to bitmap val bitmap = Bitmap32(width, height) Image.Embedded( format = image.str("format"), image = bitmap, encoding = encoding, compression = compression, transparent = transparent ) } } private fun Xml.parseProperties(): Map<String, Property> { val out = LinkedHashMap<String, Property>() for (property in this.children("property")) { val pname = property.str("name") val rawValue = property.strNull("value") ?: property.text val type = property.str("type", "string") val pvalue = when (type) { "string" -> Property.StringT(rawValue) "int" -> Property.IntT(rawValue.toIntOrNull() ?: 0) "float" -> Property.FloatT(rawValue.toDoubleOrNull() ?: 0.0) "bool" -> Property.BoolT(rawValue == "true") "color" -> Property.ColorT(colorFromARGB(rawValue, Colors.TRANSPARENT_BLACK)) "file" -> Property.FileT(if (rawValue.isEmpty()) "." else rawValue) "object" -> Property.ObjectT(rawValue.toIntOrNull() ?: 0) else -> Property.StringT(rawValue) } out[pname] = pvalue } return out } //TODO: move to korim fun colorFromARGB(color: String, default: RGBA): RGBA { if (!color.startsWith('#') || color.length != 9 && color.length != 7) return default val hex = color.substring(1) val start = if (color.length == 7) 0 else 2 val a = if (color.length == 9) hex.substr(0, 2).toInt(16) else 0xFF val r = hex.substr(start + 0, 2).toInt(16) val g = hex.substr(start + 2, 2).toInt(16) val b = hex.substr(start + 4, 2).toInt(16) return RGBA(r, g, b, a) } private val spaces = Regex("\\s+")
apache-2.0
e473ae2c1f98c3fea7257e03f852e6a7
33.217009
161
0.64017
3.543274
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/MastodonSearchLoader.kt
1
2817
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.loader import android.accounts.AccountManager import android.content.Context import android.support.v4.content.FixedAsyncTaskLoader import de.vanita5.microblog.library.MicroBlogException import de.vanita5.microblog.library.mastodon.Mastodon import de.vanita5.twittnuker.Constants import de.vanita5.twittnuker.exception.AccountNotFoundException import de.vanita5.twittnuker.extension.model.api.mastodon.toParcelable import de.vanita5.twittnuker.extension.model.newMicroBlogInstance import de.vanita5.twittnuker.model.ListResponse import de.vanita5.twittnuker.model.ParcelableHashtag import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.util.AccountUtils class MastodonSearchLoader( context: Context, private val accountKey: UserKey?, private val query: String ) : FixedAsyncTaskLoader<List<Any>>(context), Constants { override fun loadInBackground(): List<Any> { try { val am = AccountManager.get(context) val account = accountKey?.let { AccountUtils.getAccountDetails(am, it, true) } ?: throw AccountNotFoundException() val mastodon = account.newMicroBlogInstance(context, Mastodon::class.java) val searchResult = mastodon.search(query, true, null) return ListResponse(ArrayList<Any>().apply { searchResult.accounts?.mapTo(this) { it.toParcelable(account) } searchResult.hashtags?.mapTo(this) { hashtag -> ParcelableHashtag().also { it.hashtag = hashtag } } searchResult.statuses?.mapTo(this) { it.toParcelable(account) } }) } catch (e: MicroBlogException) { return ListResponse(e) } } override fun onStartLoading() { forceLoad() } }
gpl-3.0
05af4ce036df0e96e7e4cc51c2ef21b1
37.60274
86
0.692581
4.56564
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/sensors/services/SensorServiceSubscription.kt
2
1487
// Copyright 2015-present 650 Industries. All rights reserved. package abi43_0_0.expo.modules.sensors.services import android.hardware.SensorEventListener2 import abi43_0_0.expo.modules.interfaces.sensors.SensorServiceSubscriptionInterface class SensorServiceSubscription internal constructor(private val mSubscribableSensorService: SubscribableSensorService, val sensorEventListener: SensorEventListener2) : SensorServiceSubscriptionInterface { private var mIsEnabled = false private var mUpdateInterval: Long = 100L private var mHasBeenReleased = false override fun start() { assertSubscriptionIsAlive() if (!mIsEnabled) { mIsEnabled = true mSubscribableSensorService.onSubscriptionEnabledChanged(this) } } override fun isEnabled(): Boolean { return mIsEnabled } override fun getUpdateInterval(): Long { return mUpdateInterval } override fun setUpdateInterval(updateInterval: Long) { assertSubscriptionIsAlive() mUpdateInterval = updateInterval } override fun stop() { if (mIsEnabled) { mIsEnabled = false mSubscribableSensorService.onSubscriptionEnabledChanged(this) } } override fun release() { if (!mHasBeenReleased) { mSubscribableSensorService.removeSubscription(this) mHasBeenReleased = true } } private fun assertSubscriptionIsAlive() { check(!mHasBeenReleased) { "Subscription has been released, cannot call methods on a released subscription." } } }
bsd-3-clause
8a0f34350bb9669ff976457c10f0f2a5
29.346939
205
0.759247
4.735669
false
false
false
false
ioc1778/incubator
incubator-events/src/main/java/com/riaektiv/lob/OrderComparator.kt
2
742
package com.riaektiv.lob import java.util.* /** * Coding With Passion Since 1991 * Created: 11/19/2017, 9:31 PM Eastern Time * @author Sergey Chuykov */ class OrderComparator : Comparator<Order> { override fun compare(o1: Order?, o2: Order?): Int { val BEFORE = -1 val EQUAL = 0 val AFTER = 1 if (o1 == o2) return EQUAL if (o1 == null || o2 == null) throw IllegalArgumentException() if (o1.price < o2.price) { return BEFORE } if (o1.price > o2.price) { return AFTER } if (o1.mts < o2.mts) { return BEFORE } if (o1.mts > o2.mts) { return AFTER } return EQUAL } }
bsd-3-clause
b3588cd7b3d7edde5ee58d44fca73054
18.552632
70
0.514825
3.619512
false
false
false
false
b005t3r/Kotling
core/src/main/kotlin/com/kotling/util/Color-ext.kt
1
447
package com.kotling.util import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.utils.NumberUtils fun Color.set(abgr:Float):Color { var abgri = NumberUtils.floatToIntBits(abgr) val ai = abgri and 0xfe000000.toInt() ushr 24 a = (if(ai != 0) ai or 0x01 else ai) / 255.0f b = (abgri and 0x00ff0000 ushr 16) / 255.0f g = (abgri and 0x0000ff00 ushr 8) / 255.0f r = (abgri and 0x000000ff) / 255.0f return this }
mit
86ea0d2cd0b2b25ad350bb8e358f6a5b
25.294118
49
0.680089
2.829114
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/utils/MemberSerialization.kt
2
4480
package com.habitrpg.android.habitica.utils import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonParseException import com.habitrpg.android.habitica.models.inventory.Quest import com.habitrpg.android.habitica.models.members.Member import com.habitrpg.android.habitica.models.members.MemberPreferences import com.habitrpg.android.habitica.models.social.UserParty import com.habitrpg.android.habitica.models.user.Authentication import com.habitrpg.android.habitica.models.user.Backer import com.habitrpg.android.habitica.models.user.ContributorInfo import com.habitrpg.android.habitica.models.user.Inbox import com.habitrpg.android.habitica.models.user.Items import com.habitrpg.android.habitica.models.user.Outfit import com.habitrpg.android.habitica.models.user.Profile import com.habitrpg.android.habitica.models.user.Stats import io.realm.Realm import java.lang.reflect.Type class MemberSerialization : JsonDeserializer<Member> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Member { val obj = json.asJsonObject val id = obj.get("_id").asString val realm = Realm.getDefaultInstance() var member = realm.where(Member::class.java).equalTo("id", id).findFirst() ?: Member() if (member.id == null) { member.id = id } else { member = realm.copyFromRealm(member) } if (obj.has("stats")) { member.stats = context.deserialize<Stats>(obj.get("stats"), Stats::class.java) } if (obj.has("inbox")) { member.inbox = context.deserialize<Inbox>(obj.get("inbox"), Inbox::class.java) } if (obj.has("preferences")) { member.preferences = context.deserialize<MemberPreferences>(obj.get("preferences"), MemberPreferences::class.java) } if (obj.has("profile")) { member.profile = context.deserialize<Profile>(obj.get("profile"), Profile::class.java) } if (obj.has("party")) { member.party = context.deserialize<UserParty>(obj.get("party"), UserParty::class.java) if (member.party != null && member.party?.quest != null) { member.party?.quest?.id = member.id if (!obj.get("party").asJsonObject.get("quest").asJsonObject.has("RSVPNeeded")) { val quest = realm.where(Quest::class.java).equalTo("id", member.id).findFirst() if (quest != null && quest.isValid) { member.party?.quest?.RSVPNeeded = quest.RSVPNeeded } } } } if (obj.has("items")) { member.items = context.deserialize(obj.get("items"), Items::class.java) member.items?.gear = null member.items?.special = null val items = obj.getAsJsonObject("items") if (items.has("currentMount") && items.get("currentMount").isJsonPrimitive) { member.currentMount = items.get("currentMount").asString } if (items.has("currentPet") && items.get("currentPet").isJsonPrimitive) { member.currentPet = items.get("currentPet").asString } if (items.has("gear")) { val gear = items.getAsJsonObject("gear") if (gear.has("costume")) { member.costume = context.deserialize(gear.get("costume"), Outfit::class.java) } if (gear.has("equipped")) { member.equipped = context.deserialize(gear.get("equipped"), Outfit::class.java) } } } if (obj.has("contributor")) { member.contributor = context.deserialize<ContributorInfo>(obj.get("contributor"), ContributorInfo::class.java) } if (obj.has("backer")) { member.backer = context.deserialize<Backer>(obj.get("backer"), Backer::class.java) } if (obj.has("auth")) { member.authentication = context.deserialize<Authentication>(obj.get("auth"), Authentication::class.java) } if (obj.has("loginIncentives")) { member.loginIncentives = obj.get("loginIncentives").asInt } member.id = member.id realm.close() return member } }
gpl-3.0
faca6944103255a54277244204781442
43.356436
126
0.622991
4.357977
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/desktopMain/kotlin/androidx/compose/foundation/window/WindowDraggableArea.desktop.kt
3
2925
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.window import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.window.WindowScope import java.awt.MouseInfo import java.awt.Point import java.awt.Window import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.awt.event.MouseMotionAdapter /** * WindowDraggableArea is a component that allows you to drag the window using the mouse. * * @param modifier The modifier to be applied to the layout. */ @Composable fun WindowScope.WindowDraggableArea( modifier: Modifier = Modifier, content: @Composable () -> Unit = {} ) { val handler = remember { DragHandler(window) } Box( modifier = modifier.pointerInput(Unit) { awaitEachGesture { awaitFirstDown() handler.register() } } ) { content() } } private class DragHandler(private val window: Window) { private var location = window.location.toComposeOffset() private var pointStart = MouseInfo.getPointerInfo().location.toComposeOffset() private val dragListener = object : MouseMotionAdapter() { override fun mouseDragged(event: MouseEvent) = drag() } private val removeListener = object : MouseAdapter() { override fun mouseReleased(event: MouseEvent) { window.removeMouseMotionListener(dragListener) window.removeMouseListener(this) } } fun register() { location = window.location.toComposeOffset() pointStart = MouseInfo.getPointerInfo().location.toComposeOffset() window.addMouseListener(removeListener) window.addMouseMotionListener(dragListener) } private fun drag() { val point = MouseInfo.getPointerInfo().location.toComposeOffset() val location = location + (point - pointStart) window.setLocation(location.x, location.y) } private fun Point.toComposeOffset() = IntOffset(x, y) }
apache-2.0
622d050b62c46b12d05638b6eef684ca
32.62069
89
0.720684
4.472477
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/stories/landing/StoriesLandingItem.kt
1
12605
package org.thoughtcrime.securesms.stories.landing import android.graphics.Color import android.graphics.drawable.Drawable import android.text.SpannableStringBuilder import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.avatar.view.AvatarView import org.thoughtcrime.securesms.badges.BadgeImageView import org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader import org.thoughtcrime.securesms.mms.GlideApp import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.stories.StoryTextPostModel import org.thoughtcrime.securesms.stories.dialogs.StoryContextMenu import org.thoughtcrime.securesms.util.ContextUtil import org.thoughtcrime.securesms.util.DateUtils import org.thoughtcrime.securesms.util.SpanUtil import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder import org.thoughtcrime.securesms.util.visible import java.util.Locale /** * Items displaying a preview and metadata for a story from a user, allowing them to launch into the story viewer. */ object StoriesLandingItem { private const val STATUS_CHANGE = 0 fun register(mappingAdapter: MappingAdapter) { mappingAdapter.registerFactory(Model::class.java, LayoutFactory(::ViewHolder, R.layout.stories_landing_item)) } class Model( val data: StoriesLandingItemData, val onAvatarClick: () -> Unit, val onRowClick: (Model, View) -> Unit, val onHideStory: (Model) -> Unit, val onForwardStory: (Model) -> Unit, val onShareStory: (Model) -> Unit, val onGoToChat: (Model) -> Unit, val onSave: (Model) -> Unit, val onDeleteStory: (Model) -> Unit, val onInfo: (Model, View) -> Unit ) : MappingModel<Model> { override fun areItemsTheSame(newItem: Model): Boolean { return data.storyRecipient.id == newItem.data.storyRecipient.id } override fun areContentsTheSame(newItem: Model): Boolean { return data.storyRecipient.hasSameContent(newItem.data.storyRecipient) && data == newItem.data && !hasStatusChange(newItem) && !hasThumbChange(newItem) && (data.sendingCount == newItem.data.sendingCount && data.failureCount == newItem.data.failureCount) && data.storyViewState == newItem.data.storyViewState } override fun getChangePayload(newItem: Model): Any? { return if (isSameRecord(newItem) && hasStatusChange(newItem)) { STATUS_CHANGE } else { null } } private fun isSameRecord(newItem: Model): Boolean { return data.primaryStory.messageRecord.id == newItem.data.primaryStory.messageRecord.id } private fun hasStatusChange(newItem: Model): Boolean { val oldRecord = data.primaryStory.messageRecord val newRecord = newItem.data.primaryStory.messageRecord return oldRecord.isOutgoing && newRecord.isOutgoing && (oldRecord.isPending != newRecord.isPending || oldRecord.isSent != newRecord.isSent || oldRecord.isFailed != newRecord.isFailed) } private fun hasThumbChange(newItem: Model): Boolean { val oldRecord = data.primaryStory.messageRecord as? MediaMmsMessageRecord ?: return false val newRecord = newItem.data.primaryStory.messageRecord as? MediaMmsMessageRecord ?: return false val oldThumb = oldRecord.slideDeck.thumbnailSlide?.uri val newThumb = newRecord.slideDeck.thumbnailSlide?.uri if (oldThumb != newThumb) { return true } val oldBlur = oldRecord.slideDeck.thumbnailSlide?.placeholderBlur val newBlur = newRecord.slideDeck.thumbnailSlide?.placeholderBlur return oldBlur != newBlur } } private class ViewHolder(itemView: View) : MappingViewHolder<Model>(itemView) { companion object { private val TAG = Log.tag(ViewHolder::class.java) } private val avatarView: AvatarView = itemView.findViewById(R.id.avatar) private val badgeView: BadgeImageView = itemView.findViewById(R.id.badge) private val storyPreview: ImageView = itemView.findViewById<ImageView>(R.id.story).apply { isClickable = false ViewCompat.setTransitionName(this, "story") } private val storyBlur: ImageView = itemView.findViewById<ImageView>(R.id.story_blur).apply { isClickable = false } private val storyOutline: ImageView = itemView.findViewById(R.id.story_outline) private val storyMulti: ImageView = itemView.findViewById<ImageView>(R.id.story_multi).apply { isClickable = false } private val sender: TextView = itemView.findViewById(R.id.sender) private val date: TextView = itemView.findViewById(R.id.date) private val icon: ImageView = itemView.findViewById(R.id.icon) private val errorIndicator: View = itemView.findViewById(R.id.error_indicator) private val addToStoriesView: View = itemView.findViewById(R.id.add_to_story) override fun bind(model: Model) { presentDateOrStatus(model) setUpClickListeners(model) if (payload.contains(STATUS_CHANGE)) { return } if (model.data.storyRecipient.isMyStory) { avatarView.displayProfileAvatar(Recipient.self()) badgeView.setBadgeFromRecipient(null) } else { avatarView.displayProfileAvatar(model.data.storyRecipient) badgeView.setBadgeFromRecipient(model.data.storyRecipient) } val record = model.data.primaryStory.messageRecord as MediaMmsMessageRecord avatarView.setStoryRingFromState(model.data.storyViewState) val thumbnail = record.slideDeck.thumbnailSlide?.uri val blur = record.slideDeck.thumbnailSlide?.placeholderBlur if (thumbnail == null && blur == null && !record.storyType.isTextStory) { Log.w(TAG, "Story[${record.dateSent}] has no thumbnail and no blur!") } clearGlide() storyBlur.visible = blur != null if (blur != null) { GlideApp.with(storyBlur).load(blur).into(storyBlur) } @Suppress("CascadeIf") if (record.storyType.isTextStory) { storyBlur.visible = false val storyTextPostModel = StoryTextPostModel.parseFrom(record) GlideApp.with(storyPreview) .load(storyTextPostModel) .placeholder(storyTextPostModel.getPlaceholder()) .centerCrop() .dontAnimate() .into(storyPreview) } else if (thumbnail != null) { storyBlur.visible = blur != null GlideApp.with(storyPreview) .load(DecryptableStreamUriLoader.DecryptableUri(thumbnail)) .addListener(HideBlurAfterLoadListener()) .centerCrop() .dontAnimate() .into(storyPreview) } if (model.data.secondaryStory != null) { val secondaryRecord = model.data.secondaryStory.messageRecord as MediaMmsMessageRecord val secondaryThumb = secondaryRecord.slideDeck.thumbnailSlide?.uri storyOutline.setBackgroundColor(ContextCompat.getColor(context, R.color.signal_background_primary)) @Suppress("CascadeIf") if (secondaryRecord.storyType.isTextStory) { val storyTextPostModel = StoryTextPostModel.parseFrom(secondaryRecord) GlideApp.with(storyMulti) .load(storyTextPostModel) .placeholder(storyTextPostModel.getPlaceholder()) .centerCrop() .dontAnimate() .into(storyMulti) storyMulti.visible = true } else if (secondaryThumb != null) { GlideApp.with(storyMulti) .load(DecryptableStreamUriLoader.DecryptableUri(secondaryThumb)) .centerCrop() .dontAnimate() .into(storyMulti) storyMulti.visible = true } else { storyOutline.setBackgroundColor(Color.TRANSPARENT) GlideApp.with(storyMulti).clear(storyMulti) storyMulti.visible = false } } else { storyOutline.setBackgroundColor(Color.TRANSPARENT) GlideApp.with(storyMulti).clear(storyMulti) storyMulti.visible = false } sender.text = when { model.data.storyRecipient.isMyStory -> context.getText(R.string.StoriesLandingFragment__my_stories) model.data.storyRecipient.isGroup -> getGroupPresentation(model) model.data.storyRecipient.isReleaseNotes -> getReleaseNotesPresentation(model) else -> model.data.storyRecipient.getDisplayName(context) } icon.visible = (model.data.hasReplies || model.data.hasRepliesFromSelf) && !model.data.storyRecipient.isMyStory icon.setImageResource( when { model.data.hasReplies -> R.drawable.ic_messages_solid_20 else -> R.drawable.ic_reply_24_solid_tinted } ) listOf(avatarView, storyPreview, storyMulti, sender, date, icon).forEach { it.alpha = if (model.data.isHidden) 0.5f else 1f } } private fun presentDateOrStatus(model: Model) { if (model.data.sendingCount > 0 || (model.data.primaryStory.messageRecord.isOutgoing && (model.data.primaryStory.messageRecord.isPending || model.data.primaryStory.messageRecord.isMediaPending))) { errorIndicator.visible = model.data.failureCount > 0L if (model.data.sendingCount > 1) { date.text = context.getString(R.string.StoriesLandingItem__sending_d, model.data.sendingCount) } else { date.setText(R.string.StoriesLandingItem__sending) } } else if (model.data.failureCount > 0 || (model.data.primaryStory.messageRecord.isOutgoing && model.data.primaryStory.messageRecord.isFailed)) { errorIndicator.visible = true val message = if (model.data.primaryStory.messageRecord.isIdentityMismatchFailure) R.string.StoriesLandingItem__partially_sent else R.string.StoriesLandingItem__send_failed date.text = SpanUtil.color(ContextCompat.getColor(context, R.color.signal_alert_primary), context.getString(message)) } else { errorIndicator.visible = false date.text = DateUtils.getBriefRelativeTimeSpanString(context, Locale.getDefault(), model.data.dateInMilliseconds) } } private fun setUpClickListeners(model: Model) { itemView.setOnClickListener { model.onRowClick(model, storyPreview) } if (model.data.storyRecipient.isMyStory) { itemView.setOnLongClickListener(null) avatarView.setOnClickListener { model.onAvatarClick() } addToStoriesView.visible = true } else { itemView.setOnLongClickListener { displayContext(model) true } avatarView.setOnClickListener(null) avatarView.isClickable = false addToStoriesView.visible = false } } private fun getGroupPresentation(model: Model): String { return model.data.storyRecipient.getDisplayName(context) } private fun getReleaseNotesPresentation(model: Model): CharSequence { val official = ContextUtil.requireDrawable(context, R.drawable.ic_official_20) val name = SpannableStringBuilder(model.data.storyRecipient.getDisplayName(context)) SpanUtil.appendCenteredImageSpan(name, official, 20, 20) return name } private fun displayContext(model: Model) { itemView.isSelected = true StoryContextMenu.show(context, itemView, storyPreview, model) { itemView.isSelected = false } } private fun clearGlide() { GlideApp.with(storyPreview).clear(storyPreview) GlideApp.with(storyBlur).clear(storyBlur) } private inner class HideBlurAfterLoadListener : RequestListener<Drawable> { override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean = false override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean { storyBlur.visible = false return false } } } }
gpl-3.0
4c413c58753c21c2441f58ce8e26f7a8
39.143312
203
0.709798
4.455638
false
false
false
false
willjgriff/android-ethereum-wallet
app/src/main/kotlin/com/github/willjgriff/ethereumwallet/ui/screens/settings/DeleteAddressAlertDialog.kt
1
3174
package com.github.willjgriff.ethereumwallet.ui.screens.settings import android.content.Context import android.content.DialogInterface import android.os.Bundle import com.github.willjgriff.ethereumwallet.R import com.github.willjgriff.ethereumwallet.mvp.BaseMvpAlertDialog import com.github.willjgriff.ethereumwallet.ui.screens.settings.di.injectPresenter import com.github.willjgriff.ethereumwallet.ui.screens.settings.mvp.DeleteAddressPresenter import com.github.willjgriff.ethereumwallet.ui.screens.settings.mvp.DeleteAddressView import com.github.willjgriff.ethereumwallet.ui.utils.inflate import com.github.willjgriff.ethereumwallet.ui.widget.validatedtextinput.ValidatedTextInputLayout import com.jakewharton.rxbinding2.view.RxView import javax.inject.Inject /** * Created by williamgriffiths on 04/05/2017. */ class DeleteAddressAlertDialog(context: Context, private val mDialogListener: SettingsDeleteAlertDialogListener) : BaseMvpAlertDialog<DeleteAddressView, DeleteAddressPresenter>(context), DeleteAddressView { override val mvpView: DeleteAddressView get() = this @Inject override lateinit var presenter: DeleteAddressPresenter private var mValidatedTextInputLayout: ValidatedTextInputLayout = context.inflate(R.layout.view_controller_settings_delete_validated_input) as ValidatedTextInputLayout init { injectPresenter() setupAppearance() } private fun setupAppearance() { setButton(DialogInterface.BUTTON_POSITIVE, context.getString(R.string.controller_settings_delete_address)) { _, _ -> } setButton(DialogInterface.BUTTON_NEGATIVE, context.getString(R.string.controller_settings_delete_address_cancel)) { _, _ -> } setTitle(R.string.controller_settings_delete_address_dialog_title) setMessage(context.getString(R.string.controller_settings_delete_address_dialog_message)) setView(mValidatedTextInputLayout) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setupObservablesOnPresenter() } private fun setupObservablesOnPresenter() { val deleteClick = RxView.clicks(getButton(DialogInterface.BUTTON_POSITIVE)).share() val cancelClick = RxView.clicks(getButton(DialogInterface.BUTTON_NEGATIVE)).share() mValidatedTextInputLayout.setCheckValidationTrigger(deleteClick) val passwordValid = mValidatedTextInputLayout.textValidObservable val passwordChanged = mValidatedTextInputLayout.textChangedObservable presenter.apply { this.deleteClick = deleteClick this.cancelClick = cancelClick this.passwordValid = passwordValid this.passwordChanged = passwordChanged } } override fun closeDialog() { dismiss() } override fun incorrectPasswordEntered() { mDialogListener.showIncorrectPasswordDialog() } override fun addressDeleted() { mDialogListener.addressSuccessfullyDeleted() } interface SettingsDeleteAlertDialogListener { fun showIncorrectPasswordDialog() fun addressSuccessfullyDeleted() } }
apache-2.0
d76e3c77711b0e2def28280eab3565a6
39.189873
133
0.7615
4.943925
false
false
false
false
paulalewis/agl
src/main/kotlin/com/castlefrog/agl/domains/havannah/HavannahState.kt
1
2934
package com.castlefrog.agl.domains.havannah import com.castlefrog.agl.State import kotlin.math.max data class HavannahState( val base: Int, val locations: Array<ByteArray>, var agentTurn: Byte ) : State<HavannahState> { companion object { const val N_PLAYERS = 2 const val LOCATION_EMPTY: Byte = 0 const val LOCATION_BLACK: Byte = 1 const val LOCATION_WHITE: Byte = 2 const val TURN_BLACK: Byte = 0 const val TURN_WHITE: Byte = 1 } override fun copy(): HavannahState { val copyLocations = Array(locations.size) { ByteArray(locations.size) } for (i in locations.indices) { copyLocations[i] = locations[i].copyOf() } return HavannahState(base, copyLocations, agentTurn) } fun isLocationEmpty(x: Int, y: Int): Boolean { return locations[x][y] == LOCATION_EMPTY } val nPieces: Int get() { var nPieces = 0 (locations.indices).forEach { i -> (locations[0].indices) .asSequence() .filter { j -> locations[i][j] != LOCATION_EMPTY } .forEach { _ -> nPieces += 1 } } return nPieces } override fun hashCode(): Int { var hashCode = 17 + agentTurn hashCode = hashCode * 31 + base for (i in locations.indices) { for (j in locations[i].indices) { hashCode = hashCode * 31 + locations[i][j] } } return hashCode } override fun equals(other: Any?): Boolean { if (other !is HavannahState) { return false } for (i in locations.indices) { for (j in locations[i].indices) { if (locations[i][j] != other.locations[i][j]) { return false } } } return base == other.base && agentTurn == other.agentTurn } override fun toString(): String { val output = StringBuilder() for (i in locations.size - 1 downTo 0) { for (j in 0..max(base - i - 2, i - base)) { output.append(" ") } var xMin = 0 var xMax = locations.size if (i >= base) { xMin = i - base + 1 } else { xMax = base + i } for (j in xMin until xMax) { when { locations[j][i] == LOCATION_BLACK -> output.append("X") locations[j][i] == LOCATION_WHITE -> output.append("O") else -> output.append("-") } if (j != xMax - 1) { output.append(" ") } } if (i != 0) { output.append("\n") } } return output.toString() } }
mit
114662aa2de0285d1ed67be2d5111272
28.049505
79
0.474438
4.295754
false
false
false
false
Soya93/Extract-Refactoring
platform/platform-impl/src/com/intellij/internal/statistic/StatisticsUtil.kt
8
3232
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.internal.statistic import com.intellij.internal.statistic.beans.UsageDescriptor /** * Constructs a proper UsageDescriptor for a boolean value, * by adding "enabled" or "disabled" suffix to the given key, depending on the value. */ fun getBooleanUsage(key: String, value: Boolean): UsageDescriptor { return UsageDescriptor(key + if (value) ".enabled" else ".disabled", 1) } /** * Constructs a proper UsageDescriptor for a counting value. * If one needs to know a number of some items in the project, there is no direct way to report usages per-project. * Therefore this workaround: create several keys representing interesting ranges, and report that key which correspond to the range * which the given value belongs to. * * For example, to report a number of commits in Git repository, you can call this method like that: * ``` * val usageDescriptor = getCountingUsage("git.commit.count", listOf(0, 1, 100, 10000, 100000), realCommitCount) * ``` * and if there are e.g. 50000 commits in the repository, one usage of the following key will be reported: `git.commit.count.10K+`. * * NB: * (1) the list of steps must be sorted ascendingly; If it is not, the result is undefined. * (2) the value should lay somewhere inside steps ranges. If it is below the first step, the following usage will be reported: * `git.commit.count.<1`. * * @key The key prefix which will be appended with "." and range code. * @steps Limits of the ranges. Each value represents the start of the next range. The list must be sorted ascendingly. * @value Value to be checked among the given ranges. */ fun getCountingUsage(key: String, value: Int, steps: List<Int>) : UsageDescriptor { if (steps.isEmpty()) return UsageDescriptor("$key.$value", 1) if (value < steps[0]) return UsageDescriptor("$key.<${steps[0]}", 1) val index = steps.binarySearch(value) val stepIndex : Int if (index == steps.size) { stepIndex = steps.last() } else if (index >= 0) { stepIndex = index } else { stepIndex = -index - 2 } val step = steps[stepIndex] val addPlus = stepIndex == steps.size - 1 || steps[stepIndex + 1] != step + 1 val maybePlus = if (addPlus) "+" else "" return UsageDescriptor("$key.${humanize(step)}$maybePlus", 1) } private val kilo = 1000 private val mega = kilo * kilo private fun humanize(number: Int): String { if (number == 0) return "0" val m = number / mega val k = (number % mega) / kilo val r = (number % kilo) val ms = if (m > 0) "${m}M" else "" val ks = if (k > 0) "${k}K" else "" val rs = if (r > 0) "${r}" else "" return ms + ks + rs }
apache-2.0
df4dd9f4d5c62ab03c174702c4ed07d5
38.414634
132
0.69802
3.762515
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/profile/comment/ProfileCommentViewModel.kt
1
2870
package me.proxer.app.profile.comment import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import me.proxer.app.base.PagedViewModel import me.proxer.app.comment.LocalComment import me.proxer.app.util.ErrorUtils import me.proxer.app.util.data.ResettingMutableLiveData import me.proxer.app.util.extension.buildOptionalSingle import me.proxer.app.util.extension.buildSingle import me.proxer.app.util.extension.subscribeAndLogErrors import me.proxer.app.util.extension.toParsedUserComment import me.proxer.library.enums.Category import me.proxer.library.enums.CommentContentType import org.threeten.bp.Instant import kotlin.properties.Delegates /** * @author Ruben Gees */ class ProfileCommentViewModel( private val userId: String?, private val username: String?, category: Category? ) : PagedViewModel<ParsedUserComment>() { override val itemsOnPage = 10 override val dataSingle: Single<List<ParsedUserComment>> get() = Single.fromCallable { validate() } .flatMap { api.user.comments(userId, username) .category(category) .page(page) .limit(itemsOnPage) .hasContent(CommentContentType.COMMENT, CommentContentType.RATING) .buildSingle() } .observeOn(Schedulers.computation()) .map { it.map { comment -> comment.toParsedUserComment() } } var category by Delegates.observable(category) { _, old, new -> if (old != new) reload() } val itemDeletionError = ResettingMutableLiveData<ErrorUtils.ErrorAction?>() private var deleteDisposable: Disposable? = null fun deleteComment(comment: ParsedUserComment) { deleteDisposable?.dispose() deleteDisposable = api.comment.update(comment.id) .comment("") .rating(0) .buildOptionalSingle() .doOnSuccess { storageHelper.deleteCommentDraft(comment.entryId) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeAndLogErrors({ data.value = data.value?.filter { it.id != comment.id } }, { itemDeletionError.value = ErrorUtils.handle(it) }) } fun updateComment(comment: LocalComment) { data.value = data.value?.map { if (it.id == comment.id) { it.copy( ratingDetails = comment.ratingDetails, parsedContent = comment.parsedContent, overallRating = comment.overallRating, instant = Instant.now() ) } else { it } } } }
gpl-3.0
2c2f74540824a5aff2d0674b35549489
33.578313
86
0.635889
4.759536
false
false
false
false
IRA-Team/VKPlayer
app/src/main/java/com/irateam/vkplayer/service/DownloadService.kt
1
8251
/* * Copyright (C) 2015 IRA-Team * * 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.irateam.vkplayer.service import android.app.Service import android.content.Context import android.content.Intent import android.os.IBinder import android.support.v4.app.NotificationManagerCompat import android.widget.Toast import com.irateam.vkplayer.R import com.irateam.vkplayer.api.service.SettingsService import com.irateam.vkplayer.api.service.VKAudioService import com.irateam.vkplayer.database.AudioVKCacheDatabase import com.irateam.vkplayer.event.DownloadErrorEvent import com.irateam.vkplayer.event.DownloadFinishedEvent import com.irateam.vkplayer.event.DownloadProgressChangedEvent import com.irateam.vkplayer.event.DownloadTerminatedEvent import com.irateam.vkplayer.model.Audio import com.irateam.vkplayer.model.VKAudio import com.irateam.vkplayer.notification.DownloadNotificationFactory import com.irateam.vkplayer.player.Player import com.irateam.vkplayer.util.AudioDownloader import com.irateam.vkplayer.util.EventBus import com.irateam.vkplayer.util.extension.execute import com.irateam.vkplayer.util.extension.isNetworkAvailable import com.irateam.vkplayer.util.extension.isWifiNetworkAvailable import java.util.* import java.util.concurrent.ConcurrentLinkedQueue class DownloadService : Service(), AudioDownloader.Listener { private val downloadQueue = ConcurrentLinkedQueue<VKAudio>() private val syncQueue = ConcurrentLinkedQueue<VKAudio>() private var currentSession: Session? = null private lateinit var downloader: AudioDownloader private lateinit var audioService: VKAudioService private lateinit var database: AudioVKCacheDatabase private lateinit var settingsService: SettingsService private lateinit var notificationManager: NotificationManagerCompat private lateinit var notificationFactory: DownloadNotificationFactory override fun onCreate() { super.onCreate() downloader = AudioDownloader(this) downloader.listener = this audioService = VKAudioService(this) database = AudioVKCacheDatabase(this) settingsService = SettingsService(this) notificationFactory = DownloadNotificationFactory(this) notificationManager = NotificationManagerCompat.from(this) } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { intent.action?.let { when (intent.action) { START_DOWNLOADING -> { val audios = intent.getParcelableArrayListExtra<VKAudio>(AUDIO_LIST) downloadQueue.addAll(audios) startDownloadIfNeeded() } START_SYNC -> if (intent.extras.getBoolean(USER_SYNC, false)) { startManualSync() } else { startScheduledSync() } STOP_DOWNLOADING -> { stopDownloading() } } } return START_NOT_STICKY } private fun startManualSync() = if (isNetworkAvailable()) { prepareToSync() } else { Toast.makeText(this, R.string.error_no_internet_connection, Toast.LENGTH_LONG).show() } private fun startScheduledSync() { val isWifiOnly = settingsService.loadWifiSync() if ((isWifiOnly && isWifiNetworkAvailable()) || (!isWifiOnly && isNetworkAvailable())) { prepareToSync() } else { notifyNoWifiConnection() } } private fun prepareToSync() { val count = settingsService.loadSyncCount() audioService.getMy(count).execute { onSuccess { val vkList = it val cachedIds = database.getAll().map { it.id } val nonCached = vkList.filter { it.id in cachedIds }.asReversed() syncQueue.clear() syncQueue.addAll(nonCached) if (!downloader.isDownloading()) { pollAndDownload() } } onError { notifyError() } } } private fun clearCurrentSession() { currentSession = null } private fun getPreferredQueue() = if (downloadQueue.isEmpty()) { syncQueue } else { downloadQueue } private fun hasAudios(): Boolean { val queue = getPreferredQueue() return !queue.isEmpty() } private fun startDownloadIfNeeded() { if (!downloader.isDownloading()) { pollAndDownload() } } fun stopDownloading() { downloader.stop() } fun pollAndDownload() { val queue = getPreferredQueue() val audio = queue.poll() if (audio != null) { val session = Session(audio = audio, progress = 0, audioCount = currentSession?.audioCount ?: 0, queue = queue, isSync = syncQueue === queue) currentSession = session downloader.download(audio) val notification = notificationFactory.getDownload(session) startForeground(NOTIFICATION_ID_DOWNLOADING, notification) } else { clearCurrentSession() } } override fun onDownloadProgressChanged(audio: VKAudio, progress: Int) { EventBus.post(DownloadProgressChangedEvent(audio, progress)) currentSession?.let { currentSession = it.copy(progress = progress) notifyDownloading() } } override fun onDownloadFinished(audio: VKAudio) { database.cache(audio) EventBus.post(DownloadFinishedEvent(audio)) currentSession?.let { val newSession = it.copy(audioCount = it.audioCount + 1) currentSession = newSession } if (hasAudios()) { pollAndDownload() } else { notifyFinished() stopForeground(true) } } override fun onDownloadError(audio: VKAudio, cause: Throwable) { EventBus.post(DownloadErrorEvent(audio, cause)) stopForeground(true) clearCurrentSession() } override fun onDownloadTerminated(audio: VKAudio) { EventBus.post(DownloadTerminatedEvent(audio)) stopForeground(true) clearCurrentSession() } fun notifyDownloading() = currentSession?.let { val notification = notificationFactory.getDownload(it) notificationManager.notify(NOTIFICATION_ID_DOWNLOADING, notification) } fun notifyFinished() = currentSession?.let { val notification = notificationFactory.getSuccessful(it) notificationManager.notify(NOTIFICATION_ID_FINISHED, notification) } fun notifyError() = currentSession?.let { val notification = notificationFactory.getError(it) notificationManager.notify(NOTIFICATION_ID_FINISHED, notification) } fun notifyNoWifiConnection() = currentSession?.let { val notification = notificationFactory.getErrorNoWifiConnection(it) notificationManager.notify(NOTIFICATION_ID_FINISHED, notification) } override fun onBind(intent: Intent): IBinder { throw UnsupportedOperationException() } data class Session(val audio: VKAudio, val progress: Int, val audioCount: Int, private val queue: Queue<VKAudio>, val isSync: Boolean) { val audioCountLeft: Int get() = queue.size } companion object { val NOTIFICATION_ID_DOWNLOADING = 2 val NOTIFICATION_ID_FINISHED = 3 val AUDIO_LIST = "audio_list" val START_SYNC = "start_sync" val STOP_DOWNLOADING = "stop_downloading" val START_DOWNLOADING = "start_downloading" val USER_SYNC = "user_sync" @JvmStatic fun download(context: Context, audios: Collection<Audio>) { val intent = startDownloadIntent(context, audios) context.startService(intent) } @JvmStatic fun stop(context: Context) { val intent = stopDownloadIntent(context) context.stopService(intent) } @JvmStatic fun startDownloadIntent(context: Context, audios: Collection<Audio>): Intent { return Intent(context, DownloadService::class.java) .setAction(START_DOWNLOADING) .putParcelableArrayListExtra(AUDIO_LIST, ArrayList(audios)) } @JvmStatic fun stopDownloadIntent(context: Context): Intent { return Intent(context, DownloadService::class.java) .setAction(STOP_DOWNLOADING) } @JvmStatic fun startSyncIntent(context: Context, userSync: Boolean = false): Intent { return Intent(context, DownloadService::class.java) .setAction(DownloadService.START_SYNC) .putExtra(DownloadService.USER_SYNC, userSync) } } }
apache-2.0
788d53e9fd9597a327547b5a310dc5b9
27.353952
90
0.749121
3.917854
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/classificator/time/ClassificationTimeFragment.kt
2
4408
package ru.fantlab.android.ui.modules.classificator.time import android.content.Context import android.os.Bundle import android.view.View import androidx.annotation.StringRes import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.micro_grid_refresh_list.* import kotlinx.android.synthetic.main.state_layout.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.Classificator import ru.fantlab.android.data.dao.model.ClassificatorModel import ru.fantlab.android.helper.BundleConstant import ru.fantlab.android.helper.Bundler import ru.fantlab.android.ui.adapter.viewholder.ClassificatorViewHolder import ru.fantlab.android.ui.base.BaseFragment import ru.fantlab.android.ui.modules.classificator.ClassificatorPagerMvp import ru.fantlab.android.ui.widgets.treeview.TreeNode import ru.fantlab.android.ui.widgets.treeview.TreeViewAdapter import java.util.* class ClassificationTimeFragment : BaseFragment<ClassificationTimeMvp.View, ClassificationTimePresenter>(), ClassificationTimeMvp.View { private var pagerCallback: ClassificatorPagerMvp.View? = null var selectedItems = 0 override fun fragmentLayout() = R.layout.micro_grid_refresh_list override fun providePresenter() = ClassificationTimePresenter() override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { presenter.onFragmentCreated(arguments!!) } override fun onInitViews(classificators: ArrayList<ClassificatorModel>) { hideProgress() fastScroller.attachRecyclerView(recycler) refresh.setOnRefreshListener(this) val nodes = arrayListOf<TreeNode<*>>() classificators.forEach { val root = TreeNode(Classificator(it.name, it.descr, it.id)) nodes.add(root) work(it, root, false) } val adapter = TreeViewAdapter(nodes, Arrays.asList(ClassificatorViewHolder())) recycler.adapter = adapter adapter.setOnTreeNodeListener(object : TreeViewAdapter.OnTreeNodeListener { override fun onSelected(extra: Int, add: Boolean) { if (add) selectedItems++ else selectedItems-- onSetTabCount(selectedItems) pagerCallback?.onSelected(extra, add) } override fun onClick(node: TreeNode<*>, holder: RecyclerView.ViewHolder): Boolean { val viewHolder = holder as ClassificatorViewHolder.ViewHolder val state = viewHolder.checkbox.isChecked if (!node.isLeaf) { onToggle(!node.isExpand, holder) if (!state && !node.isExpand) { viewHolder.checkbox.isChecked = true } } else { viewHolder.checkbox.isChecked = !state } return false } override fun onToggle(isExpand: Boolean, holder: RecyclerView.ViewHolder) { val viewHolder = holder as ClassificatorViewHolder.ViewHolder val ivArrow = viewHolder.arrow val rotateDegree = if (isExpand) 90.0f else -90.0f ivArrow.animate().rotationBy(rotateDegree) .start() } }) } private fun work(it: ClassificatorModel, root: TreeNode<Classificator>, lastLevel: Boolean) { if (it.childs != null) { val counter = root.childList.size - 1 it.childs.forEach { val child = TreeNode(Classificator(it.name, it.descr, it.id)) if (lastLevel) { val childB = TreeNode(Classificator(it.name, it.descr, it.id)) root.childList[counter].addChild(childB) } else root.addChild(child) work(it, root, true) } } } override fun showProgress(@StringRes resId: Int, cancelable: Boolean) { refresh.isRefreshing = true stateLayout.showProgress() } override fun hideProgress() { refresh.isRefreshing = false stateLayout.hideProgress() } override fun showErrorMessage(msgRes: String?) { hideProgress() super.showErrorMessage(msgRes) } override fun showMessage(titleRes: Int, msgRes: Int) { hideProgress() super.showMessage(titleRes, msgRes) } override fun onClick(v: View?) { onRefresh() } override fun onRefresh() { hideProgress() } fun onSetTabCount(count: Int) { pagerCallback?.onSetBadge(3, count) } override fun onAttach(context: Context) { super.onAttach(context) if (context is ClassificatorPagerMvp.View) { pagerCallback = context } } override fun onDetach() { pagerCallback = null super.onDetach() } companion object { fun newInstance(workId: Int): ClassificationTimeFragment { val view = ClassificationTimeFragment() view.arguments = Bundler.start().put(BundleConstant.EXTRA, workId).end() return view } } }
gpl-3.0
9011a4a4911aa328f3707fb17a6725e8
27.62987
107
0.748639
3.856518
false
false
false
false
Gnar-Team/Gnar-bot
src/main/kotlin/xyz/gnarbot/gnar/commands/music/PauseCommand.kt
1
824
package xyz.gnarbot.gnar.commands.music import xyz.gnarbot.gnar.commands.* import xyz.gnarbot.gnar.music.MusicManager @Command( aliases = ["pause"], description = "Pause or resume the music player." ) @BotInfo( id = 68, category = Category.MUSIC, scope = Scope.VOICE ) class PauseCommand : MusicCommandExecutor(true, true) { override fun execute(context: Context, label: String, args: Array<String>, manager: MusicManager) { manager.player.isPaused = !manager.player.isPaused context.send().embed { desc { if (manager.player.isPaused) { "The player has been paused." } else { "The player has resumed playing." } } }.action().queue() } }
mit
dd53af7811311a1e50a61a2993b947a4
27.413793
103
0.574029
4.406417
false
false
false
false
googleads/googleads-mobile-android-examples
kotlin/advanced/APIDemo/app/src/main/java/com/google/android/gms/example/apidemo/AdManagerFluidSizeFragment.kt
1
2046
package com.google.android.gms.example.apidemo import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.google.android.gms.ads.admanager.AdManagerAdRequest import com.google.android.gms.example.apidemo.databinding.FragmentGamFluidSizeBinding /** The [AdManagerFluidSizeFragment] demonstrates the use of the `AdSize.FLUID` ad size. */ class AdManagerFluidSizeFragment : Fragment() { private lateinit var fragmentBinding: FragmentGamFluidSizeBinding private val mAdViewWidths = intArrayOf(200, 250, 320) private var mCurrentIndex = 0 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { fragmentBinding = FragmentGamFluidSizeBinding.inflate(inflater) return fragmentBinding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // The size for this PublisherAdView is defined in the XML layout as AdSize.FLUID. It could // also be set here by calling mPublisherAdView.setAdSizes(AdSize.FLUID). // // An ad with fluid size will automatically stretch or shrink to fit the height of its // content, which can help layout designers cut down on excess whitespace. val publisherAdRequest = AdManagerAdRequest.Builder().build() fragmentBinding.fluidAvMain.loadAd(publisherAdRequest) fragmentBinding.fluidBtnChangeWidth.setOnClickListener { val newWidth = mAdViewWidths[mCurrentIndex % mAdViewWidths.size] mCurrentIndex += 1 // Change the PublisherAdView's width. val layoutParams = fragmentBinding.fluidAvMain.layoutParams val scale = resources.displayMetrics.density layoutParams.width = (newWidth * scale + 0.5f).toInt() fragmentBinding.fluidAvMain.layoutParams = layoutParams // Update the TextView with the new width. fragmentBinding.fluidTvCurrentWidth.text = "$newWidth dp" } } }
apache-2.0
383cc514d3f5bc3b1bd5141b2e814599
36.888889
95
0.76784
4.671233
false
false
false
false
Shockah/Godwit
core/src/pl/shockah/godwit/node/gesture/Touch.kt
1
873
package pl.shockah.godwit.node.gesture import pl.shockah.godwit.GDelegates import pl.shockah.godwit.geom.ImmutableVec2 import pl.shockah.godwit.geom.Vec2 import java.util.* class Touch( val pointer: Int, val button: Int ) { private val mutablePoints = mutableListOf<Point>() var recognizer: GestureRecognizer? by GDelegates.observable(null) { _, _: GestureRecognizer?, new: GestureRecognizer? -> new?.stage?.activeContinuousGestureRecognizers?.forEach { if (it != new) it.onTouchUsedByRecognizer(this) } } var finished = false private set val points: List<Point> get() = mutablePoints fun finish() { finished = true } fun addPoint(point: Vec2) { mutablePoints += Point(point.immutable(), Date()) } operator fun plusAssign(point: Vec2) { addPoint(point) } data class Point( val position: ImmutableVec2, val date: Date ) }
apache-2.0
a6cbdc54f182efb2cd4ebf0b05ca85a6
19.325581
121
0.719359
3.281955
false
false
false
false
felipebz/sonar-plsql
sonar-zpa-plugin/src/main/kotlin/org/sonar/plsqlopen/PlSqlSquidSensor.kt
1
3879
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plsqlopen import org.sonar.api.batch.rule.ActiveRules import org.sonar.api.batch.sensor.Sensor import org.sonar.api.batch.sensor.SensorContext import org.sonar.api.batch.sensor.SensorDescriptor import org.sonar.api.config.Configuration import org.sonar.api.issue.NoSonarFilter import org.sonar.api.measures.FileLinesContextFactory import org.sonar.plsqlopen.checks.CheckList import org.sonar.plsqlopen.metadata.FormsMetadata import org.sonar.plsqlopen.rules.SonarQubeActiveRulesAdapter import org.sonar.plsqlopen.rules.SonarQubeRuleMetadataLoader import org.sonar.plsqlopen.squid.PlSqlAstScanner import org.sonar.plsqlopen.squid.ProgressReport import org.sonar.plsqlopen.utils.log.Logger import org.sonar.plsqlopen.utils.log.Loggers import org.sonar.plugins.plsqlopen.api.ZpaRulesDefinition import java.util.concurrent.TimeUnit class PlSqlSquidSensor @JvmOverloads constructor(activeRules: ActiveRules, settings: Configuration, private val noSonarFilter: NoSonarFilter, private val fileLinesContextFactory: FileLinesContextFactory, customRulesDefinition: Array<ZpaRulesDefinition>? = null) : Sensor { private val logger: Logger = Loggers.getLogger(PlSqlSquidSensor::class.java) private val checks = PlSqlChecks.createPlSqlCheck(SonarQubeActiveRulesAdapter(activeRules), SonarQubeRuleMetadataLoader()) .addChecks(PlSqlRuleRepository.KEY, CheckList.checks) .addCustomChecks(customRulesDefinition) private val isErrorRecoveryEnabled = settings.getBoolean(PlSqlPlugin.ERROR_RECOVERY_KEY).orElse(false) private val isConcurrentModeEnabled = settings.getBoolean(PlSqlPlugin.CONCURRENT_EXECUTION_KEY).orElse(true) private val formsMetadata = FormsMetadata.loadFromFile(settings.get(PlSqlPlugin.FORMS_METADATA_KEY) .orElse(null)) override fun describe(descriptor: SensorDescriptor) { descriptor.name("Z PL/SQL Analyzer").onlyOnLanguage(PlSql.KEY) } override fun execute(context: SensorContext) { val fs = context.fileSystem() val inputFiles = fs.inputFiles(fs.predicates().hasLanguage(PlSql.KEY)).toList() val progressReport = ProgressReport("Report about progress of code analyzer", TimeUnit.SECONDS.toMillis(10)) val scanner = PlSqlAstScanner(context, checks, noSonarFilter, formsMetadata, isErrorRecoveryEnabled, fileLinesContextFactory) progressReport.start(inputFiles.map { it.toString() }) val files = if (isConcurrentModeEnabled) { logger.info("Concurrent mode enabled") inputFiles.parallelStream() } else { inputFiles.stream() } files.forEach { try { scanner.scanFile(it) progressReport.nextFile() } catch (e: Exception) { logger.error("Error during analysis of file $it", e) } } progressReport.stop() } }
lgpl-3.0
35aed9e499f7988c1dd3d91dc2d98f1b
43.079545
141
0.729312
4.388009
false
false
false
false
luanalbineli/popularmovies
app/src/main/java/com/themovielist/mainactivity/MainActivity.kt
1
4009
package com.themovielist.mainactivity import android.app.Fragment import android.app.FragmentManager import android.os.Bundle import android.support.design.widget.AppBarLayout import android.support.design.widget.CoordinatorLayout import com.themovielist.R import com.themovielist.base.BaseActivity import com.themovielist.browse.MovieBrowseFragment import com.themovielist.favorite.FavoriteFragment import com.themovielist.home.HomeFragment import com.themovielist.intheaters.InTheatersFragment import com.themovielist.util.setDisplay import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.content_main.* class MainActivity : BaseActivity(), FragmentManager.OnBackStackChangedListener { // Default tab. private var mSelectedItemId = R.id.bottom_menu_item_home override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) vsMainContent.layoutResource = R.layout.content_main vsMainContent.inflate() setSupportActionBar(toolbar) if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_TAB_BUNDLE_KEY)) { mSelectedItemId = savedInstanceState.getInt(SELECTED_TAB_BUNDLE_KEY) } bnvBottomNavigationView.setOnNavigationItemSelectedListener { menuItem -> mSelectedItemId = menuItem.itemId setUpMainContentFragment() // TODO: INTEGRATE THE SEARCH BAR WITH THE APP BAR val appBarSearchMode = mSelectedItemId == R.id.bottom_menu_item_browse appBarLayout.setDisplay(!appBarSearchMode) val params = llContentContainer.layoutParams as CoordinatorLayout.LayoutParams params.behavior = if (appBarSearchMode) null else AppBarLayout.ScrollingViewBehavior() llContentContainer.requestLayout() true } bnvBottomNavigationView.selectedItemId = mSelectedItemId setUpMainContentFragment() fragmentManager.addOnBackStackChangedListener(this) checkShouldDisplayBackButton() } private fun setUpMainContentFragment() { when (mSelectedItemId) { R.id.bottom_menu_item_home -> checkChangeMainContent(HOME_FRAGMENT_TAG) { HomeFragment.getInstance() } R.id.bottom_menu_item_browse -> checkChangeMainContent(BROWSE_FRAGMENT_TAG) { MovieBrowseFragment.getInstance() } R.id.bottom_menu_item_cinema -> checkChangeMainContent(IN_THEATERS_FRAGMENT_TAG) { InTheatersFragment.getInstance() } R.id.bottom_menu_item_favorite -> checkChangeMainContent(FAVORITE_FRAGMENT_TAG) { FavoriteFragment.getInstance() } } } private fun checkChangeMainContent(fragmentTag: String, fragmentInstanceInvoker: () -> Fragment) { replaceFragment(fragmentManager, R.id.flMainContent, fragmentTag, fragmentInstanceInvoker) } private fun checkShouldDisplayBackButton() { val shouldDisplayBackButton = fragmentManager.backStackEntryCount > 0 supportActionBar?.setDisplayHomeAsUpEnabled(shouldDisplayBackButton) } override fun onSupportNavigateUp(): Boolean { fragmentManager.popBackStack() return true } override fun onBackStackChanged() { checkShouldDisplayBackButton() } public override fun onSaveInstanceState(outState: Bundle?) { super.onSaveInstanceState(outState) outState?.putInt(SELECTED_TAB_BUNDLE_KEY, mSelectedItemId) } companion object { private const val SELECTED_TAB_BUNDLE_KEY = "selected_tab" private const val HOME_FRAGMENT_TAG = "home_fragment" private const val BROWSE_FRAGMENT_TAG = "browse_fragment" private const val IN_THEATERS_FRAGMENT_TAG = "in_theaters_fragment" private const val FAVORITE_FRAGMENT_TAG = "favorite_fragment" } }
apache-2.0
9c52e54871d4cf1fe6b6e9b5370c152d
36.820755
102
0.711649
4.980124
false
false
false
false
google/private-compute-services
src/com/google/android/as/oss/policies/impl/AssetLoader.kt
1
2036
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.`as`.oss.policies.impl import android.content.Context import arcs.core.data.proto.ManifestProto import arcs.core.data.proto.PolicyProto import com.google.android.`as`.oss.policies.api.PolicyMap import com.google.common.collect.ArrayListMultimap import com.google.common.collect.Multimap import dagger.hilt.android.qualifiers.ApplicationContext /** Helper functions for loading policies from assets. */ object AssetLoader { /** * Loads a set of policies from the specified assets. * * @param context The app's context. * @param fileNames The set of file names of the assets containing the policies to load. * @return A Multimap from policy name to the policy's specification. */ fun loadPolicyMapFromAssets( @ApplicationContext context: Context, vararg fileNames: String ): PolicyMap { val policyMap: Multimap<String, PolicyProto> = ArrayListMultimap.create() setOf(*fileNames).forEach { val policy = loadPolicyFromAsset(context, it) policyMap.put(policy.name, policy) } return policyMap } fun loadPolicyFromAsset(@ApplicationContext context: Context, fileName: String): PolicyProto { val manifest = ManifestProto.parseFrom(context.assets.open(fileName).use { it.readBytes() }) check(manifest.policiesCount == 1) { "$fileName has ${manifest.policiesCount} policies, expected 1." } return manifest.policiesList.first() } }
apache-2.0
cdd3731f1067c3b7e521123a48ad0d6d
35.357143
96
0.742141
4.232848
false
false
false
false
ozodrukh/android-pkg-installer
src/main/java/com/ozodrukh/android/pkg/installer/Timber.kt
1
1308
package com.ozodrukh.android.pkg.installer /** * @author Ozodrukh */ object Timber { private val trees: ArrayList<Tree> = arrayListOf<Tree>() fun plant(tree: Tree) { trees += tree } fun d(tag: String, message: String, vararg args: Any = emptyArray()) { trees.forEach { it.log(LogLevel.DEBUG, tag, message, null, *args) } } fun i(tag: String, message: String, vararg args: Any = emptyArray()) { trees.forEach { it.log(LogLevel.INFO, tag, message, null, *args) } } fun e(tag: String, error: Throwable?, message: String, vararg args: Any = emptyArray()) { trees.forEach { it.log(LogLevel.ERROR, tag, message, error, *args) } } enum class LogLevel { DEBUG, INFO, ERROR; internal open fun print(message: String) = System.out.println("$name -- $message") } abstract class Tree { abstract fun log(level: LogLevel, tag: String, message: String, error: Throwable?, vararg args: Any) } class DebugTree : Tree() { override fun log(level: LogLevel, tag: String, message: String, error: Throwable?, vararg args: Any) { level.print("$tag: ${String.format(message, args)}") error?.let { level.print(it.message!!) } } } }
mit
031a7a800a2b114b59c3c3f7ebb0aa80
26.829787
110
0.594037
3.780347
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/storage/structure/DbStructureAdaptiveExp.kt
2
312
package org.stepic.droid.storage.structure object DbStructureAdaptiveExp { const val ADAPTIVE_EXP = "adaptive_exp" object Column { const val EXP = "exp" const val SUBMISSION_ID = "submission_id" const val SOLVED_AT = "solved_at" const val COURSE_ID = "course_id" } }
apache-2.0
8e82d1bdd9eeb6483c479b9a53d045bd
25.083333
49
0.644231
3.627907
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/ieee754/inline.kt
1
1159
// IGNORE_BACKEND: JS inline fun less(a: Comparable<Double>, b: Double): Boolean { return a < b } inline fun equals(a: Comparable<Double>, b: Comparable<Double>): Boolean { return a == b } inline fun <T: Comparable<Double>> lessGeneric(a: T, b: Double): Boolean { return a < b } inline fun <T: Comparable<Double>> equalsGeneric(a: T, b: Double): Boolean { return a == b } inline fun <reified T: Comparable<Double>> lessReified(a: T, b: Double): Boolean { return a < b } inline fun <reified T: Comparable<Double>> equalsReified(a: T, b: T): Boolean { return a == b } inline fun less754(a: Double, b: Double): Boolean { return a < b } inline fun equals754(a: Double, b: Double): Boolean { return a == b } fun box(): String { if (!less(-0.0, 0.0)) return "fail 1" if (equals(-0.0, 0.0)) return "fail 2" if (!lessGeneric(-0.0, 0.0)) return "fail 3" if (equalsGeneric(-0.0, 0.0)) return "fail 4" if (!lessReified(-0.0, 0.0)) return "fail 5" if (equalsReified(-0.0, 0.0)) return "fail 6" if (less754(-0.0, 0.0)) return "fail 7" if (!equals754(-0.0, 0.0)) return "fail 8" return "OK" }
apache-2.0
af38bed246d9ec4c2bc81a978390c682
22.673469
82
0.612597
2.926768
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/exh/log/EHDebugModeOverlay.kt
1
2608
package exh.log import android.content.Context import android.text.Html import android.view.View import android.view.ViewGroup import com.ms_square.debugoverlay.DataObserver import com.ms_square.debugoverlay.OverlayModule import eu.kanade.tachiyomi.BuildConfig import android.widget.LinearLayout import android.widget.TextView import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.util.dpToPx import uy.kohesive.injekt.injectLazy class EHDebugModeOverlay(private val context: Context) : OverlayModule<String>(null, null) { private var textView: TextView? = null private val prefs: PreferencesHelper by injectLazy() override fun start() {} override fun stop() {} override fun notifyObservers() {} override fun addObserver(observer: DataObserver<Any>) { observer.onDataAvailable(buildInfo()) } override fun removeObserver(observer: DataObserver<Any>) {} override fun onDataAvailable(data: String?) { textView?.text = Html.fromHtml(data) } override fun createView(root: ViewGroup, textColor: Int, textSize: Float, textAlpha: Float): View { val view = LinearLayout(root.context) view.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) view.setPadding(4.dpToPx, 0, 4.dpToPx, 4.dpToPx) val textView = TextView(view.context) textView.setTextColor(textColor) textView.textSize = textSize textView.alpha = textAlpha textView.text = Html.fromHtml(buildInfo()) textView.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) view.addView(textView) this.textView = textView return view } fun buildInfo() = """ <font color='green'>===[ ${context.getString(R.string.app_name)} ]===</font><br> <b>Build type:</b> ${BuildConfig.BUILD_TYPE}<br> <b>Debug mode:</b> ${BuildConfig.DEBUG.asEnabledString()}<br> <b>Version code:</b> ${BuildConfig.VERSION_CODE}<br> <b>Commit SHA:</b> ${BuildConfig.COMMIT_SHA}<br> <b>Log level:</b> ${EHLogLevel.currentLogLevel.name.toLowerCase()}<br> <b>Source blacklist:</b> ${prefs.eh_enableSourceBlacklist().getOrDefault().asEnabledString()} """.trimIndent() private fun Boolean.asEnabledString() = if(this) "enabled" else "disabled" }
apache-2.0
ccea382901b372b88c3770f12274a3fa
39.138462
103
0.693252
4.247557
false
true
false
false
mattvchandler/ProgressBars
app/src/main/java/settings/TimeZone_disp.kt
1
8225
/* Copyright (C) 2020 Matthew Chandler 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.mattvchandler.progressbars.settings import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.Toolbar import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.SortedList import org.mattvchandler.progressbars.R import org.mattvchandler.progressbars.databinding.ActivityTimezoneBinding import org.mattvchandler.progressbars.databinding.TimezoneItemBinding import org.mattvchandler.progressbars.util.Dynamic_theme_activity import java.io.Serializable import java.util.* class TimeZone_disp(val id: String, context: Context?, date: Date?): Serializable { val name = id.replace('_', ' ') val subtitle:String? val search_kwds: List<String> init { val tz = TimeZone.getTimeZone(id) val is_daylight = if(date != null) tz.inDaylightTime(date) else false val disp_name = tz.getDisplayName(is_daylight, TimeZone.LONG) val short_name = tz.getDisplayName(is_daylight, TimeZone.SHORT) subtitle = context?.resources?.getString(R.string.tz_list_subtitle, disp_name, short_name) search_kwds = listOf(name, id, disp_name, short_name).map{ it.toLowerCase(Locale.getDefault()) }.distinct() } override fun toString() = name override fun equals(other: Any?): Boolean { if(this === other) return true if(javaClass != other?.javaClass) return false other as TimeZone_disp if(id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } } private class TimeZone_adapter(private val activity: TimeZone_activity, private val date: Date): RecyclerView.Adapter<TimeZone_adapter.Holder>() { inner class Holder(private val binding: TimezoneItemBinding, view: View): RecyclerView.ViewHolder(view), View.OnClickListener { lateinit var tz: TimeZone_disp fun set() { val position = adapterPosition if(position == RecyclerView.NO_POSITION) return tz = timezones[position] binding.tz = tz } override fun onClick(v: View?) { val intent = Intent() intent.putExtra(TimeZone_activity.EXTRA_SELECTED_TZ, tz) activity.setResult(AppCompatActivity.RESULT_OK, intent) activity.finish() } } private var timezones = SortedList(TimeZone_disp::class.java, object: SortedList.Callback<TimeZone_disp>() { override fun onMoved(from_pos: Int, to_pos: Int) { notifyItemMoved(from_pos, to_pos) } override fun onChanged(pos: Int, count: Int) { notifyItemRangeChanged(pos, count) } override fun onInserted(pos: Int, count: Int) { notifyItemRangeInserted(pos, count) } override fun onRemoved(pos: Int, count: Int) { notifyItemRangeRemoved(pos, count) } override fun compare(a: TimeZone_disp, b: TimeZone_disp) = compareBy<TimeZone_disp>{ it.id }.compare(a, b) override fun areItemsTheSame(a: TimeZone_disp, b: TimeZone_disp) = a == b override fun areContentsTheSame(a: TimeZone_disp, b: TimeZone_disp) = a == b }) private val inflater = LayoutInflater.from(activity) init { filter("") } fun filter(search: String) { val all_tzs = TimeZone.getAvailableIDs().map{ TimeZone_disp(it, activity, date) } if(search == "") replace_all(all_tzs) else replace_all(all_tzs.filter{ tz -> tz.search_kwds.any{it.contains(search.toLowerCase(Locale.getDefault()))} }) } fun replace_all(tzs: List<TimeZone_disp>) { timezones.beginBatchedUpdates() for(i in timezones.size() - 1 downTo 0) { val tz = timezones.get(i) if(tz !in tzs) timezones.remove(tz) } timezones.addAll(tzs) timezones.endBatchedUpdates() } override fun getItemCount(): Int { return timezones.size() } override fun onCreateViewHolder(parent_in: ViewGroup, viewType: Int): Holder { val binding = TimezoneItemBinding.inflate(inflater, parent_in, false) val holder = Holder(binding, binding.root) binding.root.setOnClickListener(holder) return holder } override fun onBindViewHolder(holder: Holder, position: Int) { holder.set() } } class TimeZone_activity: Dynamic_theme_activity() { private lateinit var adapter: TimeZone_adapter private var saved_search: String? = null private lateinit var binding: ActivityTimezoneBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_timezone) setSupportActionBar(binding.toolbar as Toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) consume_insets(this, binding.timezoneList, binding.appbarLayout) val date = intent.getSerializableExtra(EXTRA_DATE) as Date adapter = TimeZone_adapter(this, date) binding.timezoneList.adapter = adapter binding.timezoneList.layoutManager = LinearLayoutManager(this) if(savedInstanceState != null) saved_search = savedInstanceState.getString(SAVE_SEARCH) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(SAVE_SEARCH, saved_search) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.timezone_action_bar, menu) val search_item = menu?.findItem(R.id.timezone_search)!! val search = search_item.actionView as SearchView search.maxWidth = Int.MAX_VALUE search.setOnQueryTextListener(object: SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { search.clearFocus() return true } override fun onQueryTextChange(newText: String?): Boolean { saved_search = newText adapter.filter(newText?: "") binding.timezoneList.scrollToPosition(0) return true } }) if(saved_search != null) { search.setQuery(saved_search, true) search.clearFocus() } else search.requestFocus() return super.onCreateOptionsMenu(menu) } companion object { const val EXTRA_DATE = "org.mattvchandler.progressbars.EXTRA_DATE" const val EXTRA_SELECTED_TZ = "org.mattvchandler.progressbars.EXTRA_SELECTED_ID" private const val SAVE_SEARCH = "search" } }
mit
4b9a1f39817609d00637d782ec162c3c
32.434959
144
0.677568
4.546711
false
false
false
false
da1z/intellij-community
platform/script-debugger/backend/src/debugger/StandaloneVmHelper.kt
6
3132
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.util.io.addChannelListener import com.intellij.util.io.shutdownIfOio import io.netty.channel.Channel import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.errorIfNotMessage import org.jetbrains.concurrency.nullPromise import org.jetbrains.jsonProtocol.Request import org.jetbrains.rpc.CONNECTION_CLOSED_MESSAGE import org.jetbrains.rpc.LOG import org.jetbrains.rpc.MessageProcessor open class StandaloneVmHelper(private val vm: Vm, private val messageProcessor: MessageProcessor, channel: Channel) : AttachStateManager { private @Volatile var channel: Channel? = channel fun getChannelIfActive(): Channel? { val currentChannel = channel return if (currentChannel == null || !currentChannel.isActive) null else currentChannel } fun write(content: Any): Boolean { val channel = getChannelIfActive() return channel != null && !channel.writeAndFlush(content).isCancelled } interface VmEx : Vm { fun createDisconnectRequest(): Request<out Any>? } override val isAttached: Boolean get() = channel != null override fun detach(): Promise<*> { val currentChannel = channel ?: return nullPromise() messageProcessor.cancelWaitingRequests() val disconnectRequest = (vm as? VmEx)?.createDisconnectRequest() val promise = AsyncPromise<Any?>() if (disconnectRequest == null) { messageProcessor.closed() channel = null } else { messageProcessor.send(disconnectRequest) .rejected { if (it.message != CONNECTION_CLOSED_MESSAGE) { LOG.errorIfNotMessage(it) } } // we don't wait response because 1) no response to "disconnect" message (V8 for example) 2) closed message manager just ignore any incoming messages currentChannel.flush() messageProcessor.closed() channel = null messageProcessor.cancelWaitingRequests() } closeChannel(currentChannel, promise) return promise } protected open fun closeChannel(channel: Channel, promise: AsyncPromise<Any?>) { doCloseChannel(channel, promise) } } fun doCloseChannel(channel: Channel, promise: AsyncPromise<Any?>) { channel.close().addChannelListener { try { it.channel().eventLoop().shutdownIfOio() } finally { val error = it.cause() if (error == null) { promise.setResult(null) } else { promise.setError(error) } } } }
apache-2.0
1c084f50202eff088972b73a35f0fd94
31.298969
155
0.714559
4.436261
false
false
false
false
Heiner1/AndroidAPS
diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_ALARM_BLOCK.kt
1
2020
package info.nightscout.androidaps.diaconn.pumplog import java.nio.ByteBuffer import java.nio.ByteOrder /* * Injection Blocked Alarm Log */ class LOG_ALARM_BLOCK private constructor( val data: String, val dttm: String, typeAndKind: Byte, // 1=INFO, 2=WARNING, 3=MAJOR, 4=CRITICAL val alarmLevel: Byte, // 1=OCCUR val ack: Byte, val amount: Short, // 1=BASE, 2=Meal, 3=snack , 4=square, 5=dual, 6=tube change, 7=needle change, 8=insulin change val reason: Byte, val batteryRemain: Byte ) { val type: Byte = PumplogUtil.getType(typeAndKind) val kind: Byte = PumplogUtil.getKind(typeAndKind) override fun toString(): String { val sb = StringBuilder("LOG_ALARM_BLOCK{") sb.append("LOG_KIND=").append(LOG_KIND.toInt()) sb.append(", data='").append(data).append('\'') sb.append(", dttm='").append(dttm).append('\'') sb.append(", type=").append(type.toInt()) sb.append(", kind=").append(kind.toInt()) sb.append(", alarmLevel=").append(alarmLevel.toInt()) sb.append(", ack=").append(ack.toInt()) sb.append(", amount=").append(amount.toInt()) sb.append(", reason=").append(reason.toInt()) sb.append(", batteryRemain=").append(batteryRemain.toInt()) sb.append('}') return sb.toString() } companion object { const val LOG_KIND: Byte = 0x29 fun parse(data: String): LOG_ALARM_BLOCK { val bytes = PumplogUtil.hexStringToByteArray(data) val buffer = ByteBuffer.wrap(bytes) buffer.order(ByteOrder.LITTLE_ENDIAN) return LOG_ALARM_BLOCK( data, PumplogUtil.getDttm(buffer), PumplogUtil.getByte(buffer), PumplogUtil.getByte(buffer), PumplogUtil.getByte(buffer), PumplogUtil.getShort(buffer), PumplogUtil.getByte(buffer), PumplogUtil.getByte(buffer) ) } } }
agpl-3.0
178d12bb7d43472349be699d06af36b5
33.254237
118
0.595545
4.089069
false
false
false
false
kvakil/venus
src/main/kotlin/venus/riscv/insts/xori.kt
1
255
package venus.riscv.insts import venus.riscv.insts.dsl.ITypeInstruction val xori = ITypeInstruction( name = "xori", opcode = 0b0010011, funct3 = 0b100, eval32 = { a, b -> a xor b }, eval64 = { a, b -> a xor b } )
mit
c3faa3c9fb1fb6ba9551ac78fa97298d
22.181818
45
0.568627
3.109756
false
false
false
false
unbroken-dome/gradle-xjc-plugin
src/integrationTest/kotlin/org/unbrokendome/gradle/plugins/xjc/testutil/GradleRunnerExtension.kt
1
2063
package org.unbrokendome.gradle.plugins.xjc.testutil import org.gradle.testkit.runner.GradleRunner import org.junit.jupiter.api.extension.BeforeEachCallback import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.api.extension.ParameterContext import org.junit.jupiter.api.extension.ParameterResolver private val namespace = ExtensionContext.Namespace.create(GradleRunnerExtension::class.java) private val ExtensionContext.store: ExtensionContext.Store get() = getStore(namespace) typealias GradleRunnerModifier = GradleRunner.() -> GradleRunner private object GradleRunnerModifierStoreKey @Suppress("UNCHECKED_CAST") private val ExtensionContext.gradleRunnerModifier: GradleRunnerModifier? get() = store.get(GradleRunnerModifierStoreKey) as GradleRunnerModifier? private operator fun GradleRunnerModifier?.plus(other: GradleRunnerModifier?): GradleRunnerModifier? = when { this == null -> other other == null -> this else -> { { this@plus().other() } } } class GradleRunnerExtension : ParameterResolver { override fun supportsParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Boolean = parameterContext.parameter.type == GradleRunner::class.java override fun resolveParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Any { val projectDir = extensionContext.gradleProjectDir val modifier = extensionContext.gradleRunnerModifier return GradleRunner.create() .withProjectDir(projectDir) .withPluginClasspath() .withDebug(true) .forwardOutput() .let { modifier?.invoke(it) ?: it } } } class GradleRunnerModifierExtension( private val modifier: GradleRunnerModifier ) : BeforeEachCallback { override fun beforeEach(context: ExtensionContext) { context.store.put( GradleRunnerModifierStoreKey, context.gradleRunnerModifier + modifier ) } }
mit
bfffe1f2cbe3dc6daff1141b41593e74
29.338235
117
0.735337
5.303342
false
false
false
false
searene/OneLetterOnePage
src/main/kotlin/com/searene/domain/Ip2LocationDb34.kt
1
704
package com.searene.domain import java.io.Serializable import javax.persistence.Entity import javax.persistence.Id import javax.persistence.IdClass import javax.persistence.Table class CompositeKey4(val ipFrom: Long, val ipTo: Long): Serializable { constructor() : this(ipFrom = 0, ipTo = 0) } @Entity @IdClass(CompositeKey4::class) @Table(name = "ip2location_db3_4") class Ip2LocationDb34( @Id val ipFrom: Long, @Id val ipTo: Long, val countryCode: String, val countryName: String, val regionName: String, val cityName: String ) { constructor() : this(ipFrom = 0, ipTo = 0, countryCode = "", countryName = "", regionName = "", cityName = "") }
apache-2.0
5b55de5748eab86f0e3ab5caa9706ddd
26.115385
114
0.684659
3.591837
false
false
false
false
slesar/Layers
app/src/main/java/com/psliusar/layers/sample/screen/dialog/CustomDialogLayer.kt
1
1468
package com.psliusar.layers.sample.screen.dialog import android.os.Bundle import android.view.View import android.widget.TextView import com.psliusar.layers.DialogWrapper import com.psliusar.layers.Layer import com.psliusar.layers.sample.R private const val ARGS_TITLE = "ARGS_TITLE" class CustomDialogLayer : Layer(R.layout.screen_dialog_custom) { private val dialogWrapper = DialogWrapper(this).apply { cancelable = false } init { addDelegate(dialogWrapper) } override fun onBindView(savedState: Bundle?, view: View) { super.onBindView(savedState, view) getView<TextView>(R.id.dialog_title).text = arguments!!.getString(ARGS_TITLE) getView<View>(R.id.dialog_action1).setOnClickListener { getParent<OnCustomDialogListener>().onDialogAction1(this) dialogWrapper.dismiss(false) } getView<View>(R.id.dialog_action2).setOnClickListener { getParent<OnCustomDialogListener>().onDialogAction2(this) dialogWrapper.dismiss(false) } } interface OnCustomDialogListener : DialogWrapper.OnLayerDialogListener { fun onDialogAction1(dialog: CustomDialogLayer) fun onDialogAction2(dialog: CustomDialogLayer) } companion object { fun createArguments(title: String): Bundle { val bundle = Bundle() bundle.putString(ARGS_TITLE, title) return bundle } } }
apache-2.0
7a0c95694f50de09ba1e28c5acaff6d1
28.36
85
0.684605
4.242775
false
false
false
false
Maccimo/intellij-community
platform/platform-impl/src/com/intellij/ide/projectWizard/NewProjectWizardConstants.kt
2
1111
// 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.ide.projectWizard object NewProjectWizardConstants { object Language { const val JAVA = "Java" const val KOTLIN = "Kotlin" const val GROOVY = "Groovy" const val JAVASCRIPT = "JavaScript" const val HTML = "HTML" const val PYTHON = "Python" const val PHP = "PHP" const val RUBY = "Ruby" const val GO = "Go" const val SCALA = "Scala" val ALL = arrayOf(JAVA, KOTLIN, GROOVY, JAVASCRIPT, HTML, PYTHON, PHP, RUBY, GO, SCALA) val ALL_DSL = arrayOf(KOTLIN, GROOVY) } object BuildSystem { const val INTELLIJ = "IntelliJ" const val GRADLE = "Gradle" const val MAVEN = "Maven" const val SBT = "SBT" val ALL = arrayOf(INTELLIJ, GRADLE, MAVEN, SBT) } object Generators { const val EMPTY_PROJECT = "empty-project" const val EMPTY_WEB_PROJECT = "empty-web-project" const val SIMPLE_PROJECT = "simple-project" const val SIMPLE_MODULE = "simple-module" } const val OTHER = "other" }
apache-2.0
bade86865d4dcaa89a814edbdd2f5bf0
28.263158
120
0.666967
3.678808
false
false
false
false
blindpirate/gradle
subprojects/kotlin-dsl-provider-plugins/src/main/kotlin/org/gradle/kotlin/dsl/provider/plugins/precompiled/DefaultPrecompiledScriptPluginsSupport.kt
1
18349
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.provider.plugins.precompiled import org.gradle.api.GradleException import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.file.Directory import org.gradle.api.file.FileCollection import org.gradle.api.file.SourceDirectorySet import org.gradle.api.initialization.Settings import org.gradle.api.internal.plugins.DefaultPluginManager import org.gradle.api.invocation.Gradle import org.gradle.api.model.ObjectFactory import org.gradle.api.provider.Provider import org.gradle.api.tasks.ClasspathNormalizer import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.SourceSetContainer import org.gradle.api.tasks.TaskContainer import org.gradle.api.tasks.TaskProvider import org.gradle.internal.classpath.Instrumented.fileCollectionObserved import org.gradle.internal.deprecation.Documentation import org.gradle.internal.fingerprint.classpath.ClasspathFingerprinter import org.gradle.kotlin.dsl.* import org.gradle.kotlin.dsl.precompile.v1.PrecompiledInitScript import org.gradle.kotlin.dsl.precompile.v1.PrecompiledProjectScript import org.gradle.kotlin.dsl.precompile.v1.PrecompiledSettingsScript import org.gradle.kotlin.dsl.provider.PrecompiledScriptPluginsSupport import org.gradle.kotlin.dsl.provider.inClassPathMode import org.gradle.kotlin.dsl.provider.plugins.precompiled.DefaultPrecompiledScriptPluginsSupport.Companion.PRECOMPILED_SCRIPT_MANUAL import org.gradle.kotlin.dsl.provider.plugins.precompiled.tasks.CompilePrecompiledScriptPluginPlugins import org.gradle.kotlin.dsl.provider.plugins.precompiled.tasks.ConfigurePrecompiledScriptDependenciesResolver import org.gradle.kotlin.dsl.provider.plugins.precompiled.tasks.ExtractPrecompiledScriptPluginPlugins import org.gradle.kotlin.dsl.provider.plugins.precompiled.tasks.GenerateExternalPluginSpecBuilders import org.gradle.kotlin.dsl.provider.plugins.precompiled.tasks.GeneratePrecompiledScriptPluginAccessors import org.gradle.kotlin.dsl.provider.plugins.precompiled.tasks.GenerateScriptPluginAdapters import org.gradle.kotlin.dsl.provider.plugins.precompiled.tasks.HashedProjectSchema import org.gradle.kotlin.dsl.provider.plugins.precompiled.tasks.resolverEnvironmentStringFor import org.gradle.kotlin.dsl.support.ImplicitImports import org.gradle.kotlin.dsl.support.serviceOf import org.gradle.plugin.devel.GradlePluginDevelopmentExtension import org.gradle.plugin.devel.plugins.JavaGradlePluginPlugin import org.gradle.tooling.model.kotlin.dsl.KotlinDslModelsParameters import java.io.File import java.util.function.Consumer import javax.inject.Inject /** * Exposes `*.gradle.kts` scripts from regular Kotlin source-sets as binary Gradle plugins. * * ## Defining the plugin target * * Precompiled script plugins can target one of the following Gradle model types, [Gradle], [Settings] or [Project]. * * The target of a given script plugin is defined via its file name suffix in the following manner: * - the `.init.gradle.kts` file name suffix defines a [Gradle] script plugin * - the `.settings.gradle.kts` file name suffix defines a [Settings] script plugin * - and finally, the simpler `.gradle.kts` file name suffix defines a [Project] script plugin * * ## Defining the plugin id * * The Gradle plugin id for a precompiled script plugin is defined via its file name * plus optional package declaration in the following manner: * - for a script without a package declaration, the plugin id is simply the file name without the * related plugin target suffix (see above) * - for a script containing a package declaration, the plugin id is the declared package name dot the file name without the * related plugin target suffix (see above) * * For a concrete example, take the definition of a precompiled [Project] script plugin id of * `my.project.plugin`. Given the two rules above, there are two conventional ways to do it: * * by naming the script `my.project.plugin.gradle.kts` and including no package declaration * * by naming the script `plugin.gradle.kts` and including a package declaration of `my.project`: * ```kotlin * // plugin.gradle.kts * package my.project * * // ... plugin implementation ... * ``` * ## Applying plugins * Precompiled script plugins can apply plugins much in the same way as regular scripts can, using one * of the many `apply` method overloads or, in the case of [Project] scripts, via the `plugins` block. * * And just as regular [Project] scripts can take advantage of * [type-safe model accessors](https://docs.gradle.org/current/userguide/kotlin_dsl.html#type-safe-accessors) * to model elements contributed by plugins applied via the `plugins` block, so can precompiled [Project] script plugins: * ```kotlin * // java7-project.gradle.kts * * plugins { * java * } * * java { // type-safe model accessor to the `java` extension contributed by the `java` plugin * sourceCompatibility = JavaVersion.VERSION_1_7 * targetCompatibility = JavaVersion.VERSION_1_7 * } * ``` * ## Implementation Notes * External plugin dependencies are declared as regular artifact dependencies but a more * semantic preserving model could be introduced in the future. * * ### Type-safe accessors * The process of generating type-safe accessors for precompiled script plugins is carried out by the * following tasks: * - [ExtractPrecompiledScriptPluginPlugins] - extracts the `plugins` block of every precompiled script plugin and * saves it to a file with the same name in the output directory * - [GenerateExternalPluginSpecBuilders] - generates plugin spec builders for the plugins in the compile classpath * - [CompilePrecompiledScriptPluginPlugins] - compiles the extracted `plugins` blocks along with the internal * and external plugin spec builders * - [GeneratePrecompiledScriptPluginAccessors] - uses the compiled `plugins` block of each precompiled script plugin * to compute its [HashedProjectSchema] and emit the corresponding type-safe accessors */ class DefaultPrecompiledScriptPluginsSupport : PrecompiledScriptPluginsSupport { companion object { val PRECOMPILED_SCRIPT_MANUAL = Documentation.userManual("custom_plugins", "sec:precompiled_plugins")!! } override fun enableOn(target: PrecompiledScriptPluginsSupport.Target): Boolean = target.project.run { val scriptPluginFiles = collectScriptPluginFiles() if (scriptPluginFiles.isEmpty()) { return false } val scriptPlugins = scriptPluginFiles.map(::PrecompiledScriptPlugin) enableScriptCompilationOf( scriptPlugins, target.kotlinSourceDirectorySet ) plugins.withType<JavaGradlePluginPlugin> { exposeScriptsAsGradlePlugins( scriptPlugins, target.kotlinSourceDirectorySet ) } return true } @Deprecated("Use enableOn(Target)") override fun enableOn( project: Project, kotlinSourceDirectorySet: SourceDirectorySet, kotlinCompileTask: TaskProvider<out Task>, kotlinCompilerArgsConsumer: Consumer<List<String>> ) { enableOn(object : PrecompiledScriptPluginsSupport.Target { override val project get() = project override val kotlinSourceDirectorySet get() = kotlinSourceDirectorySet @Deprecated("No longer used.", ReplaceWith("")) override val kotlinCompileTask get() = error("No longer used.") @Deprecated("No longer used.", ReplaceWith("")) override fun applyKotlinCompilerArgs(args: List<String>) = error("No longer used.") }) } override fun collectScriptPluginFilesOf(project: Project): List<File> = project.collectScriptPluginFiles().toList() } private fun Project.enableScriptCompilationOf( scriptPlugins: List<PrecompiledScriptPlugin>, kotlinSourceDirectorySet: SourceDirectorySet ) { val extractedPluginsBlocks = buildDir("kotlin-dsl/plugins-blocks/extracted") val compiledPluginsBlocks = buildDir("kotlin-dsl/plugins-blocks/compiled") val accessorsMetadata = buildDir("kotlin-dsl/precompiled-script-plugins-metadata/accessors") val pluginSpecBuildersMetadata = buildDir("kotlin-dsl/precompiled-script-plugins-metadata/plugin-spec-builders") val compileClasspath: FileCollection = sourceSets["main"].compileClasspath tasks { val extractPrecompiledScriptPluginPlugins by registering(ExtractPrecompiledScriptPluginPlugins::class) { plugins = scriptPlugins outputDir.set(extractedPluginsBlocks) } val (generateExternalPluginSpecBuilders, externalPluginSpecBuilders) = codeGenerationTask<GenerateExternalPluginSpecBuilders>( "external-plugin-spec-builders", "generateExternalPluginSpecBuilders", kotlinSourceDirectorySet ) { classPathFiles.from(compileClasspath) sourceCodeOutputDir.set(it) metadataOutputDir.set(pluginSpecBuildersMetadata) } val compilePluginsBlocks by registering(CompilePrecompiledScriptPluginPlugins::class) { dependsOn(extractPrecompiledScriptPluginPlugins) sourceDir(extractedPluginsBlocks) dependsOn(generateExternalPluginSpecBuilders) sourceDir(externalPluginSpecBuilders) classPathFiles.from(compileClasspath) outputDir.set(compiledPluginsBlocks) } val (generatePrecompiledScriptPluginAccessors, _) = codeGenerationTask<GeneratePrecompiledScriptPluginAccessors>( "accessors", "generatePrecompiledScriptPluginAccessors", kotlinSourceDirectorySet ) { dependsOn(compilePluginsBlocks) classPathFiles.from(compileClasspath) runtimeClassPathFiles.from(configurations["runtimeClasspath"]) sourceCodeOutputDir.set(it) metadataOutputDir.set(accessorsMetadata) compiledPluginsBlocksDir.set(compiledPluginsBlocks) strict.set( providers .systemProperty("org.gradle.kotlin.dsl.precompiled.accessors.strict") .map(java.lang.Boolean::parseBoolean) .orElse(false) ) plugins = scriptPlugins } compileKotlin { dependsOn(generatePrecompiledScriptPluginAccessors) inputs.files(compileClasspath) .withNormalizer(ClasspathNormalizer::class.java) .withPropertyName("compileClasspath") inputs.dir(accessorsMetadata) .withPathSensitivity(PathSensitivity.RELATIVE) .ignoreEmptyDirectories() .withPropertyName("accessorsMetadata") inputs.property("kotlinDslScriptTemplates", scriptTemplates) configureScriptResolverEnvironmentOnDoFirst( objects, serviceOf(), compileClasspath, accessorsMetadata ) } if (inClassPathMode()) { val configurePrecompiledScriptDependenciesResolver by registering(ConfigurePrecompiledScriptDependenciesResolver::class) { dependsOn(generatePrecompiledScriptPluginAccessors) metadataDir.set(accessorsMetadata) classPathFiles.from(compileClasspath) onConfigure { resolverEnvironment -> objects.withInstance<TaskContainerScope>() { configureScriptResolverEnvironment(resolverEnvironment) } } } registerBuildScriptModelTask( configurePrecompiledScriptDependenciesResolver ) } } } private fun Task.configureScriptResolverEnvironmentOnDoFirst( objects: ObjectFactory, implicitImports: ImplicitImports, compileClasspath: FileCollection, accessorsMetadata: Provider<Directory> ) { doFirst { objects.withInstance<ResolverEnvironmentScope>() { configureScriptResolverEnvironment( resolverEnvironmentStringFor( implicitImports, classpathFingerprinter, compileClasspath, accessorsMetadata.get().asFile ) ) } } } private inline fun <reified T> ObjectFactory.withInstance(block: T.() -> Unit) { with(newInstance(), block) } private fun TaskContainerScope.configureScriptResolverEnvironment(resolverEnvironment: String) { taskContainer.compileKotlin { val scriptCompilerArgs = listOf( "-script-templates", scriptTemplates, // Propagate implicit imports and other settings "-Xscript-resolver-environment=$resolverEnvironment" ) withGroovyBuilder { getProperty("kotlinOptions").withGroovyBuilder { @Suppress("unchecked_cast") val freeCompilerArgs: List<String> = getProperty("freeCompilerArgs") as List<String> setProperty("freeCompilerArgs", freeCompilerArgs + scriptCompilerArgs) } } } } private fun TaskContainer.compileKotlin(action: Task.() -> Unit) { named("compileKotlin") { it.action() } } private interface TaskContainerScope { @get:Inject val taskContainer: TaskContainer } private interface ResolverEnvironmentScope : TaskContainerScope { @get:Inject val classpathFingerprinter: ClasspathFingerprinter } private fun Project.registerBuildScriptModelTask( modelTask: TaskProvider<out Task> ) { rootProject.tasks.named(KotlinDslModelsParameters.PREPARATION_TASK_NAME) { it.dependsOn(modelTask) } } private val scriptTemplates by lazy { listOf( // treat *.settings.gradle.kts files as Settings scripts PrecompiledSettingsScript::class.qualifiedName!!, // treat *.init.gradle.kts files as Gradle scripts PrecompiledInitScript::class.qualifiedName!!, // treat *.gradle.kts files as Project scripts PrecompiledProjectScript::class.qualifiedName!! ).joinToString(separator = ",") } private fun Project.exposeScriptsAsGradlePlugins(scriptPlugins: List<PrecompiledScriptPlugin>, kotlinSourceDirectorySet: SourceDirectorySet) { scriptPlugins.forEach { validateScriptPlugin(it) } declareScriptPlugins(scriptPlugins) generatePluginAdaptersFor(scriptPlugins, kotlinSourceDirectorySet) } private fun Project.collectScriptPluginFiles(): Set<File> = gradlePlugin.pluginSourceSet.allSource.matching { it.include("**/*.gradle.kts") }.filter { it.isFile }.also { // Declare build configuration input fileCollectionObserved(it, "Kotlin DSL") }.files private val Project.gradlePlugin get() = the<GradlePluginDevelopmentExtension>() private fun Project.validateScriptPlugin(scriptPlugin: PrecompiledScriptPlugin) { if (scriptPlugin.id == DefaultPluginManager.CORE_PLUGIN_NAMESPACE || scriptPlugin.id.startsWith(DefaultPluginManager.CORE_PLUGIN_PREFIX)) { throw GradleException( String.format( "The precompiled plugin (%s) cannot start with '%s' or be in the '%s' package.\n\n%s", this.relativePath(scriptPlugin.scriptFile), DefaultPluginManager.CORE_PLUGIN_NAMESPACE, DefaultPluginManager.CORE_PLUGIN_NAMESPACE, PRECOMPILED_SCRIPT_MANUAL.consultDocumentationMessage() ) ) } val existingPlugin = plugins.findPlugin(scriptPlugin.id) if (existingPlugin != null && existingPlugin.javaClass.getPackage().name.startsWith(DefaultPluginManager.CORE_PLUGIN_PREFIX)) { throw GradleException( String.format( "The precompiled plugin (%s) conflicts with the core plugin '%s'. Rename your plugin.\n\n%s", this.relativePath(scriptPlugin.scriptFile), scriptPlugin.id, PRECOMPILED_SCRIPT_MANUAL.consultDocumentationMessage() ) ) } } private fun Project.declareScriptPlugins(scriptPlugins: List<PrecompiledScriptPlugin>) { configure<GradlePluginDevelopmentExtension> { for (scriptPlugin in scriptPlugins) { plugins.create(scriptPlugin.id) { it.id = scriptPlugin.id it.implementationClass = scriptPlugin.implementationClass } } } } private fun Project.generatePluginAdaptersFor(scriptPlugins: List<PrecompiledScriptPlugin>, kotlinSourceDirectorySet: SourceDirectorySet) { codeGenerationTask<GenerateScriptPluginAdapters>( "plugins", "generateScriptPluginAdapters", kotlinSourceDirectorySet ) { plugins = scriptPlugins outputDirectory.set(it) } } private inline fun <reified T : Task> Project.codeGenerationTask( purpose: String, taskName: String, kotlinSourceDirectorySet: SourceDirectorySet, noinline configure: T.(Provider<Directory>) -> Unit ) = buildDir("generated-sources/kotlin-dsl-$purpose/kotlin").let { outputDir -> val task = tasks.register(taskName, T::class.java) { it.configure(outputDir) } kotlinSourceDirectorySet.srcDir(files(outputDir).builtBy(task)) task to outputDir } private fun Project.buildDir(path: String) = layout.buildDirectory.dir(path) private val Project.sourceSets get() = project.the<SourceSetContainer>()
apache-2.0
751ff59467aeca422467abbdef4ff289
36.755144
226
0.709848
4.923263
false
false
false
false
mdaniel/intellij-community
platform/script-debugger/backend/src/debugger/ScriptBase.kt
13
1422
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.openapi.util.UserDataHolderBase import com.intellij.util.Url import org.jetbrains.concurrency.Promise import org.jetbrains.debugger.sourcemap.SourceMap import kotlin.math.max abstract class ScriptBase(override val type: Script.Type, override val url: Url, line: Int, override val column: Int, override val endLine: Int, override val vm: Vm) : UserDataHolderBase(), Script { override val line: Int = max(line, 0) @SuppressWarnings("UnusedDeclaration") @Volatile private var source: Promise<String>? = null override var sourceMap: SourceMap? = null override fun toString(): String = "[url=$url, lineRange=[$line;$endLine]]" }
apache-2.0
6b77d453ee4f06e74fef802713e5fea7
35.487179
79
0.68706
4.485804
false
false
false
false
mdaniel/intellij-community
build/tasks/src/org/jetbrains/intellij/build/tasks/sign.kt
1
15688
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build.tasks import com.intellij.diagnostic.telemetry.use import com.intellij.diagnostic.telemetry.useWithScope import com.jcraft.jsch.agentproxy.AgentProxy import com.jcraft.jsch.agentproxy.AgentProxyException import com.jcraft.jsch.agentproxy.Connector import com.jcraft.jsch.agentproxy.ConnectorFactory import com.jcraft.jsch.agentproxy.sshj.AuthAgent import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import net.schmizz.keepalive.KeepAliveProvider import net.schmizz.sshj.DefaultConfig import net.schmizz.sshj.SSHClient import net.schmizz.sshj.connection.channel.Channel import net.schmizz.sshj.sftp.SFTPClient import net.schmizz.sshj.transport.verification.PromiscuousVerifier import net.schmizz.sshj.userauth.method.AuthKeyboardInteractive import net.schmizz.sshj.userauth.method.AuthMethod import net.schmizz.sshj.userauth.method.AuthPassword import net.schmizz.sshj.userauth.method.PasswordResponseProvider import net.schmizz.sshj.userauth.password.PasswordFinder import net.schmizz.sshj.userauth.password.Resource import org.apache.commons.compress.archivers.zip.Zip64Mode import org.apache.commons.compress.archivers.zip.ZipArchiveEntryPredicate import org.apache.commons.compress.archivers.zip.ZipFile import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import org.jetbrains.intellij.build.io.* import org.jetbrains.intellij.build.tracer import java.io.InputStream import java.io.OutputStream import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import java.nio.file.StandardOpenOption import java.security.SecureRandom import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import java.util.function.Consumer import java.util.logging.* import java.util.zip.Deflater import kotlin.io.path.name import kotlin.io.path.outputStream private val random by lazy { SecureRandom() } // our zip for JARs, but here we need to support file permissions - that's why apache compress is used fun prepareMacZip(macZip: Path, sitFile: Path, productJson: String, zipRoot: String) { Files.newByteChannel(macZip, StandardOpenOption.READ).use { sourceFileChannel -> ZipFile(sourceFileChannel).use { zipFile -> writeNewFile(sitFile) { targetFileChannel -> NoDuplicateZipArchiveOutputStream(targetFileChannel).use { out -> // file is used only for transfer to mac builder out.setLevel(Deflater.BEST_SPEED) out.setUseZip64(Zip64Mode.Never) // exclude existing product-info.json as a custom one will be added val productJsonZipPath = "$zipRoot/Resources/product-info.json" zipFile.copyRawEntries(out, ZipArchiveEntryPredicate { it.name != productJsonZipPath }) out.entry(productJsonZipPath, productJson.encodeToByteArray()) } } } } } // 0644 octal -> 420 decimal private const val regularFileMode = 420 // 0777 octal -> 511 decimal private const val executableFileMode = 511 fun signMacApp( host: String, user: String, password: String, codesignString: String, fullBuildNumber: String, notarize: Boolean, bundleIdentifier: String, appArchiveFile: Path, communityHome: BuildDependenciesCommunityRoot, artifactDir: Path, dmgImage: Path?, artifactBuilt: Consumer<Path>, publishAppArchive: Boolean, jetSignClient: Path ) { executeTask(host, user, password, "intellij-builds/${fullBuildNumber}") { ssh, sftp, remoteDir -> tracer.spanBuilder("upload file") .setAttribute("file", appArchiveFile.toString()) .setAttribute("remoteDir", remoteDir) .setAttribute("host", host) .use { sftp.put(NioFileSource(appArchiveFile, filePermission = regularFileMode), "$remoteDir/${appArchiveFile.fileName}") } val scriptDir = communityHome.communityRoot.resolve("platform/build-scripts/tools/mac/scripts") tracer.spanBuilder("upload scripts") .setAttribute("scriptDir", scriptDir.toString()) .setAttribute("remoteDir", remoteDir) .setAttribute("host", host) .use { sftp.put(NioFileSource(scriptDir.resolve("entitlements.xml"), filePermission = regularFileMode), "$remoteDir/entitlements.xml") @Suppress("SpellCheckingInspection") for (fileName in listOf("sign.sh", "notarize.sh", "signapp.sh", "makedmg.sh", "makedmg.py", "codesign.sh")) { sftp.put(NioFileSource(scriptDir.resolve(fileName), filePermission = executableFileMode), "$remoteDir/$fileName") } if (dmgImage != null) { sftp.put(NioFileSource(dmgImage, filePermission = regularFileMode), "$remoteDir/$fullBuildNumber.png") } sftp.put(NioFileSource(jetSignClient, filePermission = executableFileMode), "$remoteDir/${jetSignClient.name}") } val args = listOf( appArchiveFile.fileName.toString(), fullBuildNumber, user, password, codesignString, if (notarize) "yes" else "no", bundleIdentifier, publishAppArchive.toString(), "/Users/$user/$remoteDir/${jetSignClient.name}" ) val env = sequenceOf("ARTIFACTORY_URL", "SERVICE_ACCOUNT_NAME", "SERVICE_ACCOUNT_TOKEN") .map { it to System.getenv(it) } .filterNot { it.second.isNullOrEmpty() } .toList().takeIf { it.isNotEmpty() } ?.joinToString(separator = " ", postfix = " ") { "${it.first}=${it.second}" } ?: "" @Suppress("SpellCheckingInspection") tracer.spanBuilder("sign mac app").setAttribute("file", appArchiveFile.toString()).useWithScope { signFile(remoteDir = remoteDir, commandString = "$env'$remoteDir/signapp.sh' '${args.joinToString("' '")}'", file = appArchiveFile, ssh = ssh, ftpClient = sftp, artifactDir = artifactDir, artifactBuilt = artifactBuilt) if (publishAppArchive) { downloadResult(remoteFile = "$remoteDir/${appArchiveFile.fileName}", localFile = appArchiveFile, ftpClient = sftp, failedToSign = null) } } if (publishAppArchive) { artifactBuilt.accept(appArchiveFile) } if (dmgImage != null) { val fileNameWithoutExt = appArchiveFile.fileName.toString().removeSuffix(".sit") val dmgFile = artifactDir.resolve("$fileNameWithoutExt.dmg") tracer.spanBuilder("build dmg").setAttribute("file", dmgFile.toString()).useWithScope { @Suppress("SpellCheckingInspection") processFile(localFile = dmgFile, ssh = ssh, commandString = "/bin/bash -l '$remoteDir/makedmg.sh' '${fileNameWithoutExt}' '$fullBuildNumber'", artifactDir = artifactDir, artifactBuilt = artifactBuilt, taskLogClassifier = "dmg") downloadResult(remoteFile = "$remoteDir/${dmgFile.fileName}", localFile = dmgFile, ftpClient = sftp, failedToSign = null) artifactBuilt.accept(dmgFile) } } } } private fun signFile(remoteDir: String, file: Path, ssh: SSHClient, ftpClient: SFTPClient, commandString: String, artifactDir: Path, artifactBuilt: Consumer<Path>) { ftpClient.put(NioFileSource(file), "$remoteDir/${file.fileName}") processFile(localFile = file, ssh = ssh, commandString = commandString, artifactDir = artifactDir, artifactBuilt = artifactBuilt, taskLogClassifier = "sign") } private fun processFile(localFile: Path, ssh: SSHClient, commandString: String, artifactDir: Path, artifactBuilt: Consumer<Path>, taskLogClassifier: String) { val fileName = localFile.fileName.toString() val logFile = artifactDir.resolve("macos-logs").resolve("$taskLogClassifier-$fileName.log") Files.createDirectories(logFile.parent) ssh.startSession().use { session -> val command = session.exec(commandString) try { logFile.outputStream(StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING).use { logStream -> // use CompletableFuture because get will call ForkJoinPool.helpAsyncBlocker, so, other tasks in FJP will be executed while waiting CompletableFuture.allOf( runAsync { command.inputStream.writeEachLineTo(logStream, System.out, channel = command) }, runAsync { command.errorStream.writeEachLineTo(logStream, System.out, channel = command) }, ).get(6, TimeUnit.HOURS) } command.join(1, TimeUnit.MINUTES) } catch (e: Exception) { val logFileLocation = if (Files.exists(logFile)) artifactDir.relativize(logFile) else "<internal error - log file is not created>" throw RuntimeException("SSH command failed, details are available in $logFileLocation: ${e.message}", e) } finally { if (Files.exists(logFile)) { artifactBuilt.accept(logFile) } command.close() } if (command.exitStatus != 0) { throw RuntimeException("SSH command failed, details are available in ${artifactDir.relativize(logFile)}" + " (exitStatus=${command.exitStatus}, exitErrorMessage=${command.exitErrorMessage})") } } } private fun InputStream.writeEachLineTo(vararg outputStreams: OutputStream, channel: Channel) { val lineBuffer = StringBuilder() fun writeLine() { val lineBytes = lineBuffer.toString().toByteArray() outputStreams.forEach { synchronized(it) { it.write(lineBytes) } } } bufferedReader().use { reader -> while (channel.isOpen || reader.ready()) { if (reader.ready()) { val char = reader.read() .takeIf { it != -1 }?.toChar() ?.also(lineBuffer::append) val endOfLine = char == '\n' || char == '\r' || char == null if (endOfLine && lineBuffer.isNotEmpty()) { writeLine() lineBuffer.clear() } } else { Thread.sleep(100L) } } if (lineBuffer.isNotBlank()) { writeLine() } } } private fun downloadResult(remoteFile: String, localFile: Path, ftpClient: SFTPClient, failedToSign: MutableList<Path>?) { tracer.spanBuilder("download file") .setAttribute("remoteFile", remoteFile) .setAttribute("localFile", localFile.toString()) .use { span -> val localFileParent = localFile.parent val tempFile = localFileParent.resolve("${localFile.fileName}.download") Files.createDirectories(localFileParent) var attempt = 1 do { try { ftpClient.get(remoteFile, NioFileDestination(tempFile)) } catch (e: Exception) { span.addEvent("cannot download $remoteFile", Attributes.of( AttributeKey.longKey("attemptNumber"), attempt.toLong(), AttributeKey.stringKey("error"), e.toString(), AttributeKey.stringKey("remoteFile"), remoteFile, )) attempt++ if (attempt > 3) { Files.deleteIfExists(tempFile) if (failedToSign == null) { throw RuntimeException("Failed to sign file: $localFile") } else { failedToSign.add(localFile) } return } else { continue } } break } while (true) if (attempt != 1) { span.addEvent("file was downloaded", Attributes.of( AttributeKey.longKey("attemptNumber"), attempt.toLong(), )) } Files.move(tempFile, localFile, StandardCopyOption.REPLACE_EXISTING) } } private val initLog by lazy { val root = Logger.getLogger("") if (root.handlers.isEmpty()) { root.level = Level.INFO root.addHandler(ConsoleHandler().also { it.formatter = object : Formatter() { override fun format(record: LogRecord): String { return record.message + System.lineSeparator() } } }) } } private fun generateRemoteDirName(remoteDirPrefix: String): String { val currentDateTimeString = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME).replace(':', '-') return "$remoteDirPrefix-$currentDateTimeString-${java.lang.Long.toUnsignedString(random.nextLong(), Character.MAX_RADIX)}" } @Throws(java.lang.Exception::class) private fun AgentProxy.getAuthMethods(): List<AuthMethod> { val identities = identities System.getLogger("org.jetbrains.intellij.build.tasks.Sign") .info("SSH-Agent identities: ${identities.joinToString { String(it.comment, StandardCharsets.UTF_8) }}") return identities.map { AuthAgent(this, it) } } private fun getAgentConnector(): Connector? { try { return ConnectorFactory.getDefault().createConnector() } catch (ignored: AgentProxyException) { System.getLogger("org.jetbrains.intellij.build.tasks.Sign") .warn("SSH-Agent connector creation failed: ${ignored.message}") } return null } private inline fun executeTask(host: String, user: String, password: String, remoteDirPrefix: String, task: (ssh: SSHClient, sftp: SFTPClient, remoteDir: String) -> Unit) { initLog val config = DefaultConfig() config.keepAliveProvider = KeepAliveProvider.KEEP_ALIVE SSHClient(config).use { ssh -> ssh.addHostKeyVerifier(PromiscuousVerifier()) ssh.connect(host) val passwordFinder = object : PasswordFinder { override fun reqPassword(resource: Resource<*>?) = password.toCharArray().clone() override fun shouldRetry(resource: Resource<*>?) = false } val authMethods: List<AuthMethod> = (getAgentConnector()?.let { AgentProxy(it) }?.getAuthMethods() ?: emptyList()) + listOf(AuthPassword(passwordFinder), AuthKeyboardInteractive(PasswordResponseProvider(passwordFinder))) ssh.auth(user, authMethods) ssh.newSFTPClient().use { sftp -> val remoteDir = generateRemoteDirName(remoteDirPrefix) sftp.mkdir(remoteDir) try { task(ssh, sftp, remoteDir) } finally { // as odd as it is, session can only be used once // https://stackoverflow.com/a/23467751 removeDir(ssh, remoteDir) } } } } private fun removeDir(ssh: SSHClient, remoteDir: String) { tracer.spanBuilder("remove remote dir").setAttribute("remoteDir", remoteDir).use { ssh.startSession().use { session -> val command = session.exec("rm -rf '$remoteDir'") command.join(30, TimeUnit.SECONDS) // must be called before checking exit code command.close() if (command.exitStatus != 0) { throw RuntimeException("cannot remove remote directory (exitStatus=${command.exitStatus}, " + "exitErrorMessage=${command.exitErrorMessage})") } } } }
apache-2.0
c250bd94ac684e4865207a0f95349110
37.080097
139
0.653111
4.489983
false
false
false
false
ingokegel/intellij-community
plugins/gradle/java/src/service/project/GradleDependencyCollector.kt
1
2495
// 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.gradle.service.project import com.intellij.ide.plugins.DependencyCollector import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.Key import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType import com.intellij.openapi.externalSystem.service.project.ProjectDataManager import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.project.Project import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginAdvertiserService import kotlinx.coroutines.launch import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData import org.jetbrains.plugins.gradle.util.GradleConstants internal class GradleDependencyCollector : DependencyCollector { override fun collectDependencies(project: Project): Set<String> { return ProjectDataManager.getInstance() .getExternalProjectsData(project, GradleConstants.SYSTEM_ID) .asSequence() .mapNotNull { it.externalProjectStructure } .flatMap { projectStructure -> projectStructure.getChildrenSequence(ProjectKeys.MODULE) .flatMap { it.getChildrenSequence(GradleSourceSetData.KEY) } .flatMap { it.getChildrenSequence(ProjectKeys.LIBRARY_DEPENDENCY) } }.map { it.data.target } .mapNotNull { libraryData -> val groupId = libraryData.groupId val artifactId = libraryData.artifactId if (groupId != null && artifactId != null) "$groupId:$artifactId" else null }.toSet() } private fun <T> DataNode<*>.getChildrenSequence(key: Key<T>) = ExternalSystemApiUtil.getChildren(this, key).asSequence() } internal class GradleDependencyUpdater : ExternalSystemTaskNotificationListenerAdapter() { override fun onEnd(id: ExternalSystemTaskId) { if (id.projectSystemId == GradleConstants.SYSTEM_ID && id.type == ExternalSystemTaskType.RESOLVE_PROJECT) { id.findProject()?.let { project -> project.coroutineScope.launch { PluginAdvertiserService.getInstance().rescanDependencies(project) } } } } }
apache-2.0
2c1948a2a0c1be9f93e3d95a4260e033
46.075472
122
0.779158
4.960239
false
false
false
false
mdaniel/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/list/search/PersistingReviewListSearchHistoryModel.kt
2
1019
// 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.collaboration.ui.codereview.list.search import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job abstract class PersistingReviewListSearchHistoryModel<S : ReviewListSearchValue>( private val scope: CoroutineScope, private val historySizeLimit: Int = 10 ) : ReviewListSearchHistoryModel<S> { override fun getHistory(): List<S> = persistentHistory protected abstract var persistentHistory: List<S> private var delayedHistoryAdditionJob: Job? = null override fun add(search: S) { persistentHistory = persistentHistory.toMutableList().apply { remove(search) add(search) }.trim(historySizeLimit) } companion object { private fun <E> List<E>.trim(sizeLimit: Int): List<E> { val result = this.toMutableList() while (result.size > sizeLimit) { result.removeFirst() } return result } } }
apache-2.0
3dba62644a7730bce8d06bb11fc8f30b
29
120
0.729146
4.281513
false
false
false
false
FlexSeries/FlexLib
src/main/kotlin/me/st28/flexseries/flexlib/message/MessageModule.kt
1
3778
/** * Copyright 2016 Stealth2800 <http://stealthyone.com/> * Copyright 2016 Contributors <https://github.com/FlexSeries> * * 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 me.st28.flexseries.flexlib.message import me.st28.flexseries.flexlib.logging.LogHelper import me.st28.flexseries.flexlib.plugin.FlexModule import me.st28.flexseries.flexlib.plugin.FlexPlugin import me.st28.flexseries.flexlib.plugin.storage.flatfile.YamlFileManager import org.apache.commons.lang.StringEscapeUtils import java.io.File import java.util.HashMap import java.util.regex.Pattern class MessageModule<out T : FlexPlugin>(plugin: T) : FlexModule<T>(plugin, "messages", "Manages a plugin's messages") { companion object { val PATTERN_VARIABLE: Pattern = Pattern.compile("\\{([0-9]+)\\}") val PATTERN_VARIABLE_REVERSE: Pattern = Pattern.compile("%([0-9]+)\\\$s") fun setupPatternReplace(input: String): String { return PATTERN_VARIABLE.matcher(input).replaceAll("%$1\\\$s") } fun reversePatternReplace(input: String): String { return PATTERN_VARIABLE_REVERSE.matcher(input).replaceAll("{$1}") } } private val messages: MutableMap<String, String> = HashMap() private val tags: MutableMap<String, String> = HashMap() override fun handleReload() { messages.clear() val messageFile = YamlFileManager(plugin.dataFolder.path + File.separator + "messages.yml") if (messageFile.isEmpty()) { plugin.saveResource("messages.yml", true) messageFile.reload() } for ((key, value) in messageFile.config.getValues(true)) { if (value is String) { val curValue = StringEscapeUtils.unescapeJava(value) // Check if key is a tag if (key == "tag") { tags.put("", curValue) continue } else if (key.endsWith(".tag")) { tags.put(key.replace(".tag", ""), curValue) continue } messages.put(key, curValue) } } LogHelper.info(this, "Loaded ${messages.size} message(s) and ${tags.size} tag(s)") } private fun getMessageTag(name: String): String { var tag: String? var curKey = name var lastIndex: Int do { lastIndex = curKey.lastIndexOf(".") // Check if the tag exists tag = tags[curKey] // Update curKey if (lastIndex != -1) { curKey = curKey.substring(0, lastIndex) } } while (lastIndex != -1) // Try base tag, otherwise return empty string return tag ?: tags[""] ?: "" } fun getMessage(name: String, vararg replacements: Any?): Message { val message: String if (messages.containsKey(name)) { val masterManager = FlexPlugin.getGlobalModule(MasterMessageModule::class) message = reversePatternReplace(masterManager.processMessage(setupPatternReplace(messages[name]!!))) } else { message = name } return Message(message.replace("{TAG}", getMessageTag(name)), *replacements) } }
apache-2.0
6cb38cee45ecba047d8a54b81ab0417c
33.669725
119
0.621493
4.352535
false
false
false
false
Turbo87/intellij-emberjs
src/main/kotlin/com/emberjs/navigation/DelegatingNavigationItem.kt
1
687
package com.emberjs.navigation import com.intellij.navigation.ItemPresentation import com.intellij.navigation.NavigationItem class DelegatingNavigationItem(val base: NavigationItem) : NavigationItem { private var presentation: ItemPresentation? = null fun withPresentation(presentation: ItemPresentation) = apply { this.presentation = presentation } override fun getName() = base.name override fun getPresentation() = presentation ?: base.presentation override fun navigate(requestFocus: Boolean) = base.navigate(requestFocus) override fun canNavigate() = base.canNavigate() override fun canNavigateToSource() = base.canNavigateToSource() }
apache-2.0
197fb4756e38fe8840cca06c31bbc9ea
33.35
78
0.770015
5.409449
false
false
false
false
icela/FriceEngine
src/org/frice/util/media/AudioPlayer.kt
1
1519
package org.frice.util.media import org.frice.util.message.FLog import org.frice.util.unless import java.io.Closeable import java.io.File import javax.sound.sampled.* /** * From https://github.com/ice1000/Dekoder * * Created by ice1000 on 2016/8/16. * @author ice1000 * @since v0.3.1 * @see org.frice.util.media.getPlayer */ open class AudioPlayer internal constructor(val file: File) : Thread(), Closeable { protected var audioInputStream: AudioInputStream private var format: AudioFormat protected var line: SourceDataLine var stopped = false init { audioInputStream = AudioSystem.getAudioInputStream(file) format = audioInputStream.format if (format.encoding != AudioFormat.Encoding.PCM_SIGNED) { format = AudioFormat( AudioFormat.Encoding.PCM_SIGNED, format.sampleRate, 16, format.channels, format.channels shl 1, format.frameRate, false) audioInputStream = AudioSystem.getAudioInputStream(format, audioInputStream) } line = `{-# getLine #-}`(format) } protected fun openLine() { try { unless(line.isOpen) { line.open() line.start() } } catch (ignored: IllegalStateException) { FLog.e("""There're some issues with the audio mixer in your JRE. Please use `org.frice.util.media.MediaManager instead of AudioManager if you see this message.""") } } /** * It's the safest way to stop playing. * @since v1.7.7 */ fun stopPlaying() { stopped = true } override fun close() { line.close() audioInputStream.close() } }
agpl-3.0
5a0bda262aeb9f0266619c8081999f55
22.734375
98
0.707702
3.421171
false
false
false
false
walleth/kethereum
bip32/src/main/kotlin/org/kethereum/bip32/BIP32.kt
1
4175
@file:JvmName("BIP32") package org.kethereum.bip32 import org.kethereum.bip32.model.CHAINCODE_SIZE import org.kethereum.bip32.model.ExtendedKey import org.kethereum.bip32.model.Seed import org.kethereum.bip44.BIP44 import org.kethereum.bip44.BIP44Element import org.kethereum.crypto.* import org.kethereum.extensions.toBytesPadded import org.kethereum.hashes.ripemd160 import org.kethereum.hashes.sha256 import org.kethereum.model.ECKeyPair import org.kethereum.model.PRIVATE_KEY_SIZE import org.kethereum.model.PrivateKey import java.math.BigInteger import java.nio.ByteBuffer import java.nio.ByteOrder import java.security.InvalidKeyException import java.security.KeyException import java.security.NoSuchAlgorithmException import java.security.NoSuchProviderException fun Seed.toKey(pathString: String, testnet: Boolean = false) = BIP44(pathString).path .fold(toExtendedKey(testnet = testnet)) { current, bip44Element -> current.generateChildKey(bip44Element) } /** * Gets an [Int] representation of public key hash * @return an Int built from the first 4 bytes of the result of hash160 over the compressed public key */ private fun ECKeyPair.computeFingerPrint(): Int { val pubKeyHash = getCompressedPublicKey() .sha256() .ripemd160() var fingerprint = 0 for (i in 0..3) { fingerprint = fingerprint shl 8 fingerprint = fingerprint or (pubKeyHash[i].toInt() and 0xff) } return fingerprint } fun ExtendedKey.generateChildKey(element: BIP44Element): ExtendedKey { try { require(!(element.hardened && keyPair.privateKey.key == BigInteger.ZERO)) { "need private key for private generation using hardened paths" } val mac = CryptoAPI.hmac.init(chainCode) val extended: ByteArray val pub = keyPair.getCompressedPublicKey() if (element.hardened) { val privateKeyPaddedBytes = keyPair.privateKey.key.toBytesPadded(PRIVATE_KEY_SIZE) extended = ByteBuffer .allocate(privateKeyPaddedBytes.size + 5) .order(ByteOrder.BIG_ENDIAN) .put(0) .put(privateKeyPaddedBytes) .putInt(element.numberWithHardeningFlag) .array() } else { //non-hardened extended = ByteBuffer .allocate(pub.size + 4) .order(ByteOrder.BIG_ENDIAN) .put(pub) .putInt(element.numberWithHardeningFlag) .array() } val lr = mac.generate(extended) val l = lr.copyOfRange(0, PRIVATE_KEY_SIZE) val r = lr.copyOfRange(PRIVATE_KEY_SIZE, PRIVATE_KEY_SIZE + CHAINCODE_SIZE) val m = BigInteger(1, l) if (m >= CURVE.n) { throw KeyException("Child key derivation resulted in a key with higher modulus. Suggest deriving the next increment.") } return if (keyPair.privateKey.key != BigInteger.ZERO) { val k = m.add(keyPair.privateKey.key).mod(CURVE.n) if (k == BigInteger.ZERO) { throw KeyException("Child key derivation resulted in zeros. Suggest deriving the next increment.") } ExtendedKey(PrivateKey(k).toECKeyPair(), r, (depth + 1).toByte(), keyPair.computeFingerPrint(), element.numberWithHardeningFlag, versionBytes) } else { val q = CURVE.g.mul(m).add(CURVE.decodePoint(pub)).normalize() if (q.isInfinity()) { throw KeyException("Child key derivation resulted in zeros. Suggest deriving the next increment.") } val point = CURVE.createPoint(q.x, q.y) ExtendedKey(ECKeyPair(PrivateKey(BigInteger.ZERO), point.toPublicKey()), r, (depth + 1).toByte(), keyPair.computeFingerPrint(), element.numberWithHardeningFlag, versionBytes) } } catch (e: NoSuchAlgorithmException) { throw KeyException(e) } catch (e: NoSuchProviderException) { throw KeyException(e) } catch (e: InvalidKeyException) { throw KeyException(e) } }
mit
e6f61489e6816090683c3b2c8c38dfe7
37.657407
186
0.651497
4.225709
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/stories/viewer/reply/reaction/OnReactionSentView.kt
2
1546
package org.thoughtcrime.securesms.stories.viewer.reply.reaction import android.content.Context import android.util.AttributeSet import android.widget.FrameLayout import androidx.constraintlayout.motion.widget.MotionLayout import androidx.constraintlayout.motion.widget.TransitionAdapter import androidx.core.view.doOnNextLayout import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.emoji.EmojiImageView class OnReactionSentView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : FrameLayout(context, attrs) { var callback: Callback? = null init { inflate(context, R.layout.on_reaction_sent_view, this) } private val motionLayout: MotionLayout = findViewById(R.id.motion_layout) init { motionLayout.addTransitionListener(object : TransitionAdapter() { override fun onTransitionCompleted(p0: MotionLayout?, p1: Int) { motionLayout.progress = 0f callback?.onFinished() } }) } fun playForEmoji(emoji: CharSequence) { motionLayout.progress = 0f listOf( R.id.emoji_1, R.id.emoji_2, R.id.emoji_3, R.id.emoji_4, R.id.emoji_5, R.id.emoji_6, R.id.emoji_7, R.id.emoji_8, R.id.emoji_9, R.id.emoji_10, R.id.emoji_11, ).forEach { findViewById<EmojiImageView>(it).setImageEmoji(emoji) } motionLayout.requestLayout() motionLayout.doOnNextLayout { motionLayout.transitionToEnd() } } interface Callback { fun onFinished() } }
gpl-3.0
13e6d49bcaf8d72ba2c478545dc4043c
23.935484
75
0.705045
3.845771
false
false
false
false
AntonovAlexander/activecore
hwast/src/hw_frac.kt
1
5545
/* * hw_frac.kt * * Created on: 05.06.2019 * Author: Alexander Antonov <[email protected]> * License: See LICENSE file for details */ package hwast abstract class hw_frac () { abstract fun GetWidth() : Int } class hw_frac_C (val index : hw_imm) : hw_frac() { constructor(index : Int) : this(hw_imm(index.toString())) override fun GetWidth() : Int { return 1 } } class hw_frac_V (val index : hw_var) : hw_frac() { override fun GetWidth() : Int { return 1 } } class hw_frac_CC (val msb : hw_imm, val lsb : hw_imm) : hw_frac() { constructor(msb : Int, lsb : Int) : this(hw_imm(msb.toString()), hw_imm(lsb.toString())) override fun GetWidth() : Int { if (msb.toInt() > lsb.toInt()) return (msb.toInt() - lsb.toInt()) else return (lsb.toInt() - msb.toInt()) } } class hw_frac_CV (val msb : hw_imm, val lsb : hw_var) : hw_frac() { constructor(msb : Int, lsb : hw_var) : this(hw_imm(msb.toString()), lsb) override fun GetWidth() : Int { return 0 } } class hw_frac_VC (val msb : hw_var, val lsb : hw_imm) : hw_frac() { constructor(msb : hw_var, lsb : Int) : this(msb, hw_imm(lsb.toString())) override fun GetWidth() : Int { return 0 } } class hw_frac_VV (val msb : hw_var, val lsb : hw_var) : hw_frac() { override fun GetWidth() : Int { return 0 } } class hw_frac_SubStruct (val substruct_name : String) : hw_frac() { var subStructIndex : Int = 0 var src_struct = DUMMY_STRUCT override fun GetWidth() : Int { return 0 } } // container for variable fractures to take class hw_fracs() : ArrayList<hw_frac>() { constructor(index : Int) : this() { this.add(hw_frac_C(index)) } constructor(index : hw_var) : this() { this.add(hw_frac_V(index)) } constructor(msb : Int, lsb : Int) : this() { this.add(hw_frac_CC(msb, lsb)) } constructor(msb : Int, lsb : hw_var) : this() { this.add(hw_frac_CV(msb, lsb)) } constructor(msb : hw_var, lsb : Int) : this() { this.add(hw_frac_VC(msb, lsb)) } constructor(msb : hw_var, lsb : hw_var) : this() { this.add(hw_frac_VV(msb, lsb)) } constructor(substruct_name : String) : this() { this.add(hw_frac_SubStruct(substruct_name)) } constructor(vararg fractions: hw_frac) : this() { for (fraction in fractions) { this.add(fraction) } } fun add(new_elem : Int) { add(hw_frac_C(new_elem)) } fun add(new_elem : hw_imm) { add(hw_frac_C(new_elem)) } fun add(new_elem : hw_var) { add(hw_frac_V(new_elem)) } fun add(new_elem : hw_param) { if (new_elem is hw_imm) add(hw_frac_C(new_elem)) else if (new_elem is hw_var) add(hw_frac_V(new_elem)) else ERROR("frac error") } fun add(msb : hw_param, lsb : hw_param) { if (msb is hw_imm) { if (lsb is hw_imm) add(hw_frac_CC(msb, lsb)) else if (lsb is hw_var) add(hw_frac_CV(msb, lsb)) else ERROR("frac error") } else if (msb is hw_var) { if (lsb is hw_imm) add(hw_frac_VC(msb, lsb)) else if (lsb is hw_var) add(hw_frac_VV(msb, lsb)) else ERROR("frac error") } else { ERROR("frac error") } } fun add(msb : hw_param, lsb : Int) { add(msb, hw_imm(lsb)) } fun add(msb : Int, lsb : hw_param) { add(hw_imm(msb), lsb) } fun add(msb : Int, lsb : Int) { add(hw_imm(msb), hw_imm(lsb)) } fun add(new_elem : String) { add(hw_frac_SubStruct(new_elem)) } fun FillSubStructs(dst: hw_var) { var dst_struct_ptr = dst.vartype.src_struct for (fraction in this) { if (fraction is hw_frac_SubStruct) { //println("Substruct found!") if (dst_struct_ptr != DUMMY_STRUCT) { var substr_found = false var SUBSTR_INDEX = 0 for (structvar in dst_struct_ptr) { //println("structvar: " + structvar.name) if (structvar.name == fraction.substruct_name) { //println("src_struct: " + dst_struct_ptr.name) //println("subStructIndex: " + SUBSTR_INDEX) fraction.src_struct = dst_struct_ptr fraction.subStructIndex = SUBSTR_INDEX if (structvar.vartype.DataType == DATA_TYPE.STRUCTURED) { dst_struct_ptr = structvar.vartype.src_struct } else { dst_struct_ptr = DUMMY_STRUCT } substr_found = true break } SUBSTR_INDEX += 1 } if (!substr_found){ MSG("Available substructs in variable: " + dst.name) for (structvar in dst_struct_ptr) MSG("substruct: " + structvar.name) ERROR("substruct " + (fraction as hw_frac_SubStruct).substruct_name + " not found!") } } else ERROR("substruct " + (fraction as hw_frac_SubStruct).substruct_name + " request for dst " + dst.name + " is inconsistent!") } } } }
apache-2.0
12d89ea8e6c15a5b258c16ca342b816d
27.290816
146
0.506583
3.498423
false
false
false
false
dimagi/commcare-android
app/src/org/commcare/location/CommCareFusedLocationController.kt
1
2293
package org.commcare.location import android.content.Context import android.location.Location import com.google.android.gms.location.* /** * @author $|-|!˅@M */ class CommCareFusedLocationController(private var mContext: Context?, private var mListener: CommCareLocationListener?): CommCareLocationController { private val mFusedLocationClient = LocationServices.getFusedLocationProviderClient(mContext!!) private val settingsClient = LocationServices.getSettingsClient(mContext!!) private val mLocationRequest = LocationRequest.create().apply { priority = LocationRequest.PRIORITY_HIGH_ACCURACY interval = LOCATION_UPDATE_INTERVAL } private var mCurrentLocation: Location? = null private val mLocationCallback = object: LocationCallback() { override fun onLocationResult(result: LocationResult?) { result ?: return mCurrentLocation = result.lastLocation mListener?.onLocationResult(mCurrentLocation!!) } } companion object { const val LOCATION_UPDATE_INTERVAL = 5000L } private fun requestUpdates() { if (isLocationPermissionGranted(mContext)) { mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null) } else { mListener?.missingPermissions() } } override fun start() { val locationSettingsRequest = LocationSettingsRequest.Builder() .addLocationRequest(mLocationRequest) .setAlwaysShow(true) .build() settingsClient.checkLocationSettings(locationSettingsRequest) .addOnSuccessListener { mListener?.onLocationRequestStart() requestUpdates() } .addOnFailureListener { exception -> mListener?.onLocationRequestFailure(CommCareLocationListener.Failure.ApiException(exception)) } } override fun stop() { mFusedLocationClient.removeLocationUpdates(mLocationCallback) } override fun getLocation(): Location? { return mCurrentLocation } override fun destroy() { mContext = null mListener = null } }
apache-2.0
da69454d6c3dcd9e51c996a28637126f
33.223881
117
0.654887
5.892031
false
false
false
false