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
soniccat/android-taskmanager
authorization/src/main/java/com/example/alexeyglushkov/authorization/AuthorizationActivity.kt
1
2969
package com.example.alexeyglushkov.authorization import android.os.Bundle import android.webkit.WebView import android.webkit.WebViewClient import androidx.appcompat.app.AppCompatActivity import com.example.alexeyglushkov.tools.CancelError import io.reactivex.Single /** * Created by alexeyglushkov on 24.10.15. */ class AuthorizationActivity : AppCompatActivity() /*implements OAuthWebClient*/ { private var webView: WebView? = null private var isHandled = false private val loadUrl: String? get() = intent?.extras?.getString(LOAD_URL) private val callbackUrl: String? get() = intent?.extras?.getString(CALLBACK_URL) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_authorization) webView = findViewById<WebView>(R.id.web_view).apply { bindWebView(this) } loadUrl?.let { runOnUiThread { webView?.loadUrl(it) } } } private fun bindWebView(webView: WebView) { webView.getSettings().javaScriptEnabled = true webView.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { callbackUrl?.let { if (url.startsWith(it)) { AuthActivityProxy.finish(url, null) if (!isHandled) { isHandled = true finish() } return true } } return super.shouldOverrideUrlLoading(view, url) } override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) { super.onReceivedError(view, errorCode, description, failingUrl) val error = Exception("AuthorizationActivity webView error $errorCode $description") if (!isHandled) { AuthActivityProxy.finish(null, error) isHandled = true finish() } } } } override fun onDestroy() { super.onDestroy() webView = null } override fun finish() { if (!isHandled) { AuthActivityProxy.finish(null, CancelError()) isHandled = true } webView!!.webViewClient = null super.finish() if (AuthActivityProxy.getCurrentActivity() === this) { AuthActivityProxy.setCurrentActivity(null) } } // fun loadUrl(url: String?): String { // runOnUiThread { webView?.loadUrl(url) } // return AuthActivityProxy.authResult() // } companion object { private const val TAG = "AuthorizationActivity" const val LOAD_URL = "LOAD_URL" const val CALLBACK_URL = "CALLBACK_URL" } }
mit
537e86f0230adef721cf75e81f67cca3
30.935484
114
0.583025
5.172474
false
false
false
false
arturbosch/detekt
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/DetektResult.kt
1
1229
package io.gitlab.arturbosch.detekt.core import io.gitlab.arturbosch.detekt.api.Detektion import io.gitlab.arturbosch.detekt.api.Finding import io.gitlab.arturbosch.detekt.api.Notification import io.gitlab.arturbosch.detekt.api.ProjectMetric import io.gitlab.arturbosch.detekt.api.RuleSetId import org.jetbrains.kotlin.com.intellij.openapi.util.Key import org.jetbrains.kotlin.com.intellij.util.keyFMap.KeyFMap @Suppress("DataClassShouldBeImmutable") data class DetektResult(override val findings: Map<RuleSetId, List<Finding>>) : Detektion { private val _notifications = ArrayList<Notification>() override val notifications: Collection<Notification> = _notifications private val _metrics = ArrayList<ProjectMetric>() override val metrics: Collection<ProjectMetric> = _metrics private var userData = KeyFMap.EMPTY_MAP override fun add(projectMetric: ProjectMetric) { _metrics.add(projectMetric) } override fun add(notification: Notification) { _notifications.add(notification) } override fun <V> getData(key: Key<V>): V? = userData.get(key) override fun <V> addData(key: Key<V>, value: V) { userData = userData.plus(key, requireNotNull(value)) } }
apache-2.0
cdfe029ad00de8150b034604f5393846
34.114286
91
0.752644
4.01634
false
false
false
false
arturbosch/detekt
detekt-rules-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/UnnecessaryFilter.kt
1
3977
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.psi.unpackFunctionLiteral import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull /** * Unnecessary filters add complexity to the code and accomplish nothing. They should be removed. * * <noncompliant> * val x = listOf(1, 2, 3) * .filter { it > 1 } * .count() * * val x = listOf(1, 2, 3) * .filter { it > 1 } * .isEmpty() * </noncompliant> * * <compliant> * val x = listOf(1, 2, 3) * .count { it > 2 } * } * * val x = listOf(1, 2, 3) * .none { it > 1 } * </compliant> * */ @RequiresTypeResolution class UnnecessaryFilter(config: Config = Config.empty) : Rule(config) { override val issue: Issue = Issue( "UnnecessaryFilter", Severity.Style, "filter() with other collection operations may be simplified.", Debt.FIVE_MINS ) @Suppress("ReturnCount") override fun visitCallExpression(expression: KtCallExpression) { super.visitCallExpression(expression) if (bindingContext == BindingContext.EMPTY) return if (!expression.isCalling(filterFqNames)) return val lambdaArgumentText = expression.lambda()?.text ?: return val qualifiedOrCall = expression.getQualifiedExpressionForSelectorOrThis() val nextCall = qualifiedOrCall.getQualifiedExpressionForReceiver()?.selectorExpression ?: return secondCalls.forEach { if (nextCall.isCalling(it.fqName)) { val message = "'${expression.text}' can be replaced by '${it.correctOperator} $lambdaArgumentText'" report(CodeSmell(issue, Entity.from(expression), message)) } } } private fun KtCallExpression.lambda(): KtLambdaExpression? { val argument = lambdaArguments.singleOrNull() ?: valueArguments.singleOrNull() return argument?.getArgumentExpression()?.unpackFunctionLiteral() } private fun KtExpression.isCalling(fqNames: List<FqName>): Boolean { val calleeText = (this as? KtCallExpression)?.calleeExpression?.text ?: this.text val targetFqNames = fqNames.filter { it.shortName().asString() == calleeText } if (targetFqNames.isEmpty()) return false return getResolvedCall(bindingContext)?.resultingDescriptor?.fqNameOrNull() in targetFqNames } private fun KtExpression.isCalling(fqName: FqName) = isCalling(listOf(fqName)) private data class SecondCall(val fqName: FqName, val correctOperator: String = fqName.shortName().asString()) companion object { private val filterFqNames = listOf( FqName("kotlin.collections.filter"), FqName("kotlin.sequences.filter"), ) private val secondCalls = listOf( SecondCall(FqName("kotlin.collections.List.size")), SecondCall(FqName("kotlin.collections.List.isEmpty"), "any"), SecondCall(FqName("kotlin.collections.isNotEmpty"), "none"), SecondCall(FqName("kotlin.collections.count")), SecondCall(FqName("kotlin.sequences.count")), ) } }
apache-2.0
690fd292388f209de42b67747a9ba983
37.240385
115
0.7043
4.550343
false
false
false
false
arturbosch/detekt
detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/MaxLineLengthSpec.kt
1
9089
package io.gitlab.arturbosch.detekt.rules.style import io.github.detekt.test.utils.compileContentForTest import io.github.detekt.test.utils.compileForTest import io.gitlab.arturbosch.detekt.api.SourceLocation import io.gitlab.arturbosch.detekt.rules.Case import io.gitlab.arturbosch.detekt.test.TestConfig import io.gitlab.arturbosch.detekt.test.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe private const val MAX_LINE_LENGTH = "maxLineLength" private const val EXCLUDE_PACKAGE_STATEMENTS = "excludePackageStatements" private const val EXCLUDE_IMPORT_STATEMENTS = "excludeImportStatements" private const val EXCLUDE_COMMENT_STATEMENTS = "excludeCommentStatements" class MaxLineLengthSpec : Spek({ describe("MaxLineLength rule") { context("a kt file with some long lines") { val file by memoized { compileForTest(Case.MaxLineLength.path()) } val lines by memoized { file.text.splitToSequence("\n") } val fileContent by memoized { KtFileContent(file, lines) } it("should report no errors when maxLineLength is set to 200") { val rule = MaxLineLength(TestConfig(mapOf(MAX_LINE_LENGTH to "200"))) rule.visit(fileContent) assertThat(rule.findings).isEmpty() } it("should report all errors with default maxLineLength") { val rule = MaxLineLength() rule.visit(fileContent) assertThat(rule.findings).hasSize(6) } } context("a kt file with long but suppressed lines") { val file by memoized { compileForTest(Case.MaxLineLengthSuppressed.path()) } val lines by memoized { file.text.splitToSequence("\n") } val fileContent by memoized { KtFileContent(file, lines) } it("should not report as lines are suppressed") { val rule = MaxLineLength() rule.visit(fileContent) assertThat(rule.findings).isEmpty() } } context("a kt file with a long package name and long import statements") { val code = """ package anIncrediblyLongAndComplexPackageNameThatProbablyShouldBeMuchShorterButForTheSakeOfTheTestItsNot import anIncrediblyLongAndComplexImportNameThatProbablyShouldBeMuchShorterButForTheSakeOfTheTestItsNot class Test { } """ val file by memoized { compileContentForTest(code) } val lines by memoized { file.text.splitToSequence("\n") } val fileContent by memoized { KtFileContent(file, lines) } it("should not report the package statement and import statements by default") { val rule = MaxLineLength( TestConfig( mapOf( MAX_LINE_LENGTH to "60" ) ) ) rule.visit(fileContent) assertThat(rule.findings).isEmpty() } it("should report the package statement and import statements if they're enabled") { val rule = MaxLineLength( TestConfig( mapOf( MAX_LINE_LENGTH to "60", EXCLUDE_PACKAGE_STATEMENTS to "false", EXCLUDE_IMPORT_STATEMENTS to "false" ) ) ) rule.visit(fileContent) assertThat(rule.findings).hasSize(2) } it("should not report anything if both package and import statements are disabled") { val rule = MaxLineLength( TestConfig( mapOf( MAX_LINE_LENGTH to "60", EXCLUDE_PACKAGE_STATEMENTS to "true", EXCLUDE_IMPORT_STATEMENTS to "true" ) ) ) rule.visit(fileContent) assertThat(rule.findings).isEmpty() } } context("a kt file with a long package name, long import statements, a long line and long comments") { val file by memoized { compileForTest(Case.MaxLineLengthWithLongComments.path()) } val lines by memoized { file.text.splitToSequence("\n") } val fileContent by memoized { KtFileContent(file, lines) } it("should report the package statement, import statements, line and comments by default") { val rule = MaxLineLength( TestConfig( mapOf( MAX_LINE_LENGTH to "60" ) ) ) rule.visit(fileContent) assertThat(rule.findings).hasSize(8) } it("should report the package statement, import statements, line and comments if they're enabled") { val rule = MaxLineLength( TestConfig( mapOf( MAX_LINE_LENGTH to "60", EXCLUDE_PACKAGE_STATEMENTS to "false", EXCLUDE_IMPORT_STATEMENTS to "false", EXCLUDE_COMMENT_STATEMENTS to "false" ) ) ) rule.visit(fileContent) assertThat(rule.findings).hasSize(8) } it("should not report comments if they're disabled") { val rule = MaxLineLength( TestConfig( mapOf( MAX_LINE_LENGTH to "60", EXCLUDE_COMMENT_STATEMENTS to "true" ) ) ) rule.visit(fileContent) assertThat(rule.findings).hasSize(5) } } context("a kt file with a long package name, long import statements and a long line") { val code = """ package anIncrediblyLongAndComplexPackageNameThatProbablyShouldBeMuchShorterButForTheSakeOfTheTestItsNot import anIncrediblyLongAndComplexImportNameThatProbablyShouldBeMuchShorterButForTheSakeOfTheTestItsNot class Test { fun anIncrediblyLongAndComplexMethodNameThatProbablyShouldBeMuchShorterButForTheSakeOfTheTestItsNot() {} } """.trim() val file by memoized { compileContentForTest(code) } val lines by memoized { file.text.splitToSequence("\n") } val fileContent by memoized { KtFileContent(file, lines) } it("should only the function line by default") { val rule = MaxLineLength( TestConfig( mapOf( MAX_LINE_LENGTH to "60" ) ) ) rule.visit(fileContent) assertThat(rule.findings).hasSize(1) } it("should report the package statement, import statements and line if they're not excluded") { val rule = MaxLineLength( TestConfig( mapOf( MAX_LINE_LENGTH to "60", EXCLUDE_PACKAGE_STATEMENTS to "false", EXCLUDE_IMPORT_STATEMENTS to "false" ) ) ) rule.visit(fileContent) assertThat(rule.findings).hasSize(3) } it("should report only method if both package and import statements are disabled") { val rule = MaxLineLength( TestConfig( mapOf( MAX_LINE_LENGTH to "60", EXCLUDE_PACKAGE_STATEMENTS to "true", EXCLUDE_IMPORT_STATEMENTS to "true" ) ) ) rule.visit(fileContent) assertThat(rule.findings).hasSize(1) } it("should report correct line and column for function with excessive length") { val rule = MaxLineLength( TestConfig( mapOf( MAX_LINE_LENGTH to "60", EXCLUDE_PACKAGE_STATEMENTS to "true", EXCLUDE_IMPORT_STATEMENTS to "true" ) ) ) rule.visit(fileContent) assertThat(rule.findings).hasSize(1) assertThat(rule.findings).hasSourceLocations(SourceLocation(6, 17)) } } } })
apache-2.0
f937457225311ce7827a577e41e353a6
37.029289
120
0.516558
5.756175
false
true
false
false
wiltonlazary/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/ir/Ir.kt
1
28275
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.backend.konan.ir import org.jetbrains.kotlin.backend.common.COROUTINE_SUSPENDED_NAME import org.jetbrains.kotlin.backend.common.ir.Ir import org.jetbrains.kotlin.backend.common.ir.Symbols import org.jetbrains.kotlin.backend.konan.* import org.jetbrains.kotlin.backend.konan.descriptors.kotlinNativeInternal import org.jetbrains.kotlin.backend.konan.llvm.findMainEntryPoint import org.jetbrains.kotlin.backend.konan.lower.TestProcessor import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.builtins.UnsignedType import org.jetbrains.kotlin.config.coroutinesIntrinsicsPackageFqName import org.jetbrains.kotlin.config.coroutinesPackageFqName import org.jetbrains.kotlin.config.languageVersionSettings import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.ir.declarations.IrModuleFragment import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns import org.jetbrains.kotlin.ir.symbols.IrClassSymbol import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.types.typeWith import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.calls.components.isVararg import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.Variance import kotlin.properties.Delegates // This is what Context collects about IR. internal class KonanIr(context: Context, irModule: IrModuleFragment): Ir<Context>(context, irModule) { override var symbols: KonanSymbols by Delegates.notNull() } internal class KonanSymbols( context: Context, irBuiltIns: IrBuiltIns, private val symbolTable: SymbolTable, lazySymbolTable: ReferenceSymbolTable, val functionIrClassFactory: BuiltInFictitiousFunctionIrClassFactory ): Symbols<Context>(context, irBuiltIns, symbolTable) { val entryPoint = findMainEntryPoint(context)?.let { symbolTable.referenceSimpleFunction(it) } override val externalSymbolTable = lazySymbolTable val nothing = symbolTable.referenceClass(builtIns.nothing) val throwable = symbolTable.referenceClass(builtIns.throwable) val enum = symbolTable.referenceClass(builtIns.enum) val nativePtr = symbolTable.referenceClass(context.nativePtr) val nativePointed = symbolTable.referenceClass(context.interopBuiltIns.nativePointed) val nativePtrType = nativePtr.typeWith(arguments = emptyList()) val nonNullNativePtr = symbolTable.referenceClass(context.nonNullNativePtr) val immutableBlobOf = symbolTable.referenceSimpleFunction(context.immutableBlobOf) private fun unsignedClass(unsignedType: UnsignedType): IrClassSymbol = classById(unsignedType.classId) override val uByte = unsignedClass(UnsignedType.UBYTE) override val uShort = unsignedClass(UnsignedType.USHORT) override val uInt = unsignedClass(UnsignedType.UINT) override val uLong = unsignedClass(UnsignedType.ULONG) val signedIntegerClasses = setOf(byte, short, int, long) val unsignedIntegerClasses = setOf(uByte, uShort, uInt, uLong) val allIntegerClasses = signedIntegerClasses + unsignedIntegerClasses val unsignedToSignedOfSameBitWidth = unsignedIntegerClasses.associate { it to when (it) { uByte -> byte uShort -> short uInt -> int uLong -> long else -> error(it.descriptor) } } val integerConversions = allIntegerClasses.flatMap { fromClass -> allIntegerClasses.map { toClass -> val name = Name.identifier("to${toClass.descriptor.name.asString().capitalize()}") val descriptor = if (fromClass in signedIntegerClasses && toClass in unsignedIntegerClasses) { builtInsPackage("kotlin") .getContributedFunctions(name, NoLookupLocation.FROM_BACKEND) .single { it.dispatchReceiverParameter == null && it.extensionReceiverParameter?.type == fromClass.descriptor.defaultType && it.valueParameters.isEmpty() } } else { fromClass.descriptor.unsubstitutedMemberScope .getContributedFunctions(name, NoLookupLocation.FROM_BACKEND) .single { it.extensionReceiverParameter == null && it.valueParameters.isEmpty() } } val symbol = symbolTable.referenceSimpleFunction(descriptor) (fromClass to toClass) to symbol } }.toMap() val arrayList = symbolTable.referenceClass(getArrayListClassDescriptor(context)) val symbolName = topLevelClass(RuntimeNames.symbolNameAnnotation) val filterExceptions = topLevelClass(RuntimeNames.filterExceptions) val exportForCppRuntime = topLevelClass(RuntimeNames.exportForCppRuntime) val objCMethodImp = symbolTable.referenceClass(context.interopBuiltIns.objCMethodImp) val onUnhandledException = internalFunction("OnUnhandledException") val interopNativePointedGetRawPointer = symbolTable.referenceSimpleFunction(context.interopBuiltIns.nativePointedGetRawPointer) val interopCPointer = symbolTable.referenceClass(context.interopBuiltIns.cPointer) val interopCstr = symbolTable.referenceSimpleFunction(context.interopBuiltIns.cstr.getter!!) val interopWcstr = symbolTable.referenceSimpleFunction(context.interopBuiltIns.wcstr.getter!!) val interopMemScope = symbolTable.referenceClass(context.interopBuiltIns.memScope) val interopCValue = symbolTable.referenceClass(context.interopBuiltIns.cValue) val interopCValues = symbolTable.referenceClass(context.interopBuiltIns.cValues) val interopCValuesRef = symbolTable.referenceClass(context.interopBuiltIns.cValuesRef) val interopCValueWrite = symbolTable.referenceSimpleFunction(context.interopBuiltIns.cValueWrite) val interopCValueRead = symbolTable.referenceSimpleFunction(context.interopBuiltIns.cValueRead) val interopAllocType = symbolTable.referenceSimpleFunction(context.interopBuiltIns.allocType) val interopTypeOf = symbolTable.referenceSimpleFunction(context.interopBuiltIns.typeOf) val interopCPointerGetRawValue = symbolTable.referenceSimpleFunction(context.interopBuiltIns.cPointerGetRawValue) val interopAllocObjCObject = symbolTable.referenceSimpleFunction(context.interopBuiltIns.allocObjCObject) val interopForeignObjCObject = interopClass("ForeignObjCObject") // These are possible supertypes of forward declarations - we need to reference them explicitly to force their deserialization. // TODO: Do it lazily. val interopCOpaque = symbolTable.referenceClass(context.interopBuiltIns.cOpaque) val interopObjCObject = symbolTable.referenceClass(context.interopBuiltIns.objCObject) val interopObjCObjectBase = symbolTable.referenceClass(context.interopBuiltIns.objCObjectBase) val interopObjCRelease = interopFunction("objc_release") val interopObjCRetain = interopFunction("objc_retain") val interopObjcRetainAutoreleaseReturnValue = interopFunction("objc_retainAutoreleaseReturnValue") val interopCreateObjCObjectHolder = interopFunction("createObjCObjectHolder") val interopCreateKotlinObjectHolder = interopFunction("createKotlinObjectHolder") val interopUnwrapKotlinObjectHolderImpl = interopFunction("unwrapKotlinObjectHolderImpl") val interopCreateObjCSuperStruct = interopFunction("createObjCSuperStruct") val interopGetMessenger = interopFunction("getMessenger") val interopGetMessengerStret = interopFunction("getMessengerStret") val interopGetObjCClass = symbolTable.referenceSimpleFunction(context.interopBuiltIns.getObjCClass) val interopObjCObjectSuperInitCheck = symbolTable.referenceSimpleFunction(context.interopBuiltIns.objCObjectSuperInitCheck) val interopObjCObjectInitBy = symbolTable.referenceSimpleFunction(context.interopBuiltIns.objCObjectInitBy) val interopObjCObjectRawValueGetter = symbolTable.referenceSimpleFunction(context.interopBuiltIns.objCObjectRawPtr) val interopNativePointedRawPtrGetter = symbolTable.referenceSimpleFunction(context.interopBuiltIns.nativePointedRawPtrGetter) val interopCPointerRawValue = symbolTable.referenceProperty(context.interopBuiltIns.cPointerRawValue) val interopInterpretObjCPointer = symbolTable.referenceSimpleFunction(context.interopBuiltIns.interpretObjCPointer) val interopInterpretObjCPointerOrNull = symbolTable.referenceSimpleFunction(context.interopBuiltIns.interpretObjCPointerOrNull) val interopInterpretNullablePointed = symbolTable.referenceSimpleFunction(context.interopBuiltIns.interpretNullablePointed) val interopInterpretCPointer = symbolTable.referenceSimpleFunction(context.interopBuiltIns.interpretCPointer) val interopCreateNSStringFromKString = symbolTable.referenceSimpleFunction(context.interopBuiltIns.CreateNSStringFromKString) val createForeignException = interopFunction("CreateForeignException") val interopObjCGetSelector = interopFunction("objCGetSelector") val interopCEnumVar = interopClass("CEnumVar") val nativeMemUtils = symbolTable.referenceClass(context.interopBuiltIns.nativeMemUtils) val readBits = interopFunction("readBits") val writeBits = interopFunction("writeBits") val objCExportTrapOnUndeclaredException = symbolTable.referenceSimpleFunction(context.builtIns.kotlinNativeInternal.getContributedFunctions( Name.identifier("trapOnUndeclaredException"), NoLookupLocation.FROM_BACKEND ).single()) val objCExportResumeContinuation = internalFunction("resumeContinuation") val objCExportResumeContinuationWithException = internalFunction("resumeContinuationWithException") val objCExportGetCoroutineSuspended = internalFunction("getCoroutineSuspended") val objCExportInterceptedContinuation = internalFunction("interceptedContinuation") val getNativeNullPtr = symbolTable.referenceSimpleFunction(context.getNativeNullPtr) val boxCachePredicates = BoxCache.values().associate { it to internalFunction("in${it.name.toLowerCase().capitalize()}BoxCache") } val boxCacheGetters = BoxCache.values().associate { it to internalFunction("getCached${it.name.toLowerCase().capitalize()}Box") } val immutableBlob = symbolTable.referenceClass( builtInsPackage("kotlin", "native").getContributedClassifier( Name.identifier("ImmutableBlob"), NoLookupLocation.FROM_BACKEND ) as ClassDescriptor ) val executeImpl = symbolTable.referenceSimpleFunction( builtIns.builtInsModule.getPackage(FqName("kotlin.native.concurrent")).memberScope .getContributedFunctions(Name.identifier("executeImpl"), NoLookupLocation.FROM_BACKEND) .single() ) val areEqualByValue = context.getKonanInternalFunctions("areEqualByValue").map { symbolTable.referenceSimpleFunction(it) }.associateBy { it.descriptor.valueParameters[0].type.computePrimitiveBinaryTypeOrNull()!! } val reinterpret = internalFunction("reinterpret") val ieee754Equals = context.getKonanInternalFunctions("ieee754Equals").map { symbolTable.referenceSimpleFunction(it) } val equals = context.builtIns.any.unsubstitutedMemberScope .getContributedFunctions(Name.identifier("equals"), NoLookupLocation.FROM_BACKEND) .single().let { symbolTable.referenceSimpleFunction(it) } val throwArithmeticException = internalFunction("ThrowArithmeticException") val throwIndexOutOfBoundsException = internalFunction("ThrowIndexOutOfBoundsException") override val throwNullPointerException = internalFunction("ThrowNullPointerException") override val throwNoWhenBranchMatchedException = internalFunction("ThrowNoWhenBranchMatchedException") override val throwTypeCastException = internalFunction("ThrowTypeCastException") override val throwKotlinNothingValueException = internalFunction("ThrowKotlinNothingValueException") val throwClassCastException = internalFunction("ThrowClassCastException") val throwInvalidReceiverTypeException = internalFunction("ThrowInvalidReceiverTypeException") val throwIllegalStateException = internalFunction("ThrowIllegalStateException") val throwIllegalStateExceptionWithMessage = internalFunction("ThrowIllegalStateExceptionWithMessage") val throwIllegalArgumentException = internalFunction("ThrowIllegalArgumentException") val throwIllegalArgumentExceptionWithMessage = internalFunction("ThrowIllegalArgumentExceptionWithMessage") override val throwUninitializedPropertyAccessException = internalFunction("ThrowUninitializedPropertyAccessException") override val stringBuilder = symbolTable.referenceClass( builtInsPackage("kotlin", "text").getContributedClassifier( Name.identifier("StringBuilder"), NoLookupLocation.FROM_BACKEND ) as ClassDescriptor ) override val defaultConstructorMarker = symbolTable.referenceClass( context.getKonanInternalClass("DefaultConstructorMarker") ) val checkProgressionStep = context.getKonanInternalFunctions("checkProgressionStep") .map { Pair(it.returnType, symbolTable.referenceSimpleFunction(it)) }.toMap() val getProgressionLast = context.getKonanInternalFunctions("getProgressionLast") .map { Pair(it.returnType, symbolTable.referenceSimpleFunction(it)) }.toMap() val arrayContentToString = arrays.associateBy( { it }, { findArrayExtension(it.descriptor, "contentToString") } ) val arrayContentHashCode = arrays.associateBy( { it }, { findArrayExtension(it.descriptor, "contentHashCode") } ) private val kotlinCollectionsPackageScope: MemberScope get() = builtInsPackage("kotlin", "collections") private fun findArrayExtension(descriptor: ClassDescriptor, name: String): IrSimpleFunctionSymbol { val functionDescriptor = kotlinCollectionsPackageScope .getContributedFunctions(Name.identifier(name), NoLookupLocation.FROM_BACKEND) .singleOrNull { it.valueParameters.isEmpty() && it.extensionReceiverParameter?.type?.constructor?.declarationDescriptor == descriptor && it.extensionReceiverParameter?.type?.isMarkedNullable == false && !it.isExpect } ?: error(descriptor.toString()) return symbolTable.referenceSimpleFunction(functionDescriptor) } override val copyRangeTo get() = TODO() fun getNoParamFunction(name: Name, receiverType: KotlinType): IrFunctionSymbol { val descriptor = receiverType.memberScope.getContributedFunctions(name, NoLookupLocation.FROM_BACKEND) .first { it.valueParameters.isEmpty() } return symbolTable.referenceFunction(descriptor) } val copyInto = arrays.map { symbol -> val packageViewDescriptor = builtIns.builtInsModule.getPackage(StandardNames.COLLECTIONS_PACKAGE_FQ_NAME) val functionDescriptor = packageViewDescriptor.memberScope .getContributedFunctions(Name.identifier("copyInto"), NoLookupLocation.FROM_BACKEND) .single { !it.isExpect && it.extensionReceiverParameter?.type?.constructor?.declarationDescriptor == symbol.descriptor } symbol.descriptor to symbolTable.referenceSimpleFunction(functionDescriptor) }.toMap() val arrayGet = arrays.associateWith { it.descriptor.unsubstitutedMemberScope .getContributedFunctions(Name.identifier("get"), NoLookupLocation.FROM_BACKEND) .single().let { symbolTable.referenceSimpleFunction(it) } } val arraySet = arrays.associateWith { it.descriptor.unsubstitutedMemberScope .getContributedFunctions(Name.identifier("set"), NoLookupLocation.FROM_BACKEND) .single().let { symbolTable.referenceSimpleFunction(it) } } val arraySize = arrays.associateWith { it.descriptor.unsubstitutedMemberScope .getContributedVariables(Name.identifier("size"), NoLookupLocation.FROM_BACKEND) .single().let { symbolTable.referenceSimpleFunction(it.getter!!) } } val valuesForEnum = internalFunction("valuesForEnum") val valueOfForEnum = internalFunction("valueOfForEnum") val createUninitializedInstance = internalFunction("createUninitializedInstance") val initInstance = internalFunction("initInstance") val freeze = symbolTable.referenceSimpleFunction( builtInsPackage("kotlin", "native", "concurrent").getContributedFunctions( Name.identifier("freeze"), NoLookupLocation.FROM_BACKEND).single()) val println = symbolTable.referenceSimpleFunction( builtInsPackage("kotlin", "io").getContributedFunctions( Name.identifier("println"), NoLookupLocation.FROM_BACKEND) .single { it.valueParameters.singleOrNull()?.type == builtIns.stringType }) val anyNToString = symbolTable.referenceSimpleFunction( builtInsPackage("kotlin").getContributedFunctions( Name.identifier("toString"), NoLookupLocation.FROM_BACKEND) .single { it.extensionReceiverParameter?.type == builtIns.nullableAnyType}) override val getContinuation = internalFunction("getContinuation") override val returnIfSuspended = internalFunction("returnIfSuspended") val coroutineLaunchpad = internalFunction("coroutineLaunchpad") override val suspendCoroutineUninterceptedOrReturn = internalFunction("suspendCoroutineUninterceptedOrReturn") private val coroutinesIntrinsicsPackage = context.builtIns.builtInsModule.getPackage( context.config.configuration.languageVersionSettings.coroutinesIntrinsicsPackageFqName()).memberScope private val coroutinesPackage = context.builtIns.builtInsModule.getPackage( context.config.configuration.languageVersionSettings.coroutinesPackageFqName()).memberScope override val coroutineContextGetter = symbolTable.referenceSimpleFunction( coroutinesPackage .getContributedVariables(Name.identifier("coroutineContext"), NoLookupLocation.FROM_BACKEND) .single() .getter!!) override val coroutineGetContext = internalFunction("getCoroutineContext") override val coroutineImpl get() = TODO() val baseContinuationImpl = topLevelClass("kotlin.coroutines.native.internal.BaseContinuationImpl") val restrictedContinuationImpl = topLevelClass("kotlin.coroutines.native.internal.RestrictedContinuationImpl") val continuationImpl = topLevelClass("kotlin.coroutines.native.internal.ContinuationImpl") val invokeSuspendFunction = symbolTable.referenceSimpleFunction( baseContinuationImpl.descriptor.unsubstitutedMemberScope .getContributedFunctions(Name.identifier("invokeSuspend"), NoLookupLocation.FROM_BACKEND) .single() ) override val coroutineSuspendedGetter = symbolTable.referenceSimpleFunction( coroutinesIntrinsicsPackage .getContributedVariables(COROUTINE_SUSPENDED_NAME, NoLookupLocation.FROM_BACKEND) .filterNot { it.isExpect }.single().getter!! ) val cancellationException = topLevelClass(KonanFqNames.cancellationException) val kotlinResult = topLevelClass("kotlin.Result") val kotlinResultGetOrThrow = symbolTable.referenceSimpleFunction( builtInsPackage("kotlin") .getContributedFunctions(Name.identifier("getOrThrow"), NoLookupLocation.FROM_BACKEND) .single { it.extensionReceiverParameter?.type?.constructor?.declarationDescriptor == kotlinResult.descriptor } ) override val functionAdapter = symbolTable.referenceClass(context.getKonanInternalClass("FunctionAdapter")) val refClass = symbolTable.referenceClass(context.getKonanInternalClass("Ref")) val kFunctionImpl = symbolTable.referenceClass(context.reflectionTypes.kFunctionImpl) val kSuspendFunctionImpl = symbolTable.referenceClass(context.reflectionTypes.kSuspendFunctionImpl) val kMutableProperty0 = symbolTable.referenceClass(context.reflectionTypes.kMutableProperty0) val kMutableProperty1 = symbolTable.referenceClass(context.reflectionTypes.kMutableProperty1) val kMutableProperty2 = symbolTable.referenceClass(context.reflectionTypes.kMutableProperty2) val kProperty0Impl = symbolTable.referenceClass(context.reflectionTypes.kProperty0Impl) val kProperty1Impl = symbolTable.referenceClass(context.reflectionTypes.kProperty1Impl) val kProperty2Impl = symbolTable.referenceClass(context.reflectionTypes.kProperty2Impl) val kMutableProperty0Impl = symbolTable.referenceClass(context.reflectionTypes.kMutableProperty0Impl) val kMutableProperty1Impl = symbolTable.referenceClass(context.reflectionTypes.kMutableProperty1Impl) val kMutableProperty2Impl = symbolTable.referenceClass(context.reflectionTypes.kMutableProperty2Impl) val kLocalDelegatedPropertyImpl = symbolTable.referenceClass(context.reflectionTypes.kLocalDelegatedPropertyImpl) val kLocalDelegatedMutablePropertyImpl = symbolTable.referenceClass(context.reflectionTypes.kLocalDelegatedMutablePropertyImpl) val getClassTypeInfo = internalFunction("getClassTypeInfo") val getObjectTypeInfo = internalFunction("getObjectTypeInfo") val kClassImpl = internalClass("KClassImpl") val kClassImplConstructor by lazy { kClassImpl.constructors.single() } val kClassUnsupportedImpl = internalClass("KClassUnsupportedImpl") val kClassUnsupportedImplConstructor by lazy { kClassUnsupportedImpl.constructors.single() } val kTypeImpl = internalClass("KTypeImpl") val kTypeImplForGenerics = internalClass("KTypeImplForGenerics") val kTypeProjection = symbolTable.referenceClass(context.reflectionTypes.kTypeProjection) private val kTypeProjectionCompanionDescriptor = context.reflectionTypes.kTypeProjection.companionObjectDescriptor!! val kTypeProjectionCompanion = symbolTable.referenceClass(kTypeProjectionCompanionDescriptor) val kTypeProjectionStar = symbolTable.referenceProperty( kTypeProjectionCompanionDescriptor.unsubstitutedMemberScope .getContributedVariables(Name.identifier("STAR"), NoLookupLocation.FROM_BACKEND).single() ) val kTypeProjectionFactories: Map<Variance, IrSimpleFunctionSymbol> = Variance.values().toList().associateWith { val factoryName = when (it) { Variance.INVARIANT -> "invariant" Variance.IN_VARIANCE -> "contravariant" Variance.OUT_VARIANCE -> "covariant" } symbolTable.referenceSimpleFunction( kTypeProjectionCompanionDescriptor.unsubstitutedMemberScope .getContributedFunctions(Name.identifier(factoryName), NoLookupLocation.FROM_BACKEND).single() ) } val emptyList = symbolTable.referenceSimpleFunction( kotlinCollectionsPackageScope .getContributedFunctions(Name.identifier("emptyList"), NoLookupLocation.FROM_BACKEND) .single { it.valueParameters.isEmpty() } ) val listOf = symbolTable.referenceSimpleFunction( kotlinCollectionsPackageScope .getContributedFunctions(Name.identifier("listOf"), NoLookupLocation.FROM_BACKEND) .single { it.valueParameters.size == 1 && it.valueParameters[0].isVararg } ) val listOfInternal = internalFunction("listOfInternal") val threadLocal = symbolTable.referenceClass( context.builtIns.builtInsModule.findClassAcrossModuleDependencies( ClassId.topLevel(KonanFqNames.threadLocal))!!) val sharedImmutable = symbolTable.referenceClass( context.builtIns.builtInsModule.findClassAcrossModuleDependencies( ClassId.topLevel(KonanFqNames.sharedImmutable))!!) private fun topLevelClass(fqName: String): IrClassSymbol = topLevelClass(FqName(fqName)) private fun topLevelClass(fqName: FqName): IrClassSymbol = classById(ClassId.topLevel(fqName)) private fun classById(classId: ClassId): IrClassSymbol = symbolTable.referenceClass(builtIns.builtInsModule.findClassAcrossModuleDependencies(classId)!!) private fun internalFunction(name: String): IrSimpleFunctionSymbol = symbolTable.referenceSimpleFunction(context.getKonanInternalFunctions(name).single()) private fun internalClass(name: String): IrClassSymbol = symbolTable.referenceClass(context.getKonanInternalClass(name)) private fun getKonanTestClass(className: String) = symbolTable.referenceClass( builtInsPackage("kotlin", "native", "internal", "test").getContributedClassifier( Name.identifier(className), NoLookupLocation.FROM_BACKEND ) as ClassDescriptor) private fun interopFunction(name: String) = symbolTable.referenceSimpleFunction( context.interopBuiltIns.packageScope .getContributedFunctions(Name.identifier(name), NoLookupLocation.FROM_BACKEND) .single() ) private fun interopClass(name: String) = symbolTable.referenceClass( context.interopBuiltIns.packageScope .getContributedClassifier(Name.identifier(name), NoLookupLocation.FROM_BACKEND) as ClassDescriptor ) override fun functionN(n: Int) = functionIrClassFactory.functionN(n).symbol override fun suspendFunctionN(n: Int) = functionIrClassFactory.suspendFunctionN(n).symbol fun kFunctionN(n: Int) = functionIrClassFactory.kFunctionN(n).symbol fun kSuspendFunctionN(n: Int) = functionIrClassFactory.kSuspendFunctionN(n).symbol fun getKFunctionType(returnType: IrType, parameterTypes: List<IrType>) = kFunctionN(parameterTypes.size).typeWith(parameterTypes + returnType) val baseClassSuite = getKonanTestClass("BaseClassSuite") val topLevelSuite = getKonanTestClass("TopLevelSuite") val testFunctionKind = getKonanTestClass("TestFunctionKind") private val testFunctionKindCache = TestProcessor.FunctionKind.values().associate { val symbol = if (it.runtimeKindString.isEmpty()) null else symbolTable.referenceEnumEntry(testFunctionKind.descriptor.unsubstitutedMemberScope.getContributedClassifier( Name.identifier(it.runtimeKindString), NoLookupLocation.FROM_BACKEND ) as ClassDescriptor) it to symbol } fun getTestFunctionKind(kind: TestProcessor.FunctionKind) = testFunctionKindCache[kind]!! } private fun getArrayListClassDescriptor(context: Context): ClassDescriptor { val module = context.builtIns.builtInsModule val pkg = module.getPackage(FqName.fromSegments(listOf("kotlin", "collections"))) val classifier = pkg.memberScope.getContributedClassifier(Name.identifier("ArrayList"), NoLookupLocation.FROM_BACKEND) return classifier as ClassDescriptor }
apache-2.0
3cc0238b79edc429d1d0ca366cffce83
49.222025
131
0.749425
5.642586
false
false
false
false
ak80/akkabase
akkabase-core/src/main/java/org/ak80/akkabase/Message.kt
1
1102
package org.ak80.akkabase import java.io.Serializable /** * Message for Akka Actors */ fun getDbActor(remoteAddress: String) = "akka.tcp://$serverSystem@$remoteAddress/user/$dbActor" val serverSystem = "akkabase" val dbActor = "akkabase-db" // SetRequest for insert and update of a key-value-pair class SetRequest(val key: String, val value: Any) : Serializable { override fun toString() = "${this.javaClass.simpleName} $key=$value" } // GetRequest for insert and update of a key-value-pair class GetRequest(val key: String) : Serializable { override fun toString() = "${this.javaClass.simpleName} $key" } // SetIfNotExists for insert if no pair exists for key class SetIfNotExistsRequest(val key: String, val value: Any) : Serializable { override fun toString() = "${this.javaClass.simpleName} $key=$value" } // DeleteRequest delete of a key-value-pair class DeleteRequest(val key: String) : Serializable { override fun toString() = "${this.javaClass.simpleName} $key" } // for key not found class KeyNotFoundException(val key: String) : Exception(), Serializable
apache-2.0
712ac8cc3e88d14b4291f291be01853e
22.978261
95
0.72686
3.649007
false
false
false
false
langara/MyIntent
myactivities/src/main/java/pl/mareklangiewicz/myactivities/MyExampleActivity.kt
1
847
package pl.mareklangiewicz.myactivities import android.os.Bundle import pl.mareklangiewicz.myutils.i /** * Created by Marek Langiewicz on 22.09.15. * Simple example activity using MyActivity features... */ class MyExampleActivity : MyActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) log.i("Hi, I am the example activity..") gnav!!.menuId = R.menu.ma_my_example_global gnav!!.headerId = R.layout.ma_my_example_global_header gnav!!.items { // we ignore returned subscription - navigation will live as long as activity if (it == R.id.ma_meg_i_my_example_action) log.i("[SNACK][SHORT]Example: ACTION!") } if (savedInstanceState == null) gnav!!.setCheckedItem(R.id.ma_meg_i_my_example_fragment_1, true) } }
apache-2.0
1732f9307f12331013e118f909ad5951
37.5
100
0.672963
3.86758
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/scene/CompletableScene.kt
1
936
package com.soywiz.korge.scene import com.soywiz.klock.* import com.soywiz.korge.internal.* import com.soywiz.korge.view.* import com.soywiz.korio.async.* import kotlinx.coroutines.* abstract class CompletableScene<T>() : Scene() { private val deferred = CompletableDeferred<T>() val completed get() = deferred as Deferred<T> abstract suspend fun Container.setup() abstract suspend fun process(): T final override suspend fun Container.sceneInit() { setup() launchImmediately { try { deferred.complete(process()) } catch (e: Throwable) { deferred.completeExceptionally(e) } } } } suspend inline fun <reified T : CompletableScene<R>, R> SceneContainer.changeToResult( vararg injects: Any, time: TimeSpan = 0.milliseconds, transition: Transition = AlphaTransition ): R { val instance = changeTo(T::class, *injects, time = time, transition = transition) return instance.completed.await() }
apache-2.0
3002f5899b741a42ce6d26c13567f873
25
86
0.726496
3.714286
false
false
false
false
arturbosch/TiNBo
tinbo-plugin-api/src/main/kotlin/io/gitlab/arturbosch/tinbo/api/commands/EditableCommands.kt
1
4298
package io.gitlab.arturbosch.tinbo.api.commands import io.gitlab.arturbosch.tinbo.api.TinboTerminal import io.gitlab.arturbosch.tinbo.api.config.ModeManager import io.gitlab.arturbosch.tinbo.api.marker.Command import io.gitlab.arturbosch.tinbo.api.marker.Editable import io.gitlab.arturbosch.tinbo.api.model.AbstractExecutor import io.gitlab.arturbosch.tinbo.api.model.Data import io.gitlab.arturbosch.tinbo.api.model.DummyEntry import io.gitlab.arturbosch.tinbo.api.model.Entry import io.gitlab.arturbosch.tinbo.api.utils.printlnInfo import java.util.HashSet /** * @author artur */ @Suppress("MemberVisibilityCanBePrivate") abstract class EditableCommands<E : Entry, D : Data<E>, in T : DummyEntry>( val executor: AbstractExecutor<E, D, T>, val console: TinboTerminal) : Command, Editable { private val needEditModeText = "Before adding or list entries exit edit mode with 'save' or 'cancel'." protected var isListMode: Boolean = false protected var isEditMode: Boolean = false protected fun withListMode(body: () -> String): String { isListMode = true return body.invoke() } protected fun withinListMode(body: () -> String): String { return if (isListMode) { body.invoke() } else { "Before editing entries you have to 'list' them to get indices to work on." } } protected fun enterEditModeWithIndex(index: Int, body: () -> String): String { return if (executor.indexExists(index)) { ModeManager.isBackCommandBlocked = true isEditMode = true body.invoke() } else { "This index doesn't exist" } } protected fun withinEditMode(command: String, body: () -> String): String { return if (isEditMode) { ModeManager.isBackCommandBlocked = false isEditMode = false isListMode = false body.invoke() } else { "You need to be in edit mode to use $command." } } protected fun whileNotInEditMode(body: () -> String): String { return if (isEditMode) { needEditModeText } else { body.invoke() } } override fun load(name: String): String { executor.loadData(name) return "Successfully loaded data set $name" } override fun list(categoryName: String, all: Boolean): String { return withListMode { if (isEditMode) { if (categoryName.isNotEmpty()) printlnInfo("While in edit mode filtering is ignored.") executor.listInMemoryEntries(all) } else { when (categoryName) { "" -> executor.listData(all) else -> executor.listDataFilteredBy(categoryName, all) } } } } override fun cancel(): String { return withinEditMode("cancel") { executor.cancel() "Cancelled edit mode." } } override fun save(name: String): String { return withinEditMode("save") { executor.saveEntries(name) "Successfully saved edited data" } } override fun delete(indexPattern: String): String { return withinListMode { try { val indices = if (indexPattern == "-1") setOf(-1) else parseIndices(indexPattern) ModeManager.isBackCommandBlocked = true isEditMode = true executor.deleteEntries(indices) "Successfully deleted task(s)." } catch (e: IllegalArgumentException) { "Could not parse the indices pattern. Use something like '1 2 3-5 6'." } } } override fun changeCategory(oldName: String, newName: String): String { return whileNotInEditMode { executor.changeCategory(oldName, newName) "Updated entries of category $oldName to have new category $newName" } } override fun categories(): String = executor.categoryNames().joinToString() override fun data(): String { return "Available data sets: " + executor.getAllDataNames().joinToString() } private fun parseIndices(indexPattern: String): Set<Int> { val result = HashSet<Int>() val indices = indexPattern.split(" ") val regex = Regex("[1-9][0-9]*") val regex2 = Regex("[1-9]+-[0-9]+") for (index in indices) { if (regex.matches(index)) { result.add(index.toInt() - 1) } else if (regex2.matches(index)) { val interval = index.split("-") if (interval.size == 2) { val (i1, i2) = Pair(interval[0].toInt(), interval[1].toInt()) IntRange(i1 - 1, i2 - 1) .forEach { result.add(it) } } else { throw IllegalArgumentException() } } else { throw IllegalArgumentException() } } return result } }
apache-2.0
063a4a2451ae100b2df1ff3b19df52d9
26.909091
103
0.695207
3.471729
false
false
false
false
Ztiany/Repository
Android/AndroidDatabase/app/src/main/java/me/ztiany/android/database/origin/utils/DBUtils.kt
2
1525
package me.ztiany.android.database.origin.utils import android.content.Context import android.content.Context.MODE_PRIVATE import android.database.sqlite.SQLiteDatabase import android.os.Environment import android.util.Log import me.ztiany.android.database.ORIGIN_TAG import java.io.File /** 查看手机中由SQLiteDatabase创建的的数据库文件 */ fun showDataBase(sqLiteDatabase: SQLiteDatabase) { val ll = sqLiteDatabase.attachedDbs for (i in ll.indices) { val p = ll[i] Log.d(ORIGIN_TAG, p.first + "=" + p.second) } } /** * Context.openOrCreateDatabase 打开或创建数据库,可以指定数据库文件的操作模式 * * @param database 数据库名称 * @param context 上下文 */ fun openOrCreateDatabase(context: Context, database: String) { /**指定数据库的名称为 info2.db,并指定数据文件的操作模式为MODE_PRIVATE */ val sqLiteDatabase = context.openOrCreateDatabase(database, MODE_PRIVATE, null) /**查看改对象所创建的数据库 */ showDataBase(sqLiteDatabase) } /** * SQLiteDatabase.openOrCreateDatabase 打开或创建数据库 * * @param fileName 可以指定数据库文件的路径 */ fun sQLiteDatabase(fileName: String) { val dataBaseFile = File(Environment.getExternalStorageDirectory(), "/sqlite$fileName") if (!dataBaseFile.parentFile.exists()) { dataBaseFile.mkdirs() } val sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(dataBaseFile, null) showDataBase(sqLiteDatabase) }
apache-2.0
3162ac2aa29a86cc6b26af4487f60119
27.170213
90
0.74452
3.654696
false
false
false
false
jitsi/jicofo
jicofo/src/test/kotlin/org/jitsi/jicofo/jibri/JibriDetectorTest.kt
1
7405
/* * Copyright @ 2018 - present 8x8, 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 org.jitsi.jicofo.jibri import io.kotest.core.spec.IsolationMode import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.mockk.every import io.mockk.mockk import org.jitsi.impl.protocol.xmpp.ChatRoom import org.jitsi.impl.protocol.xmpp.ChatRoomMember import org.jitsi.impl.protocol.xmpp.XmppProvider import org.jitsi.jicofo.jibri.JibriDetector.Companion.FAILURE_TIMEOUT import org.jitsi.jicofo.jibri.JibriDetector.Companion.SELECT_TIMEOUT import org.jitsi.jicofo.xmpp.muc.MemberRole import org.jitsi.jicofo.xmpp.muc.SourceInfo import org.jitsi.utils.mins import org.jitsi.utils.ms import org.jitsi.utils.time.FakeClock import org.jitsi.xmpp.extensions.health.HealthStatusPacketExt import org.jitsi.xmpp.extensions.health.HealthStatusPacketExt.Health.HEALTHY import org.jitsi.xmpp.extensions.health.HealthStatusPacketExt.Health.UNHEALTHY import org.jitsi.xmpp.extensions.jibri.JibriBusyStatusPacketExt import org.jitsi.xmpp.extensions.jibri.JibriStatusPacketExt import org.jivesoftware.smack.AbstractXMPPConnection import org.jivesoftware.smack.packet.Presence import org.jxmpp.jid.EntityFullJid import org.jxmpp.jid.Jid import org.jxmpp.jid.impl.JidCreate class JibriDetectorTest : ShouldSpec({ isolationMode = IsolationMode.InstancePerLeaf val mockXmppConnection = mockk<AbstractXMPPConnection>() val mockXmppProvider = mockk<XmppProvider>().apply { every { xmppConnection } returns mockXmppConnection } val clock = FakeClock().apply { elapse(10.mins) } val detector = JibriDetector(mockXmppProvider, JidCreate.entityBareFrom("[email protected]"), false, clock) val jibriJids = listOf( JidCreate.entityFullFrom("[email protected]/jibri1"), JidCreate.entityFullFrom("[email protected]/jibri2"), JidCreate.entityFullFrom("[email protected]/jibri3") ) val jibriMembers = jibriJids.map { JibriChatRoomMember(it, detector) } context("Selecting a Jibri") { context("When none of the instances are healthy") { jibriMembers.forEach { it.setStatus(idle = true, healthy = false) } detector.selectJibri() shouldBe null } context("When none of the instances are idle") { jibriMembers.forEach { it.setStatus(idle = false, healthy = true) } detector.selectJibri() shouldBe null } context("Select an idle and healthy jibri if one is available") { jibriMembers[0].setStatus(idle = true, healthy = false) jibriMembers[1].setStatus(idle = false, healthy = true) jibriMembers[2].setStatus(idle = true, healthy = true) detector.selectJibri() shouldBe jibriJids[2] } context("Select timeout") { val selection1 = detector.selectJibri() selection1 shouldNotBe null val selection2 = detector.selectJibri() selection2 shouldNotBe null selection2 shouldNotBe selection1 val selection3 = detector.selectJibri() selection3 shouldNotBe null selection3 shouldNotBe selection1 selection3 shouldNotBe selection2 val selection4 = detector.selectJibri() selection4 shouldBe null clock.elapse(SELECT_TIMEOUT + 10.ms) detector.selectJibri() shouldNotBe null } context("Instances failure") { jibriMembers[0].setStatus(idle = false, healthy = true) jibriMembers[1].setStatus(idle = true, healthy = true) jibriMembers[2].setStatus(idle = true, healthy = true) detector.instanceFailed(jibriJids[1]) detector.selectJibri() shouldBe jibriJids[2] detector.selectJibri() shouldBe null // select timeout clock.elapse(SELECT_TIMEOUT + 100.ms) detector.instanceFailed(jibriJids[2]) // All idle instances failed recently. detector.selectJibri() shouldBe null clock.elapse(FAILURE_TIMEOUT + 1.mins) // jibri1 failed less recently detector.selectJibri() shouldBe jibriJids[1] clock.elapse(FAILURE_TIMEOUT + 1.mins) detector.instanceFailed(jibriJids[1]) clock.elapse(SELECT_TIMEOUT + 100.ms) detector.instanceFailed(jibriJids[2]) clock.elapse(SELECT_TIMEOUT + 100.ms) jibriMembers[1].setStatus(idle = true, healthy = true) // Updated presence should clear the failure indication. detector.selectJibri() shouldBe jibriJids[1] jibriMembers[2].setStatus(idle = true, healthy = true) // jibri1 is still in select timeout detector.selectJibri() shouldBe jibriJids[2] } } }) class JibriChatRoomMember( val jid_: EntityFullJid, val detector: JibriDetector ) : ChatRoomMember { override fun getName(): String = TODO("Not yet implemented") override fun getChatRoom(): ChatRoom = TODO("Not yet implemented") override fun getRole(): MemberRole = TODO("Not yet implemented") override fun setRole(role: MemberRole?) = TODO("Not yet implemented") override fun getJid(): Jid = TODO("Not yet implemented") override fun getSourceInfos(): MutableSet<SourceInfo> = TODO("Not yet implemented") override fun getJoinOrderNumber(): Int = TODO("Not yet implemented") override fun isRobot(): Boolean = TODO("Not yet implemented") override fun isJigasi(): Boolean = TODO("Not yet implemented") override fun isJibri(): Boolean = TODO("Not yet implemented") override fun isAudioMuted(): Boolean = TODO("Not yet implemented") override fun isVideoMuted(): Boolean = TODO("Not yet implemented") override fun getRegion(): String = TODO("Not yet implemented") override fun getStatsId(): String = TODO("Not yet implemented") var idle: Boolean = true var healthy: Boolean = true init { detector.processMemberPresence(this) } fun setStatus(idle: Boolean, healthy: Boolean) { this.idle = idle this.healthy = healthy detector.processMemberPresence(this) } override fun getOccupantJid(): EntityFullJid = jid_ override fun getPresence(): Presence = mockk { every { getExtensionElement(JibriStatusPacketExt.ELEMENT, JibriStatusPacketExt.NAMESPACE) } answers { JibriStatusPacketExt().apply { healthStatus = HealthStatusPacketExt().apply { status = if (healthy) HEALTHY else UNHEALTHY } busyStatus = JibriBusyStatusPacketExt().apply { setAttribute("status", if (idle) "idle" else "busy") } } } } }
apache-2.0
16d86f0ab79884a8d0b2c0af1a08c2a7
40.836158
118
0.684267
4.463532
false
false
false
false
Ribesg/anko
dsl/testData/functional/support-v4/LayoutsTest.kt
2
11200
private val defaultInit: Any.() -> Unit = {} open class _FragmentTabHost(ctx: Context): android.support.v4.app.FragmentTabHost(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.widget.FrameLayout.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _ViewPager(ctx: Context): android.support.v4.view.ViewPager(ctx) { fun <T: View> T.lparams( init: android.support.v4.view.ViewPager.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v4.view.ViewPager.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( context: android.content.Context?, attrs: android.util.AttributeSet?, init: android.support.v4.view.ViewPager.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v4.view.ViewPager.LayoutParams(context!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } } open class _DrawerLayout(ctx: Context): android.support.v4.widget.DrawerLayout(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.support.v4.widget.DrawerLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v4.widget.DrawerLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.support.v4.widget.DrawerLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v4.widget.DrawerLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: android.support.v4.widget.DrawerLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v4.widget.DrawerLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.support.v4.widget.DrawerLayout.LayoutParams?, init: android.support.v4.widget.DrawerLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v4.widget.DrawerLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.support.v4.widget.DrawerLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v4.widget.DrawerLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.support.v4.widget.DrawerLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v4.widget.DrawerLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _NestedScrollView(ctx: Context): android.support.v4.widget.NestedScrollView(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.widget.FrameLayout.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _SlidingPaneLayout(ctx: Context): android.support.v4.widget.SlidingPaneLayout(ctx) { fun <T: View> T.lparams( init: android.support.v4.widget.SlidingPaneLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v4.widget.SlidingPaneLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.support.v4.widget.SlidingPaneLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v4.widget.SlidingPaneLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.support.v4.widget.SlidingPaneLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v4.widget.SlidingPaneLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.support.v4.widget.SlidingPaneLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v4.widget.SlidingPaneLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.support.v4.widget.SlidingPaneLayout.LayoutParams?, init: android.support.v4.widget.SlidingPaneLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v4.widget.SlidingPaneLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.support.v4.widget.SlidingPaneLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v4.widget.SlidingPaneLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } }
apache-2.0
4c95ad39b4fd91b94312dd0c8c007e21
37.757785
102
0.644554
4.530744
false
false
false
false
eviltak/adb-nmap
src/main/kotlin/net/eviltak/adbnmap/net/protocol/messages/AdbTransportMessage.kt
1
3159
/* * adb-nmap: An ADB network device discovery and connection library * Copyright (C) 2017-present Arav Singhal and adb-nmap contributors * * 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. * * The full license can be found in LICENSE.md. */ package net.eviltak.adbnmap.net.protocol.messages import java.nio.ByteBuffer import java.nio.ByteOrder /** * Represents a message used for communication between the ADB server and remote device adbd daemon via the * ADB transport protocol. */ class AdbTransportMessage private constructor(val command: Int, val arg0: Int, val arg1: Int, val dataLength: Int, val dataChecksum: Int, val magic: Int, val payload: String) : Message { /** * The various commands that can be sent via the ADB transport protocol. */ enum class Command(val intValue: Int) { SYNC(0x434e5953), CNXN(0x4e584e43), AUTH(0x48545541), OPEN(0x4e45504f), OKAY(0x59414b4f), CLSE(0x45534c43), WRTE(0x45545257) } companion object { /** * The header size in bytes. */ const val HEADER_SIZE = 24 /** * Checks whether the data in [byteArray] represents an [AdbTransportMessage] or not. * The data in [byteArray] must be stored in little endian format. * * @return true if the data in [byteArray] is a valid representation of an [AdbTransportMessage], * else false. */ fun representsTransportMessage(byteArray: ByteArray): Boolean { val byteBuffer = ByteBuffer.wrap(byteArray).order(ByteOrder.LITTLE_ENDIAN) val command = byteBuffer.int // Read last integer of header byteBuffer.position(AdbTransportMessage.HEADER_SIZE - 4) val magic = byteBuffer.int return Command.values().any { it.intValue == command } && (command xor magic == -1) } } constructor(command: Command, arg0: Int, arg1: Int, payload: String) : this(command.intValue, arg0, arg1, payload.length, 0, command.intValue xor -1, payload) /** * Encodes the message into a byte array. * * @return The resulting byte array. */ override fun toByteArray(): ByteArray { val byteBuffer = ByteBuffer.allocate(HEADER_SIZE + dataLength).order(ByteOrder.LITTLE_ENDIAN) byteBuffer .putInt(command) .putInt(arg0) .putInt(arg1) .putInt(dataLength) .putInt(dataChecksum) .putInt(magic) .put(payload.toByteArray(Charsets.US_ASCII)) return byteBuffer.array() } }
gpl-3.0
d969065a52aec18b737361c2bdb57c23
32.967742
107
0.640076
4.240268
false
false
false
false
deskchanproject/DeskChanJava
src/main/kotlin/info/deskchan/MessageData/GUI/SetSprite.kt
2
2038
package info.deskchan.MessageData.GUI import info.deskchan.core.MessageData import info.deskchan.core.Path /** * Set sprite state. You can show your own custom sprites and animate them. * * @property id System id of sprite (will be transformed to "sender-id") * @property type Type of action to perform towards sprite, CREATE by default * * @property animations Character animations * @property posX X coord of sprite, in pixels * @property posY Y coord of sprite, in pixels * @property scaleX Horizontal scale of sprite * @property scaleY Vertical scale of sprite * @property rotation Rotation of sprite * @property draggable Can be dragged, True by default **/ @MessageData.Tag("gui:set-sprite") class SetSprite : MessageData { enum class SpriteActionType { CREATE, SHOW, HIDE, DELETE, ANIMATE, DROP_ANIMATION } val id: String private var type: String = "CREATE" var posX: Int? = null var posY: Int? = null var scaleX: Float? = null var scaleY: Float? = null var rotation: Float? = null var draggable: Boolean? = null var animations: List<Animation>? = null fun getActionType() = SpriteActionType.valueOf(type.toUpperCase()) fun setActionType(value: SpriteActionType){ type = value.toString() } constructor(id: String, type: SpriteActionType){ this.id = id setActionType(type) } open class Animation : MessageData { var next: Path? = null var scalingX: Float? = null get() = field?: 0F var scalingY: Float? = null get() = field?: 0F var movingX: Float? = null get() = field?: 0F var movingY: Float? = null get() = field?: 0F // var movingZ = 0f var rotation: Float? = null get() = field?: 0F var smooth: Boolean? = null get() = field?: false var opacity: Float? = null get() = field?: 0F var delay: Long? = null get() = field?: 200L } }
lgpl-3.0
cf75e86d316fa02c1b50e632ddf91265
28.128571
77
0.623651
4.167689
false
false
false
false
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/model/parsers/AccountRangeJsonParser.kt
1
2046
package com.stripe.android.model.parsers import com.stripe.android.core.model.StripeJsonUtils import com.stripe.android.core.model.parsers.ModelJsonParser import com.stripe.android.model.AccountRange import com.stripe.android.model.BinRange import org.json.JSONObject internal class AccountRangeJsonParser : ModelJsonParser<AccountRange> { override fun parse(json: JSONObject): AccountRange? { val accountRangeHigh = StripeJsonUtils.optString(json, FIELD_ACCOUNT_RANGE_HIGH) val accountRangeLow = StripeJsonUtils.optString(json, FIELD_ACCOUNT_RANGE_LOW) val panLength = StripeJsonUtils.optInteger(json, FIELD_PAN_LENGTH) val brandInfo = StripeJsonUtils.optString(json, FIELD_BRAND).let { brandName -> AccountRange.BrandInfo.values().firstOrNull { it.brandName == brandName } } return if (accountRangeHigh != null && accountRangeLow != null && panLength != null && brandInfo != null ) { AccountRange( binRange = BinRange(accountRangeLow, accountRangeHigh), panLength = panLength, brandInfo = brandInfo, country = StripeJsonUtils.optString(json, FIELD_COUNTRY) ) } else { null } } fun serialize(accountRange: AccountRange): JSONObject { return JSONObject() .put(FIELD_ACCOUNT_RANGE_LOW, accountRange.binRange.low) .put(FIELD_ACCOUNT_RANGE_HIGH, accountRange.binRange.high) .put(FIELD_PAN_LENGTH, accountRange.panLength) .put(FIELD_BRAND, accountRange.brandInfo.brandName) .put(FIELD_COUNTRY, accountRange.country) } private companion object { const val FIELD_ACCOUNT_RANGE_HIGH = "account_range_high" const val FIELD_ACCOUNT_RANGE_LOW = "account_range_low" const val FIELD_PAN_LENGTH = "pan_length" const val FIELD_BRAND = "brand" const val FIELD_COUNTRY = "country" } }
mit
0b8d5481a559a1fc744f5a9c27a0264e
39.117647
89
0.64956
4.381156
false
false
false
false
UnknownJoe796/ponderize
app/src/main/java/com/ivieleague/ponderize/vc/ChapterVC.kt
1
5034
package com.ivieleague.ponderize.vc import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.graphics.drawable.LayerDrawable import android.support.v4.content.ContextCompat import android.view.Gravity import android.view.View import android.widget.TextView import com.ivieleague.ponderize.model.Chapter import com.ivieleague.ponderize.model.Verse import com.ivieleague.ponderize.model.title import com.ivieleague.ponderize.styleDefault import com.ivieleague.ponderize.styleHeader import com.ivieleague.ponderize.styleItem import com.lightningkite.kotlincomponents.adapter.LightningAdapter import com.lightningkite.kotlincomponents.alpha import com.lightningkite.kotlincomponents.observable.KObservable import com.lightningkite.kotlincomponents.observable.bind import com.lightningkite.kotlincomponents.selectableItemBackgroundResource import com.lightningkite.kotlincomponents.verticalLayout import com.lightningkite.kotlincomponents.viewcontroller.StandardViewController import com.lightningkite.kotlincomponents.viewcontroller.containers.VCStack import com.lightningkite.kotlincomponents.viewcontroller.implementations.VCActivity import org.jetbrains.anko.* import java.util.* /** * Created by josep on 10/4/2015. */ class ChapterVC(val stack: VCStack, val chapter: Chapter, val onResult: (ArrayList<Verse>) -> Unit) : StandardViewController() { public val versesBond: KObservable<ArrayList<Verse>> = KObservable(ArrayList()) public var verses: ArrayList<Verse> by versesBond override fun makeView(activity: VCActivity): View = verticalLayout(activity) { gravity = Gravity.CENTER textView(chapter.title) { styleHeader() }.lparams(wrapContent, wrapContent) listView { adapter = LightningAdapter(chapter.verses) { itemObs -> TextView(context).apply { styleItem() bind(itemObs) { text = it.verse.toString() + ") " + it.text if (verses.contains(it)) { val selDraw = ContextCompat.getDrawable(context, selectableItemBackgroundResource) background = LayerDrawable(arrayOf(selDraw, ColorDrawable(Color.WHITE.alpha(.25f)))) } else { backgroundResource = selectableItemBackgroundResource } } bind(versesBond) { if (it.contains(itemObs.value)) { val selDraw = ContextCompat.getDrawable(context, selectableItemBackgroundResource) background = LayerDrawable(arrayOf(selDraw, ColorDrawable(Color.WHITE.alpha(.25f)))) } else { backgroundResource = selectableItemBackgroundResource } } onClick { if (verses.contains(itemObs.value)) { verses.remove(itemObs.value) versesBond.update() } else { val index = verses.indexOfFirst { itemObs.value.verse < it.verse } if (index == -1) verses.add(itemObs.value) else verses.add(index, itemObs.value) versesBond.update() } } } } }.lparams(matchParent, 0, 1f) textView { styleDefault() gravity = Gravity.CENTER bind(versesBond) { text = it.title } }.lparams(matchParent, wrapContent) linearLayout { button { styleDefault() bind(versesBond) { if (it.size <= 0) { isEnabled = false text = "Select a verse..." } else if (it.size == 1) { isEnabled = true text = "Use this verse" } else { isEnabled = true text = "Use these verses" } } onClick { if (verses.size >= 1) { onResult(verses) stack.back({ it is MainVC }) } } }.lparams(0, wrapContent, 1f) button("Clear") { styleDefault() bind(versesBond) { if (it.size == 0) isEnabled = false else isEnabled = true } onClick { verses.clear() versesBond.update() } }.lparams(wrapContent, wrapContent) }.lparams(matchParent, wrapContent) } }
mit
daf8fa91ba0268cb465900e08a1557d6
39.28
128
0.54271
5.587125
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/sensors/modules/DeviceMotionModule.kt
2
9060
package abi43_0_0.expo.modules.sensors.modules import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener2 import android.hardware.SensorManager import android.os.Bundle import android.view.Choreographer import android.view.Surface import android.view.WindowManager import abi43_0_0.expo.modules.interfaces.sensors.SensorServiceInterface import abi43_0_0.expo.modules.interfaces.sensors.SensorServiceSubscriptionInterface import abi43_0_0.expo.modules.interfaces.sensors.services.AccelerometerServiceInterface import abi43_0_0.expo.modules.interfaces.sensors.services.GravitySensorServiceInterface import abi43_0_0.expo.modules.interfaces.sensors.services.GyroscopeServiceInterface import abi43_0_0.expo.modules.interfaces.sensors.services.LinearAccelerationSensorServiceInterface import abi43_0_0.expo.modules.interfaces.sensors.services.RotationVectorSensorServiceInterface import abi43_0_0.expo.modules.core.ExportedModule import abi43_0_0.expo.modules.core.ModuleRegistry import abi43_0_0.expo.modules.core.Promise import abi43_0_0.expo.modules.core.interfaces.ExpoMethod import abi43_0_0.expo.modules.core.interfaces.services.EventEmitter import abi43_0_0.expo.modules.core.interfaces.services.UIManager class DeviceMotionModule(context: Context?) : ExportedModule(context), SensorEventListener2 { private var mLastUpdate: Long = 0 private var mUpdateInterval = 1.0f / 60.0f private val mRotationMatrix = FloatArray(9) private val mRotationResult = FloatArray(3) private var mAccelerationEvent: SensorEvent? = null private var mAccelerationIncludingGravityEvent: SensorEvent? = null private var mRotationEvent: SensorEvent? = null private var mRotationRateEvent: SensorEvent? = null private var mGravityEvent: SensorEvent? = null private lateinit var mServiceSubscriptions: MutableList<SensorServiceSubscriptionInterface> private lateinit var mUIManager: UIManager private lateinit var mModuleRegistry: ModuleRegistry private val mCurrentFrameCallback: ScheduleDispatchFrameCallback = ScheduleDispatchFrameCallback() private val mDispatchEventRunnable = DispatchEventRunnable() private lateinit var mEventEmitter: EventEmitter override fun getName(): String = "ExponentDeviceMotion" override fun getConstants(): Map<String, Any> { // Gravity on the planet this module supports (currently just Earth) represented as m/s^2. return mapOf(Pair("Gravity", 9.80665)) } @ExpoMethod fun setUpdateInterval(updateInterval: Int, promise: Promise) { mUpdateInterval = updateInterval.toFloat() promise.resolve(null) } @ExpoMethod fun startObserving(promise: Promise) { if (!this::mServiceSubscriptions.isInitialized) { mServiceSubscriptions = ArrayList() for (kernelService in getSensorKernelServices()) { val subscription = kernelService.createSubscriptionForListener(this) // We want handle update interval on our own, // because we need to coordinate updates from multiple sensor services. subscription.updateInterval = 0 mServiceSubscriptions.add(subscription) } } mServiceSubscriptions.forEach { it.start() } promise.resolve(null) } @ExpoMethod fun stopObserving(promise: Promise) { mUIManager.runOnUiQueueThread { mServiceSubscriptions.forEach { it.stop() } mCurrentFrameCallback.stop() promise.resolve(null) } } @ExpoMethod fun isAvailableAsync(promise: Promise) { val mSensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager val sensorTypes = arrayListOf(Sensor.TYPE_GYROSCOPE, Sensor.TYPE_ACCELEROMETER, Sensor.TYPE_LINEAR_ACCELERATION, Sensor.TYPE_ROTATION_VECTOR, Sensor.TYPE_GRAVITY) for (type in sensorTypes) { if (mSensorManager.getDefaultSensor(type!!) == null) { promise.resolve(false) return } } promise.resolve(true) } override fun onCreate(moduleRegistry: ModuleRegistry) { mEventEmitter = moduleRegistry.getModule(EventEmitter::class.java) mUIManager = moduleRegistry.getModule(UIManager::class.java) mModuleRegistry = moduleRegistry } private fun getSensorKernelServices(): List<SensorServiceInterface> { return arrayListOf( mModuleRegistry.getModule(GyroscopeServiceInterface::class.java), mModuleRegistry.getModule(LinearAccelerationSensorServiceInterface::class.java), mModuleRegistry.getModule(AccelerometerServiceInterface::class.java), mModuleRegistry.getModule(RotationVectorSensorServiceInterface::class.java), mModuleRegistry.getModule(GravitySensorServiceInterface::class.java) ) } override fun onSensorChanged(sensorEvent: SensorEvent) { val sensor = sensorEvent.sensor when (sensor.type) { Sensor.TYPE_GYROSCOPE -> mRotationRateEvent = sensorEvent Sensor.TYPE_ACCELEROMETER -> mAccelerationIncludingGravityEvent = sensorEvent Sensor.TYPE_LINEAR_ACCELERATION -> mAccelerationEvent = sensorEvent Sensor.TYPE_ROTATION_VECTOR -> mRotationEvent = sensorEvent Sensor.TYPE_GRAVITY -> mGravityEvent = sensorEvent } mCurrentFrameCallback.maybePostFromNonUI() } override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) = Unit override fun onFlushCompleted(sensor: Sensor) = Unit private inner class ScheduleDispatchFrameCallback : Choreographer.FrameCallback { @Volatile private var mIsPosted = false private var mShouldStop = false override fun doFrame(frameTimeNanos: Long) { if (mShouldStop) { mIsPosted = false } else { post() } val curTime = System.currentTimeMillis() if (curTime - mLastUpdate > mUpdateInterval) { mUIManager.runOnClientCodeQueueThread(mDispatchEventRunnable) mLastUpdate = curTime } } fun stop() { mShouldStop = true } fun maybePost() { if (!mIsPosted) { mIsPosted = true post() } } private fun post() { Choreographer.getInstance().postFrameCallback(mCurrentFrameCallback) } fun maybePostFromNonUI() { if (mIsPosted) { return } mUIManager.runOnUiQueueThread { maybePost() } } } private inner class DispatchEventRunnable : Runnable { override fun run() { mEventEmitter.emit("deviceMotionDidUpdate", eventsToMap()) } } private fun eventsToMap(): Bundle { val map = Bundle() var interval = 0.0 if (mAccelerationEvent != null) { map.putBundle( "acceleration", Bundle().apply { putDouble("x", mAccelerationEvent!!.values[0].toDouble()) putDouble("y", mAccelerationEvent!!.values[1].toDouble()) putDouble("z", mAccelerationEvent!!.values[2].toDouble()) } ) interval = mAccelerationEvent!!.timestamp.toDouble() } if (mAccelerationIncludingGravityEvent != null && mGravityEvent != null) { map.putBundle( "accelerationIncludingGravity", Bundle().apply { putDouble("x", (mAccelerationIncludingGravityEvent!!.values[0] - 2 * mGravityEvent!!.values[0]).toDouble()) putDouble("y", (mAccelerationIncludingGravityEvent!!.values[1] - 2 * mGravityEvent!!.values[1]).toDouble()) putDouble("z", (mAccelerationIncludingGravityEvent!!.values[2] - 2 * mGravityEvent!!.values[2]).toDouble()) } ) interval = mAccelerationIncludingGravityEvent!!.timestamp.toDouble() } if (mRotationRateEvent != null) { map.putBundle( "rotationRate", Bundle().apply { putDouble("alpha", Math.toDegrees(mRotationRateEvent!!.values[0].toDouble())) putDouble("beta", Math.toDegrees(mRotationRateEvent!!.values[1].toDouble())) putDouble("gamma", Math.toDegrees(mRotationRateEvent!!.values[2].toDouble())) } ) interval = mRotationRateEvent!!.timestamp.toDouble() } if (mRotationEvent != null) { SensorManager.getRotationMatrixFromVector(mRotationMatrix, mRotationEvent!!.values) SensorManager.getOrientation(mRotationMatrix, mRotationResult) map.putBundle( "rotation", Bundle().apply { putDouble("alpha", (-mRotationResult[0]).toDouble()) putDouble("beta", (-mRotationResult[1]).toDouble()) putDouble("gamma", mRotationResult[2].toDouble()) } ) interval = mRotationEvent!!.timestamp.toDouble() } map.putDouble("interval", interval) map.putInt("orientation", getOrientation()) return map } private fun getOrientation(): Int { val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager? if (windowManager != null) { when (windowManager.defaultDisplay.rotation) { Surface.ROTATION_0 -> return 0 Surface.ROTATION_90 -> return 90 Surface.ROTATION_180 -> return 180 Surface.ROTATION_270 -> return -90 else -> { } } } return 0 } }
bsd-3-clause
56926eb3dec007bcfd56a112fdb68152
36.438017
166
0.718764
4.532266
false
false
false
false
AndroidX/androidx
room/room-runtime/src/main/java/androidx/room/util/RelationUtil.kt
3
4803
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("RelationUtil") @file:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) package androidx.room.util import androidx.annotation.RestrictTo import androidx.collection.ArrayMap import androidx.collection.LongSparseArray import androidx.room.RoomDatabase /** * Utility function used in generated code to recursively fetch relationships when the amount of * keys exceed [RoomDatabase.MAX_BIND_PARAMETER_CNT]. * * @param map - The map containing the relationship keys to fill-in. * @param isRelationCollection - True if [V] is a [Collection] which means it is non null. * @param fetchBlock - A lambda for calling the generated _fetchRelationship function. */ fun <K : Any, V> recursiveFetchHashMap( map: HashMap<K, V>, isRelationCollection: Boolean, fetchBlock: (HashMap<K, V>) -> Unit ) { val tmpMap = HashMap<K, V>(RoomDatabase.MAX_BIND_PARAMETER_CNT) var count = 0 for (key in map.keys) { // Safe because `V` is a nullable type arg when isRelationCollection == false and vice versa @Suppress("UNCHECKED_CAST") if (isRelationCollection) { tmpMap[key] = map[key] as V } else { tmpMap[key] = null as V } count++ if (count == RoomDatabase.MAX_BIND_PARAMETER_CNT) { // recursively load that batch fetchBlock(tmpMap) // for non collection relation, put the loaded batch in the original map, // not needed when dealing with collections since references are passed if (!isRelationCollection) { map.putAll(tmpMap) } tmpMap.clear() count = 0 } } if (count > 0) { // load the last batch fetchBlock(tmpMap) // for non collection relation, put the last batch in the original map if (!isRelationCollection) { map.putAll(tmpMap) } } } /** * Same as [recursiveFetchHashMap] but for [LongSparseArray]. */ fun <V> recursiveFetchLongSparseArray( map: LongSparseArray<V>, isRelationCollection: Boolean, fetchBlock: (LongSparseArray<V>) -> Unit ) { val tmpMap = LongSparseArray<V>(RoomDatabase.MAX_BIND_PARAMETER_CNT) var count = 0 var mapIndex = 0 val limit = map.size() while (mapIndex < limit) { if (isRelationCollection) { tmpMap.put(map.keyAt(mapIndex), map.valueAt(mapIndex)) } else { // Safe because `V` is a nullable type arg when isRelationCollection == false @Suppress("UNCHECKED_CAST") tmpMap.put(map.keyAt(mapIndex), null as V) } mapIndex++ count++ if (count == RoomDatabase.MAX_BIND_PARAMETER_CNT) { fetchBlock(tmpMap) if (!isRelationCollection) { map.putAll(tmpMap) } tmpMap.clear() count = 0 } } if (count > 0) { fetchBlock(tmpMap) if (!isRelationCollection) { map.putAll(tmpMap) } } } /** * Same as [recursiveFetchHashMap] but for [ArrayMap]. */ fun <K : Any, V> recursiveFetchArrayMap( map: ArrayMap<K, V>, isRelationCollection: Boolean, fetchBlock: (ArrayMap<K, V>) -> Unit ) { val tmpMap = ArrayMap<K, V>(RoomDatabase.MAX_BIND_PARAMETER_CNT) var count = 0 var mapIndex = 0 val limit = map.size while (mapIndex < limit) { if (isRelationCollection) { tmpMap[map.keyAt(mapIndex)] = map.valueAt(mapIndex) } else { tmpMap[map.keyAt(mapIndex)] = null } mapIndex++ count++ if (count == RoomDatabase.MAX_BIND_PARAMETER_CNT) { fetchBlock(tmpMap) if (!isRelationCollection) { // Cast needed to disambiguate from putAll(SimpleArrayMap) map.putAll(tmpMap as Map<K, V>) } tmpMap.clear() count = 0 } } if (count > 0) { fetchBlock(tmpMap) if (!isRelationCollection) { // Cast needed to disambiguate from putAll(SimpleArrayMap) map.putAll(tmpMap as Map<K, V>) } } }
apache-2.0
cbf1d3659ca1c66d3a2ae0d4f0cb5805
31.234899
100
0.613158
4.140517
false
false
false
false
codeka/wwmmo
client/src/main/kotlin/au/com/codeka/warworlds/client/game/welcome/CreateEmpireLayout.kt
1
1924
package au.com.codeka.warworlds.client.game.welcome import android.content.Context import android.view.View import android.widget.Button import android.widget.EditText import android.widget.RelativeLayout import android.widget.TextView import au.com.codeka.warworlds.client.App import au.com.codeka.warworlds.client.R import au.com.codeka.warworlds.client.util.ViewBackgroundGenerator.setBackground /** Layout for [CreateEmpireScreen]. */ class CreateEmpireLayout(context: Context?, private val callbacks: Callbacks) : RelativeLayout(context) { interface Callbacks { fun onSwitchAccountClick() fun onDoneClick(empireName: String?) } private val empireName: EditText private val switchAccountButton: Button init { View.inflate(context, R.layout.create_empire, this) empireName = findViewById(R.id.empire_name) switchAccountButton = findViewById(R.id.switch_account_btn) setBackground(this) findViewById<View>(R.id.next_btn).setOnClickListener { callbacks.onDoneClick(empireName.text.toString()) } findViewById<View>(R.id.switch_account_btn).setOnClickListener { callbacks.onSwitchAccountClick() } // If you're already signed in, no need to switch accounts (we'll associate this empire with // the account you're signed in as). if (App.auth.isSignedIn) { switchAccountButton.visibility = View.GONE } } fun showSpinner() { empireName.visibility = View.GONE switchAccountButton.visibility = View.GONE findViewById<View>(R.id.progress).visibility = View.VISIBLE } /** Hide the spinner again (so the user can try again) but show an error message as well. */ fun showError(msg: String?) { empireName.visibility = View.VISIBLE switchAccountButton.visibility = View.VISIBLE findViewById<View>(R.id.progress).visibility = View.GONE (findViewById<View>(R.id.setup_name) as TextView).text = msg } }
mit
4ef31f1019fd88d0cc7ebeafe86d3e42
32.754386
96
0.744802
4.025105
false
false
false
false
AndroidX/androidx
fragment/fragment/src/androidTest/java/androidx/fragment/app/TrackingTransition.kt
3
2596
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.fragment.app import android.graphics.Rect import android.transition.Transition import android.transition.TransitionValues import android.view.View import android.view.ViewGroup import androidx.annotation.RequiresApi /** * A transition that tracks which targets are applied to it. * It will assume any target that it applies to will have differences * between the start and end state, regardless of the differences * that actually exist. In other words, it doesn't actually check * any size or position differences or any other property of the view. * It just records the difference. * * * Both start and end value Views are recorded, but no actual animation * is created. */ @RequiresApi(21) class TrackingTransition : Transition(), TargetTracking { override val enteringTargets = mutableListOf<View>() override val exitingTargets = mutableListOf<View>() override val capturedEpicenter: Rect = Rect() override fun getTransitionProperties(): Array<String> { return PROPS } override fun captureStartValues(transitionValues: TransitionValues) { transitionValues.values[PROP] = 0 } override fun captureEndValues(transitionValues: TransitionValues) { transitionValues.values[PROP] = 1 } override fun createAnimator( sceneRoot: ViewGroup, startValues: TransitionValues?, endValues: TransitionValues? ) = null.also { if (startValues != null) { exitingTargets.add(startValues.view) } if (endValues != null) { enteringTargets.add(endValues.view) } if (epicenter != null) { capturedEpicenter.set(Rect(epicenter)) } } override fun clearTargets() { enteringTargets.clear() exitingTargets.clear() capturedEpicenter.set(Rect()) } companion object { private val PROP = "tracking:prop" private val PROPS = arrayOf(PROP) } }
apache-2.0
546650b9a3951b63dbdaa4dea907b9d4
31.049383
75
0.701464
4.460481
false
false
false
false
satamas/fortran-plugin
src/main/java/org/jetbrains/fortran/lang/psi/mixin/FortranModuleImplMixin.kt
1
2239
package org.jetbrains.fortran.lang.psi.mixin import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.fortran.lang.psi.* import org.jetbrains.fortran.lang.psi.ext.FortranNamedElement import org.jetbrains.fortran.lang.psi.impl.FortranProgramUnitImpl import org.jetbrains.fortran.lang.stubs.FortranProgramUnitStub abstract class FortranModuleImplMixin : FortranProgramUnitImpl, FortranModule { constructor(node: ASTNode) : super(node) constructor(stub: FortranProgramUnitStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override fun getNameIdentifier(): PsiElement? = moduleStmt.entityDecl override val variables: List<FortranNamedElement> get() = PsiTreeUtil.getStubChildrenOfTypeAsList(block, FortranTypeDeclarationStmt::class.java) .flatMap { PsiTreeUtil.getStubChildrenOfTypeAsList(it, FortranEntityDecl::class.java) } override val unit: FortranNamedElement? get() { val moduleStmt = PsiTreeUtil.getStubChildOfType(this, FortranModuleStmt::class.java) return PsiTreeUtil.getStubChildOfType(moduleStmt, FortranEntityDecl::class.java) } override val subprograms: List<FortranNamedElement> get() { val programUnits = PsiTreeUtil.getStubChildrenOfTypeAsList(moduleSubprogramPart, FortranProgramUnit::class.java) val functionsDeclarations = programUnits .filterIsInstance(FortranFunctionSubprogram::class.java) .flatMap { function -> function.variables.filter { function.unit?.name.equals(it.name, true) } } return programUnits.mapNotNull { it.unit } + functionsDeclarations } override val usedModules: List<FortranDataPath> get() = PsiTreeUtil.getStubChildrenOfTypeAsList(block, FortranUseStmt::class.java) .mapNotNull { it.dataPath } override val types: List<FortranNamedElement> get() = PsiTreeUtil.getStubChildrenOfTypeAsList(block, FortranDerivedTypeDef::class.java) .mapNotNull { it.derivedTypeStmt.typeDecl } }
apache-2.0
df0a62cc48ebec16fcf1ab4a448b8988
45.666667
124
0.72577
4.899344
false
false
false
false
android/enterprise-samples
ManagedConfigurations/app/src/main/java/com/example/android/managedconfigurations/MainActivity.kt
1
3983
/* * Copyright 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.managedconfigurations import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.ViewAnimator import com.example.android.managedconfigurations.databinding.ActivityMainBinding import com.example.android.common.activities.SampleActivityBase import com.example.android.common.logger.Log import com.example.android.common.logger.LogFragment import com.example.android.common.logger.LogWrapper import com.example.android.common.logger.MessageOnlyLogFilter /** * A simple launcher activity containing a summary sample description, sample log and a custom * [Fragment] which can display a view. * * * For devices with displays with a width of 720dp or greater, the sample log is always visible, * on other devices it's visibility is controlled by an item on the Action Bar. */ class MainActivity : SampleActivityBase() { // Whether the Log Fragment is currently shown private var logShown = false private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) if (savedInstanceState == null) { val transaction = supportFragmentManager.beginTransaction() val fragment = ManagedConfigurationsFragment() transaction.replace(R.id.sample_content_fragment, fragment) transaction.commit() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) return true } override fun onPrepareOptionsMenu(menu: Menu): Boolean { val logToggle = menu.findItem(R.id.menu_toggle_log) logToggle.isVisible = binding.sampleOutput is ViewAnimator logToggle.setTitle(if (logShown) R.string.sample_hide_log else R.string.sample_show_log) return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.menu_toggle_log -> { logShown = !logShown val output = binding.sampleOutput as ViewAnimator output.displayedChild = if (logShown) { 1 } else { 0 } invalidateOptionsMenu() true } else -> super.onOptionsItemSelected(item) } /** * Create a chain of targets that will receive log data */ override fun initializeLogging() { // Wraps Android's native log framework. val logWrapper = LogWrapper() // Using Log, front-end to the logging chain, emulates android.util.log method signatures. Log.setLogNode(logWrapper) // Filter strips out everything except the message text. val msgFilter = MessageOnlyLogFilter() logWrapper.next = msgFilter // On screen logging via a fragment with a TextView. val logFragment = supportFragmentManager .findFragmentById(R.id.log_fragment) as LogFragment? logFragment?.let { msgFilter.next = logFragment.logView Log.i(TAG, "Ready") } } companion object { const val TAG = "MainActivity" } }
apache-2.0
cb8fea40544208af0cfc8567052876ff
35.87963
98
0.681145
4.758662
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/shops/PurchaseDialogGemsContent.kt
1
1059
package com.habitrpg.android.habitica.ui.views.shops import android.content.Context import android.widget.ImageView import android.widget.TextView import com.habitrpg.android.habitica.databinding.DialogPurchaseGemsBinding import com.habitrpg.android.habitica.extensions.asDrawable import com.habitrpg.android.habitica.extensions.layoutInflater import com.habitrpg.android.habitica.models.shops.ShopItem import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper internal class PurchaseDialogGemsContent(context: Context) : PurchaseDialogContent(context) { internal val binding = DialogPurchaseGemsBinding.inflate(context.layoutInflater, this) override val imageView: ImageView get() = binding.imageView override val titleTextView: TextView get() = binding.titleTextView init { binding.stepperView.iconDrawable = HabiticaIconsHelper.imageOfGem().asDrawable(context.resources) } override fun setItem(item: ShopItem) { super.setItem(item) binding.notesTextView.text = item.notes } }
gpl-3.0
b16d281eba2185158931e73f9579b774
38.222222
105
0.791313
4.624454
false
false
false
false
esofthead/mycollab
mycollab-services/src/main/java/com/mycollab/common/service/impl/OptionValServiceImpl.kt
3
6341
/** * Copyright © MyCollab * * 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.mycollab.common.service.impl import com.mycollab.common.dao.OptionValMapper import com.mycollab.common.domain.OptionVal import com.mycollab.common.domain.OptionValExample import com.mycollab.common.i18n.OptionI18nEnum.StatusI18nEnum import com.mycollab.common.service.OptionValService import com.mycollab.core.UserInvalidInputException import com.mycollab.core.cache.CacheKey import com.mycollab.db.persistence.ICrudGenericDAO import com.mycollab.db.persistence.service.DefaultCrudService import com.mycollab.module.project.ProjectTypeConstants import com.mycollab.module.project.i18n.OptionI18nEnum.MilestoneStatus import org.springframework.jdbc.core.BatchPreparedStatementSetter import org.springframework.jdbc.core.JdbcTemplate import org.springframework.stereotype.Service import java.sql.PreparedStatement import java.sql.SQLException import java.time.LocalDateTime import javax.sql.DataSource /** * @author MyCollab Ltd * @since 5.1.1 */ @Service class OptionValServiceImpl(private val optionValMapper: OptionValMapper, private val dataSource: DataSource) : DefaultCrudService<Int, OptionVal>(), OptionValService { override val crudMapper: ICrudGenericDAO<Int, OptionVal> get() = optionValMapper as ICrudGenericDAO<Int, OptionVal> override fun findOptionVals(type: String, projectId: Int?, sAccountId: Int?): List<OptionVal> { val ex = OptionValExample() ex.createCriteria().andTypeEqualTo(type).andSaccountidEqualTo(sAccountId).andExtraidEqualTo(projectId) ex.orderByClause = "orderIndex ASC" ex.isDistinct = true return optionValMapper.selectByExampleWithBLOBs(ex) } override fun findOptionValsExcludeClosed(type: String, projectId: Int?, @CacheKey sAccountId: Int?): List<OptionVal> { val ex = OptionValExample() ex.createCriteria().andTypeEqualTo(type).andTypevalNotEqualTo(StatusI18nEnum.Closed.name) .andSaccountidEqualTo(sAccountId).andExtraidEqualTo(projectId) ex.orderByClause = "orderIndex ASC" ex.isDistinct = true return optionValMapper.selectByExampleWithBLOBs(ex) } override fun saveWithSession(record: OptionVal, username: String?): Int { checkSaveOrUpdateValid(record) return super.saveWithSession(record, username) } private fun checkSaveOrUpdateValid(record: OptionVal) { val typeVal = record.typeval if (java.lang.Boolean.TRUE == record.isdefault) { val ex = OptionValExample() ex.createCriteria().andTypeEqualTo(record.type).andTypevalEqualTo(typeVal) .andFieldgroupEqualTo(record.fieldgroup) .andSaccountidEqualTo(record.saccountid) if (optionValMapper.countByExample(ex) > 0) { throw UserInvalidInputException("There is already column name $typeVal") } } else { val ex = OptionValExample() ex.createCriteria().andTypeEqualTo(record.type).andTypevalEqualTo(typeVal) .andFieldgroupEqualTo(record.fieldgroup).andSaccountidEqualTo(record .saccountid).andIsdefaultEqualTo(java.lang.Boolean.FALSE) if (optionValMapper.countByExample(ex) > 0) { throw UserInvalidInputException("There is already column name $typeVal") } } } override fun massUpdateOptionIndexes(mapIndexes: List<Map<String, Int>>, sAccountId: Int?) { val jdbcTemplate = JdbcTemplate(dataSource) jdbcTemplate.batchUpdate("UPDATE `m_options` SET `orderIndex`=? WHERE `id`=?", object : BatchPreparedStatementSetter { @Throws(SQLException::class) override fun setValues(preparedStatement: PreparedStatement, i: Int) { preparedStatement.setInt(1, mapIndexes[i]["index"]!!) preparedStatement.setInt(2, mapIndexes[i]["id"]!!) } override fun getBatchSize(): Int = mapIndexes.size }) } override fun isExistedOptionVal(type: String, typeVal: String, fieldGroup: String, projectId: Int?, sAccountId: Int?): Boolean { val ex = OptionValExample() ex.createCriteria().andTypeEqualTo(type).andTypevalEqualTo(typeVal).andFieldgroupEqualTo(fieldGroup) .andSaccountidEqualTo(sAccountId).andExtraidEqualTo(projectId) return optionValMapper.countByExample(ex) > 0 } override fun createDefaultOptions(sAccountId: Int?) { val option = OptionVal() option.createdtime = LocalDateTime.now() option.isdefault = true option.saccountid = sAccountId option.type = ProjectTypeConstants.TASK option.typeval = StatusI18nEnum.Open.name option.color = "fdde86" option.fieldgroup = "status" saveWithSession(option, null) option.typeval = StatusI18nEnum.InProgress.name option.id = null saveWithSession(option, null) option.typeval = StatusI18nEnum.Closed.name option.id = null saveWithSession(option, null) option.typeval = StatusI18nEnum.Pending.name option.id = null saveWithSession(option, null) option.type = ProjectTypeConstants.MILESTONE option.typeval = MilestoneStatus.Closed.name option.id = null saveWithSession(option, null) option.typeval = MilestoneStatus.InProgress.name option.id = null saveWithSession(option, null) option.typeval = MilestoneStatus.Future.name option.id = null saveWithSession(option, null) } }
agpl-3.0
f32ebd16a2f7697d99d13eaf114cb6b7
41.266667
132
0.702997
4.366391
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/cafeteria/details/CafeteriaMenusAdapter.kt
1
4092
package de.tum.`in`.tumcampusapp.component.ui.cafeteria.details import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.ui.cafeteria.FavoriteDishDao import de.tum.`in`.tumcampusapp.component.ui.cafeteria.model.CafeteriaMenu import de.tum.`in`.tumcampusapp.component.ui.cafeteria.model.CafeteriaPrices import de.tum.`in`.tumcampusapp.database.TcaDb import de.tum.`in`.tumcampusapp.utils.Utils import de.tum.`in`.tumcampusapp.utils.splitOnChanged class CafeteriaMenusAdapter( private val context: Context, private val isBigLayout: Boolean, private val onClickListener: (() -> Unit)? = null ) : RecyclerView.Adapter<CafeteriaMenusAdapter.ViewHolder>() { private val dao: FavoriteDishDao by lazy { TcaDb.getInstance(context).favoriteDishDao() } private val rolePrices: Map<String, String> by lazy { CafeteriaPrices.getRolePrices(context) } private val itemLayout: Int by lazy { if (isBigLayout) R.layout.card_price_line_big else R.layout.card_price_line } private val adapterItems = mutableListOf<CafeteriaMenuAdapterItem>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(viewType, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val viewEntity = adapterItems[position] viewEntity.bind(holder, onClickListener) } override fun getItemCount() = adapterItems.size fun update(menus: List<CafeteriaMenu>) { val newItems = menus .filter(this::shouldShowMenu) .splitOnChanged { it.typeLong } .map(this::createAdapterItemsForSection) .flatten() val diffResult = DiffUtil.calculateDiff(DiffUtilCallback(adapterItems, newItems)) adapterItems.clear() adapterItems += newItems diffResult.dispatchUpdatesTo(this) } private fun shouldShowMenu(menu: CafeteriaMenu): Boolean { val shouldShowMenuType = Utils.getSettingBool( context, "card_cafeteria_${menu.typeShort}", "tg" == menu.typeShort || "ae" == menu.typeShort ) return shouldShowMenuType || isBigLayout } private fun createAdapterItemsForSection( menus: List<CafeteriaMenu> ): List<CafeteriaMenuAdapterItem> { val header = CafeteriaMenuAdapterItem.Header(menus.first()) val items = menus.map { val rolePrice = rolePrices[it.typeLong] val isFavorite = dao.checkIfFavoriteDish(it.tag).isNotEmpty() CafeteriaMenuAdapterItem.Item(it, isFavorite, rolePrice, isBigLayout, dao) } return if (header.menu.typeLong.isNotBlank()) listOf(header) + items else items } override fun getItemViewType(position: Int): Int { return when (adapterItems[position]) { is CafeteriaMenuAdapterItem.Header -> R.layout.cafeteria_menu_header is CafeteriaMenuAdapterItem.Item -> itemLayout } } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) private class DiffUtilCallback( private val oldItems: List<CafeteriaMenuAdapterItem>, private val newItems: List<CafeteriaMenuAdapterItem> ) : DiffUtil.Callback() { override fun getOldListSize() = oldItems.size override fun getNewListSize() = newItems.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldItems[oldItemPosition].id == newItems[newItemPosition].id } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldItems[oldItemPosition] == newItems[newItemPosition] } } }
gpl-3.0
ac64be4dda2a54c22069c1612d0be011
35.535714
94
0.695259
4.692661
false
false
false
false
fredyw/leetcode
src/main/kotlin/leetcode/Problem2049.kt
1
1786
package leetcode /** * https://leetcode.com/problems/count-nodes-with-the-highest-score/ */ class Problem2049 { fun countHighestScoreNodes(parents: IntArray): Int { val root = buildTree(parents) val scores = mutableMapOf<Long, Int>() countHighestScore(parents.size, root, scores) var answer = 0 var maxScore = 0L for ((score, count) in scores) { if (score > maxScore) { maxScore = score answer = count } } return answer } data class Node(val value: Int, var left: Node? = null, var right: Node? = null) private fun buildTree(parents: IntArray): Node? { val nodes = Array(parents.size) { i -> Node(i) } var root: Node? = null for ((index, parentIndex) in parents.withIndex()) { if (parentIndex == -1) { root = nodes[0] } else { val parent = nodes[parentIndex] val child = nodes[index] if (parent.left == null) { parent.left = child } else { parent.right = child } } } return root } private fun countHighestScore(n: Int, root: Node?, scores: MutableMap<Long, Int>): Long { if (root == null) { return -1 } val left = countHighestScore(n, root.left, scores) + 1 val right = countHighestScore(n, root.right, scores) + 1 val score = (if (left == 0L) 1 else left) * (if (right == 0L) 1 else right) * (if (n - (left + right + 1) == 0L) 1 else n - (left + right + 1)) scores[score] = (scores[score] ?: 0) + 1 return left + right } }
mit
712921b22caa043f5e9f1732a395df43
31.472727
93
0.50224
4.086957
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/util/SphericalEarthMath.kt
1
24557
@file:Suppress("NonAsciiCharacters") package de.westnordost.streetcomplete.util import de.westnordost.osmapi.map.data.BoundingBox import de.westnordost.osmapi.map.data.LatLon import de.westnordost.osmapi.map.data.OsmLatLon import de.westnordost.streetcomplete.ktx.forEachLine import de.westnordost.streetcomplete.util.math.arcIntersection import de.westnordost.streetcomplete.util.math.toLatLon import de.westnordost.streetcomplete.util.math.toNormalOnSphere import kotlin.math.* /** Calculate stuff assuming a spherical Earth. The Earth is not spherical, but it is a good * approximation and totally sufficient for our use here. */ /** In meters. See https://en.wikipedia.org/wiki/Earth_radius#Mean_radius */ const val EARTH_RADIUS = 6371000.0 /** In meters. See https://en.wikipedia.org/wiki/Earth%27s_circumference */ const val EARTH_CIRCUMFERENCE = 40000000.0 /* --------------------------------- LatLon extension functions --------------------------------- */ /** * Return a bounding box that contains a circle with the given radius around this point. In * other words, it is a square centered at the given position and with a side length of radius*2. */ fun LatLon.enclosingBoundingBox(radius: Double, globeRadius: Double = EARTH_RADIUS): BoundingBox { val distance = sqrt(2.0) * radius val min = translate(distance, 225.0, globeRadius) val max = translate(distance, 45.0, globeRadius) return BoundingBox(min, max) } /** * Returns the initial bearing from this point another. * * If you take a globe and draw a line straight up to the north pole from this point and a second * line that connects this point and the given one, this is the angle between those two lines */ fun LatLon.initialBearingTo(pos: LatLon): Double { var bearing = initialBearing( latitude.toRadians(), longitude.toRadians(), pos.latitude.toRadians(), pos.longitude.toRadians() ).toDegrees() if (bearing < 0) bearing += 360.0 if (bearing >= 360) bearing -= 360.0 return bearing } /** * Returns the final bearing from one point to the other. * * If you take a globe and draw a line straight up to the north pole from the given point and a * second one that connects this point and the given point (and goes on straight after this), this * is the angle between those two lines */ fun LatLon.finalBearingTo(pos: LatLon): Double { var bearing = finalBearing( latitude.toRadians(), longitude.toRadians(), pos.latitude.toRadians(), pos.longitude.toRadians() ).toDegrees() if (bearing < 0) bearing += 360.0 if (bearing >= 360) bearing -= 360.0 return bearing } /** Returns the distance from this point to the other point */ fun LatLon.distanceTo(pos: LatLon, globeRadius: Double = EARTH_RADIUS): Double = angularDistance( latitude.toRadians(), longitude.toRadians(), pos.latitude.toRadians(), pos.longitude.toRadians() ) * globeRadius /** Returns a new point in the given distance and angle from the this point */ fun LatLon.translate(distance: Double, angle: Double, globeRadius: Double = EARTH_RADIUS): LatLon { val pair = translate( latitude.toRadians(), longitude.toRadians(), angle.toRadians(), distance / globeRadius ) return createTranslated(pair.first.toDegrees(), pair.second.toDegrees()) } /** Returns the shortest distance between this point and the great arc spanned by the two points. * The sign tells on which side of the great arc this point is */ fun LatLon.crossTrackDistanceTo(start: LatLon, end: LatLon, globeRadius: Double = EARTH_RADIUS): Double = crossTrackAngularDistance( start.latitude.toRadians(), start.longitude.toRadians(), end.latitude.toRadians(), end.longitude.toRadians(), latitude.toRadians(), longitude.toRadians() ) * globeRadius /** * Given the great arc spanned by the two given points, returns the distance of the start point to * the point on the great arc that is closest to this point. * The sign tells the direction of that point on the great arc seen from the start point. */ fun LatLon.alongTrackDistanceTo(start: LatLon, end: LatLon, globeRadius: Double = EARTH_RADIUS): Double = alongTrackAngularDistance( start.latitude.toRadians(), start.longitude.toRadians(), end.latitude.toRadians(), end.longitude.toRadians(), latitude.toRadians(), longitude.toRadians() ) * globeRadius /** Returns the shortest distance between this point and the arc between the given points */ fun LatLon.distanceToArc(start: LatLon, end: LatLon, globeRadius: Double = EARTH_RADIUS): Double = abs( angularDistanceToArc( start.latitude.toRadians(), start.longitude.toRadians(), end.latitude.toRadians(), end.longitude.toRadians(), latitude.toRadians(), longitude.toRadians() ) ) * globeRadius /** Returns the shortest distance between this point and the arcs between the given points */ fun LatLon.distanceToArcs(polyLine: List<LatLon>, globeRadius: Double = EARTH_RADIUS): Double { require(polyLine.isNotEmpty()) { "Polyline must not be empty" } if (polyLine.size == 1) return distanceTo(polyLine[0]) var shortestDistance = Double.MAX_VALUE polyLine.forEachLine { first, second -> val distance = distanceToArc(first, second, globeRadius) if (distance < shortestDistance) shortestDistance = distance } return shortestDistance } /* -------------------------------- Polyline extension functions -------------------------------- */ /** Returns the shortest distance between this polyline and given polyline */ fun List<LatLon>.distanceTo(polyline: List<LatLon>, globeRadius: Double = EARTH_RADIUS): Double { require(isNotEmpty()) { "Polyline must not be empty" } return minOf { it.distanceToArcs(polyline, globeRadius) } } /** Returns whether this polyline intersects with the given polyline. If a polyline touches the * other at an endpoint (f.e. two consecutive polylines that share one endpoint), this doesn't * count. */ fun List<LatLon>.intersectsWith(polyline: List<LatLon>): Boolean { require(size > 1 && polyline.size > 1) { "Polylines must each contain at least two elements" } val ns = map { it.toNormalOnSphere() } val npolyline = polyline.map { it.toNormalOnSphere() } ns.forEachLine { first, second -> npolyline.forEachLine { otherFirst, otherSecond -> val intersection = arcIntersection(first, second, otherFirst, otherSecond) if (intersection != null) { // touching endpoints don't count if ( first != npolyline.first() && first != npolyline.last() && second != npolyline.first() && second != npolyline.last() ) return true } } } return false } /** Returns whether the arc spanned between p1 and p2 intersects with the arc spanned by p2 and p4 */ fun intersectionOf(p1: LatLon, p2: LatLon, p3: LatLon, p4: LatLon): LatLon? { return arcIntersection( p1.toNormalOnSphere(), p2.toNormalOnSphere(), p3.toNormalOnSphere(), p4.toNormalOnSphere() )?.toLatLon() } /** Returns a bounding box that contains all points */ fun Iterable<LatLon>.enclosingBoundingBox(): BoundingBox { val it = iterator() require(it.hasNext()) { "positions is empty" } val origin = it.next() var minLatOffset = 0.0 var minLonOffset = 0.0 var maxLatOffset = 0.0 var maxLonOffset = 0.0 while (it.hasNext()) { val pos = it.next() // calculate with offsets here to properly handle 180th meridian val lat = pos.latitude - origin.latitude val lon = normalizeLongitude(pos.longitude - origin.longitude) if (lat < minLatOffset) minLatOffset = lat if (lon < minLonOffset) minLonOffset = lon if (lat > maxLatOffset) maxLatOffset = lat if (lon > maxLonOffset) maxLonOffset = lon } return BoundingBox( origin.latitude + minLatOffset, normalizeLongitude(origin.longitude + minLonOffset), origin.latitude + maxLatOffset, normalizeLongitude(origin.longitude + maxLonOffset) ) } /** Returns the distance covered by this polyline */ fun List<LatLon>.measuredLength(globeRadius: Double = EARTH_RADIUS): Double { if (isEmpty()) return 0.0 var length = 0.0 forEachLine { first, second -> length += first.distanceTo(second, globeRadius) } return length } /** Returns the line around the center point of this polyline * @throws IllegalArgumentException if list is empty */ fun List<LatLon>.centerLineOfPolyline(globeRadius: Double = EARTH_RADIUS): Pair<LatLon, LatLon> { require(size >= 2) { "positions list must contain at least 2 elements" } var halfDistance = measuredLength() / 2 forEachLine { first, second -> halfDistance -= first.distanceTo(second, globeRadius) if (halfDistance <= 0) { return Pair(first, second) } } throw RuntimeException() } /** * Returns the center point of this polyline */ fun List<LatLon>.centerPointOfPolyline(globeRadius: Double = EARTH_RADIUS): LatLon { require(isNotEmpty()) { "list is empty" } val halfDistance = measuredLength(globeRadius) / 2 return pointOnPolylineFromStart(halfDistance) ?: first() } /** * Returns the point the distance into the polyline. Null if the polyline is not long enough. */ fun List<LatLon>.pointOnPolylineFromStart(distance: Double): LatLon? { return pointOnPolyline(distance, false) } /** * Returns the point the distance into the polyline, starting from the end. Null if the polyline is * not long enough. */ fun List<LatLon>.pointOnPolylineFromEnd(distance: Double): LatLon? { return pointOnPolyline(distance, true) } private fun List<LatLon>.pointOnPolyline(distance: Double, fromEnd: Boolean): LatLon? { val list = if (fromEnd) this.asReversed() else this var d = 0.0 list.forEachLine { first, second -> val segmentDistance = first.distanceTo(second) if (segmentDistance > 0) { d += segmentDistance if (d >= distance) { val ratio = (d - distance) / segmentDistance val lat = second.latitude - ratio * (second.latitude - first.latitude) val lon = normalizeLongitude(second.longitude - ratio * normalizeLongitude(second.longitude - first.longitude)) return OsmLatLon(lat, lon) } } } return null } /* --------------------------------- Polygon extension functions -------------------------------- */ /** * Returns the center point of the given polygon * * @throws IllegalArgumentException if positions list is empty */ fun List<LatLon>.centerPointOfPolygon(): LatLon { require(isNotEmpty()) { "positions list is empty" } var lon = 0.0 var lat = 0.0 var area = 0.0 val origin = first() forEachLine { first, second -> // calculating with offsets to avoid rounding imprecision and 180th meridian problem val dx1 = normalizeLongitude(first.longitude - origin.longitude) val dy1 = first.latitude - origin.latitude val dx2 = normalizeLongitude(second.longitude - origin.longitude) val dy2 = second.latitude - origin.latitude val f = dx1 * dy2 - dx2 * dy1 lon += (dx1 + dx2) * f lat += (dy1 + dy2) * f area += f } area *= 3.0 return if (area == 0.0) origin else OsmLatLon( lat / area + origin.latitude, normalizeLongitude(lon / area + origin.longitude) ) } /** * Returns whether the given position is within the given polygon. Whether the polygon is defined * clockwise or counterclockwise does not matter. The polygon boundary and its vertices are * considered inside the polygon */ fun LatLon.isInPolygon(polygon: List<LatLon>): Boolean { var oddNumberOfIntersections = false var lastWasIntersectionAtVertex = false val lon = longitude val lat = latitude polygon.forEachLine { first, second -> val lat0 = first.latitude val lat1 = second.latitude // scanline check, disregard line segments parallel to the cast ray if (lat0 != lat1 && inside(lat, lat0, lat1)) { val lon0 = first.longitude val lon1 = second.longitude val vt = (lat - lat1) / (lat0 - lat1) val intersectionLongitude = normalizeLongitude(lon1 + vt * normalizeLongitude(lon0 - lon1)) val lonDiff = normalizeLongitude(intersectionLongitude - lon) // position is on polygon boundary if (lonDiff == 0.0) return true // ray crosses polygon boundary. ignore if this intersection was already counted // when looking at the last intersection val isIntersectionAtVertex = lat == lat1 if (lonDiff > 0 && !lastWasIntersectionAtVertex) { oddNumberOfIntersections = !oddNumberOfIntersections } lastWasIntersectionAtVertex = isIntersectionAtVertex } } return oddNumberOfIntersections } private fun inside(v: Double, bound0: Double, bound1: Double): Boolean = if (bound0 < bound1) v in bound0..bound1 else v in bound1..bound0 /** * Returns the area of a this multipolygon, assuming the outer shell is defined counterclockwise and * any holes are defined clockwise */ fun List<List<LatLon>>.measuredMultiPolygonArea(globeRadius: Double = EARTH_RADIUS): Double { return sumOf { it.measuredAreaSigned(globeRadius) } } /** * Returns the area of a this polygon */ fun List<LatLon>.measuredArea(globeRadius: Double = EARTH_RADIUS): Double { return abs(measuredAreaSigned(globeRadius)) } /** * Returns the signed area of a this polygon. If it is defined counterclockwise, it'll return * something positive, clockwise something negative */ fun List<LatLon>.measuredAreaSigned(globeRadius: Double = EARTH_RADIUS): Double { // not closed: area 0 if (size < 4) return 0.0 if (first().latitude != last().latitude || first().longitude != last().longitude) return 0.0 var area = 0.0 /* The algorithm is basically the same as for the planar case, only the calculation of the area * for each polygon edge is the polar triangle area */ forEachLine { first, second -> area += polarTriangleArea( first.latitude.toRadians(), first.longitude.toRadians(), second.latitude.toRadians(), second.longitude.toRadians(), ) } return area * (globeRadius * globeRadius) } /** * Returns whether the given position is within the given multipolygon. Polygons defined * counterclockwise count as outer shells, polygons defined clockwise count as holes. * * It is assumed that shells do not overlap with other shells and holes do not overlap with other * holes. (Though, of course a shell can be within a hole within a shell, that's okay) */ fun LatLon.isInMultipolygon(multipolygon: List<List<LatLon>>): Boolean { var containment = 0 for (polygon in multipolygon) { if (isInPolygon(polygon)) { if (polygon.isRingDefinedClockwise()) containment-- else containment++ } } return containment > 0 } /** Returns whether the given ring is defined clockwise * * @throws IllegalArgumentException if positions list is empty */ fun List<LatLon>.isRingDefinedClockwise(): Boolean { require(isNotEmpty()) { "positions list is empty" } var sum = 0.0 val origin = first() forEachLine { first, second -> // calculating with offsets to handle 180th meridian val lon0 = normalizeLongitude(first.longitude - origin.longitude) val lat0 = first.latitude - origin.latitude val lon1 = normalizeLongitude(second.longitude - origin.longitude) val lat1 = second.latitude - origin.latitude sum += lon0 * lat1 - lon1 * lat0 } return sum > 0 } /* ------------------------------ Bounding Box extension functions ----------------------------- */ /** Returns the area enclosed by this bbox */ fun BoundingBox.area(globeRadius: Double = EARTH_RADIUS): Double { val minLatMaxLon = OsmLatLon(min.latitude, max.longitude) val maxLatMinLon = OsmLatLon(max.latitude, min.longitude) return min.distanceTo(minLatMaxLon, globeRadius) * min.distanceTo(maxLatMinLon, globeRadius) } /** Returns a new bounding box that is [radius] larger than this bounding box */ fun BoundingBox.enlargedBy(radius: Double, globeRadius: Double = EARTH_RADIUS): BoundingBox { return BoundingBox( min.translate(radius, 225.0, globeRadius), max.translate(radius, 45.0, globeRadius) ) } /** returns whether this bounding box contains the given position */ fun BoundingBox.contains(pos: LatLon): Boolean { return if (crosses180thMeridian()) { splitAt180thMeridian().any { it.containsCanonical(pos) } } else { containsCanonical(pos) } } /** returns whether this bounding box contains the given position, assuming the bounding box does * not cross the 180th meridian */ private fun BoundingBox.containsCanonical(pos: LatLon): Boolean = pos.longitude in minLongitude..maxLongitude && pos.latitude in minLatitude..maxLatitude /** returns whether this bounding box intersects with the other. Works if any of the bounding boxes * cross the 180th meridian */ fun BoundingBox.intersect(other: BoundingBox): Boolean = checkAlignment(other) { bbox1, bbox2 -> bbox1.intersectCanonical(bbox2) } /** returns whether this bounding box is completely inside the other, assuming both bounding boxes * do not cross the 180th meridian */ fun BoundingBox.isCompletelyInside(other: BoundingBox): Boolean = checkAlignment(other) { bbox1, bbox2 -> bbox1.isCompletelyInsideCanonical(bbox2) } /** returns whether this bounding box intersects with the other, assuming both bounding boxes do * not cross the 180th meridian */ private fun BoundingBox.intersectCanonical(other: BoundingBox): Boolean = maxLongitude >= other.minLongitude && minLongitude <= other.maxLongitude && maxLatitude >= other.minLatitude && minLatitude <= other.maxLatitude /** returns whether this bounding box is completely inside the other, assuming both bounding boxes * do not cross the 180th meridian */ private fun BoundingBox.isCompletelyInsideCanonical(other: BoundingBox): Boolean = minLongitude >= other.minLongitude && minLatitude >= other.minLatitude && maxLongitude <= other.maxLongitude && maxLatitude <= other.maxLatitude private inline fun BoundingBox.checkAlignment( other: BoundingBox, canonicalCheck: (bbox1: BoundingBox, bbox2: BoundingBox) -> Boolean ): Boolean { return if(crosses180thMeridian()) { val these = splitAt180thMeridian() if (other.crosses180thMeridian()) { val others = other.splitAt180thMeridian() these.any { a -> others.any { b -> canonicalCheck(a, b) } } } else { these.any { canonicalCheck(it, other) } } } else { if (other.crosses180thMeridian()) { val others = other.splitAt180thMeridian() others.any { canonicalCheck(this, it) } } else { canonicalCheck(this, other) } } } fun createTranslated(latitude: Double, longitude: Double): LatLon { var lat = latitude var lon = longitude lon = normalizeLongitude(lon) var crossedPole = false // north pole if (lat > 90) { lat = 180 - lat crossedPole = true } else if (lat < -90) { lat = -180 - lat crossedPole = true } if (crossedPole) { lon += 180.0 if (lon > 180) lon -= 360.0 } return OsmLatLon(lat, lon) } private fun Double.toRadians() = this / 180.0 * PI private fun Double.toDegrees() = this / PI * 180.0 fun normalizeLongitude(lon: Double): Double { var lon = lon % 360 // lon is now -360..360 lon = (lon + 360) % 360 // lon is now 0..360 if (lon > 180) lon -= 360 // lon is now -180..180 return lon } /* The following formulas have been adapted from this excellent source: http://www.movable-type.co.uk/scripts/latlong.html Thanks to and (c) Chris Veness 2002-2019, MIT Licence All the calculations below are done with coordinates in radians. */ /** Return a new point translated from the point [φ1], [λ1] in the initial bearing [α1] and angular distance [σ12] */ private fun translate(φ1: Double, λ1: Double, α1: Double, σ12: Double): Pair<Double, Double> { val y = sin(φ1) * cos(σ12) + cos(φ1) * sin(σ12) * cos(α1) val a = cos(φ1) * cos(σ12) - sin(φ1) * sin(σ12) * cos(α1) val b = sin(σ12) * sin(α1) val x = sqrt(a.pow(2) + b.pow(2)) val φ2 = atan2(y, x) val λ2 = λ1 + atan2(b, a) return Pair(φ2, λ2) } /** Returns the distance of two points on a sphere */ private fun angularDistance(φ1: Double, λ1: Double, φ2: Double, λ2: Double): Double { // see https://mathforum.org/library/drmath/view/51879.html for derivation val Δλ = λ2 - λ1 val Δφ = φ2 - φ1 val a = sin(Δφ / 2).pow(2) + cos(φ1) * cos(φ2) * sin(Δλ / 2).pow(2) return 2 * asin(sqrt(a)) } /** Returns the initial bearing from one point to another */ private fun initialBearing(φ1: Double, λ1: Double, φ2: Double, λ2: Double): Double { // see https://mathforum.org/library/drmath/view/55417.html for derivation val Δλ = λ2 - λ1 return atan2(sin(Δλ) * cos(φ2), cos(φ1) * sin(φ2) - sin(φ1) * cos(φ2) * cos(Δλ)) } /** Returns the final bearing from one point to another */ private fun finalBearing(φ1: Double, λ1: Double, φ2: Double, λ2: Double): Double { val Δλ = λ2 - λ1 return atan2(sin(Δλ) * cos(φ1), -cos(φ2) * sin(φ1) + sin(φ2) * cos(φ1) * cos(Δλ)) } /** Returns the shortest distance between point three and the great arc spanned by one and two. * The sign tells on which side point three is on */ private fun crossTrackAngularDistance(φ1: Double, λ1: Double, φ2: Double, λ2: Double, φ3: Double, λ3: Double): Double { val θ12 = initialBearing(φ1, λ1, φ2, λ2) val θ13 = initialBearing(φ1, λ1, φ3, λ3) val δ13 = angularDistance(φ1, λ1, φ3, λ3) return asin(sin(δ13) * sin(θ13 - θ12)) } /** * Given the great arc spanned by point one and two, returns the distance of point one from the point on the * arc that is closest to point three. */ private fun alongTrackAngularDistance(φ1: Double, λ1: Double, φ2: Double, λ2: Double, φ3: Double, λ3: Double): Double { val θ12 = initialBearing(φ1, λ1, φ2, λ2) val θ13 = initialBearing(φ1, λ1, φ3, λ3) val δ13 = angularDistance(φ1, λ1, φ3, λ3) val δxt = asin(sin(δ13) * sin(θ13 - θ12)) // <- crossTrackAngularDistance return acos(cos(δ13) / abs(cos(δxt))) * sign(cos(θ12 - θ13)) } /** Returns the shortest distance between point three and the arc between point one and two. * The sign tells on which side point three is on */ private fun angularDistanceToArc(φ1: Double, λ1: Double, φ2: Double, λ2: Double, φ3: Double, λ3: Double): Double { val θ12 = initialBearing(φ1, λ1, φ2, λ2) val θ13 = initialBearing(φ1, λ1, φ3, λ3) val δ13 = angularDistance(φ1, λ1, φ3, λ3) val δ12 = angularDistance(φ1, λ1, φ2, λ2) val δxt = asin(sin(δ13) * sin(θ13 - θ12)) // <- crossTrackAngularDistance val δat = acos(cos(δ13) / abs(cos(δxt))) * sign(cos(θ12 - θ13)) // <- alongTrackAngularDistance // shortest distance to great arc is before point one -> shortest distance is distance to point one if (δat < 0) return δ13 // shortest distance to great arc is after point two -> shortest distance is distance to point two if (δat > δ12) return angularDistance(φ2, λ2, φ3, λ3) return δxt } /** Returns the signed area of a triangle spanning between the north pole and the two given points. * */ private fun polarTriangleArea(φ1: Double, λ1: Double, φ2: Double, λ2: Double): Double { val tanφ1 = tan((PI / 2 - φ1) / 2) val tanφ2 = tan((PI / 2 - φ2) / 2) val Δλ = λ1 - λ2 val tan = tanφ1 * tanφ2 return 2 * atan2(tan * sin(Δλ), 1 + tan * cos(Δλ)) }
gpl-3.0
f2ef8b7dfd7c414d3c68a81b6fd2f813
37.736089
127
0.666571
3.712479
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/ui/delegate/ViewStateDelegate.kt
2
864
package org.stepik.android.view.ui.delegate import android.view.View class ViewStateDelegate<S : Any> { private val viewMap: MutableMap<Class<out S>, Set<View>> = hashMapOf() private val views: MutableSet<View> = hashSetOf() fun addState(clazz: Class<out S>, vararg views: View) { val viewSet = views.toSet() this.viewMap[clazz] = viewSet this.views += viewSet } inline fun <reified C : S> addState(vararg views: View) { addState(C::class.java, *views) } fun switchState(newState: S) { val targetViews = viewMap[newState::class.java] ?: emptySet() val visibleViews = views.filter { it.visibility == View.VISIBLE }.toSet() (visibleViews - targetViews).forEach { it.visibility = View.GONE } (targetViews - visibleViews).forEach { it.visibility = View.VISIBLE } } }
apache-2.0
28e6c7ef0e8b0f685ab88039cce9461f
32.269231
81
0.65162
3.84
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/presentation/course_continue_redux/dispatcher/CourseContinueActionDispatcher.kt
2
2371
package org.stepik.android.presentation.course_continue_redux.dispatcher import io.reactivex.Scheduler import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import org.stepic.droid.adaptive.util.AdaptiveCoursesResolver import org.stepic.droid.analytic.Analytic import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import org.stepik.android.domain.course.interactor.ContinueLearningInteractor import org.stepik.android.domain.course_continue.analytic.CourseContinuePressedEvent import org.stepik.android.presentation.course_continue_redux.CourseContinueFeature import ru.nobird.android.presentation.redux.dispatcher.RxActionDispatcher import javax.inject.Inject class CourseContinueActionDispatcher @Inject constructor( private val analytic: Analytic, private val adaptiveCoursesResolver: AdaptiveCoursesResolver, private val continueLearningInteractor: ContinueLearningInteractor, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : RxActionDispatcher<CourseContinueFeature.Action, CourseContinueFeature.Message>() { override fun handleAction(action: CourseContinueFeature.Action) { when (action) { is CourseContinueFeature.Action.ContinueCourse -> { analytic.report(CourseContinuePressedEvent(action.course, action.interactionSource, action.viewSource)) if (adaptiveCoursesResolver.isAdaptive(action.course.id)) { onNewMessage(CourseContinueFeature.Message.ShowCourseContinue(action.course, action.viewSource, isAdaptive = true)) } else { compositeDisposable += continueLearningInteractor .getLastStepForCourse(action.course) .subscribeOn(backgroundScheduler) .observeOn(mainScheduler) .subscribeBy( onSuccess = { onNewMessage(CourseContinueFeature.Message.ShowStepsContinue(action.course, action.viewSource, it)) }, onError = { onNewMessage(CourseContinueFeature.Message.ShowCourseContinue(action.course, action.viewSource, isAdaptive = false)) } ) } } } } }
apache-2.0
80a141ca9861856818b5bb1927620e20
50.565217
158
0.727541
5.304251
false
false
false
false
StepicOrg/stepic-android
model/src/test/java/org/stepik/android/model/util/ParcelableTester.kt
2
2064
package org.stepik.android.model.util import android.os.Parcel import android.os.Parcelable import java.lang.reflect.Modifier /** * Class must properly implement equals()! */ fun <T : Parcelable> Parcelable.assertThatObjectParcelable() { val parcel = Parcel.obtain() try { this.writeToParcel(parcel, this.describeContents()) parcel.setDataPosition(0) val creator: Parcelable.Creator<T> try { val creatorField = this.javaClass.getDeclaredField("CREATOR") if (!Modifier.isPublic(creatorField.modifiers)) { throw AssertionError(this.javaClass.simpleName + ".CREATOR " + "is not public") } creatorField.isAccessible = true @Suppress("UNCHECKED_CAST") //it will throw exception, which we will rethrow as Assertion creator = creatorField.get(null) as Parcelable.Creator<T> } catch (e: NoSuchFieldException) { throw AssertionError(this.javaClass.simpleName + ".CREATOR " + "public static field must be presented in the class") } catch (e: IllegalAccessException) { throw AssertionError(this.javaClass.simpleName + ".CREATOR " + "is not accessible") } catch (e: ClassCastException) { throw AssertionError(this.javaClass.simpleName + ".CREATOR " + "field must be of type android.os.Parcelable.Creator" + "<" + this.javaClass.simpleName + ">") } val objectFromParcelable = creator.createFromParcel(parcel) if (this != objectFromParcelable) { throw AssertionError("Object before serialization is not equal to object " + "after serialization!\nOne of the possible problems -> " + "incorrect implementation of equals()." + "\nobject before = " + this + ",\nobject after = " + objectFromParcelable) } } finally { parcel.recycle() } }
apache-2.0
683c99f13c57ebc3f0a86d7e04e70094
35.875
101
0.597868
5.096296
false
false
false
false
Sulion/marco-paolo
src/main/kotlin/org/logout/notifications/telegram/infobipbot/InfobipTelegramBot.kt
1
3435
package org.logout.notifications.telegram.infobipbot import org.logout.notifications.telegram.bot.processor.* import org.logout.notifications.telegram.data.entities.InfobipIncomingMessage import org.logout.notifications.telegram.data.entities.InfobipIncomingPackage import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.scheduling.TaskScheduler import org.springframework.stereotype.Component import java.util.concurrent.Executors import javax.annotation.PostConstruct @Component class InfobipTelegramBot @Autowired constructor(private val taskScheduler: TaskScheduler, private val infobipTelegramService: InfobipTelegramService, private val staimaProcessor: StaImaNextEventProcessor, private val helpProcessor: HelpProcessor, private val startProcessor: StartProcessor, private val dissentProcessor: DissentProcessor) { companion object { val log = LoggerFactory.getLogger(InfobipTelegramBot::class.java) } val executor = Executors.newFixedThreadPool(4) @PostConstruct fun schedulePolling() { log.info("Scheduling message poll") val scheduledIncoming = taskScheduler.scheduleWithFixedDelay( { onMessages(infobipTelegramService.receiveAllmessages()) }, 3000) } fun onMessages(incomingPackage: InfobipIncomingPackage) { log.trace("Took {} messages", incomingPackage.messageCount) if (incomingPackage.messageCount == 0) return incomingPackage.results.forEach { executor.submit { onSingleMessage(it) } } } fun onSingleMessage(message: InfobipIncomingMessage) { if (message.message.type == "TEXT") { val text = message.message.text when { text.startsWith("jebiga") || text.startsWith("/jebiga") -> processMessage(dissentProcessor, message) text.startsWith("/start") -> processMessage(startProcessor, message) text.startsWith("/staima") || text.startsWith("/whatsup") || text.startsWith("/whazup") || text.startsWith("/чотамухохлов") -> processMessage(staimaProcessor, message) text.startsWith("/help") -> processMessage(helpProcessor, message) else -> infobipTelegramService.sendSingleMessage(message.message.text, message.from) } } } internal fun processMessage(processor: Processor, message: InfobipIncomingMessage) { processor.onMessage(args(message.message.text)) .forEach { infobipTelegramService.sendSingleMessage(it, message.from) } } internal fun sendCompositeMessages(lines: List<String>, toKey: String) { lines.forEach { infobipTelegramService.sendSingleMessage(it, toKey) } } private fun args(str: String) = str.split(Regex("\\s")).drop(1/*command name itself*/).toTypedArray() fun sendToEveryone(messageText: String) { infobipTelegramService.fetchUsers().users.forEach { infobipTelegramService.sendSingleMessage(messageText, it.key) } } }
apache-2.0
ce0cc1deb1df779187f311cb596d559c
44.64
107
0.648554
4.982533
false
false
false
false
juanlabrador/MonjeanClient
app/src/main/java/com/juanlabrador/monjean/appclient/DetailActivity.kt
1
3635
package com.juanlabrador.monjean.appclient import android.graphics.BitmapFactory import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.text.TextUtils import android.view.MenuItem import android.view.View import android.widget.Toast import com.parse.* import kotlinx.android.synthetic.activity_detail.toolbar import kotlinx.android.synthetic.activity_detail.collapsingToolbar import kotlinx.android.synthetic.activity_detail.data import kotlinx.android.synthetic.activity_detail.price import kotlinx.android.synthetic.activity_detail.buy import kotlinx.android.synthetic.activity_detail.photo import java.util.* /** * Created by juanlabrador on 29/10/15. */ class DetailActivity : AppCompatActivity() { var view: View? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) view = findViewById(android.R.id.content) setSupportActionBar(toolbar as Toolbar) supportActionBar.setDisplayHomeAsUpEnabled(true) var pants: Pants var id: String? = intent.getStringExtra("id") var query: ParseQuery<Pants> = ParseQuery.getQuery(Pants::class.java) query.getInBackground(id, object: GetCallback<Pants> { override fun done(obj: Pants, e: ParseException?) { if (e == null) { pants = obj collapsingToolbar.title = pants.getTitle() val amount = ArrayList<String>() for(int in 1..pants.getExistence()) { amount.add(int.toString()) } buy.addPopupLayout(R.string.buy_amount, amount) price.addTextLayout(R.string.detail_price, pants.getPrice().toString() + " Bs.") price.addTextLayout(R.string.detail_existence, pants.getExistence().toString()) var description = data.addExtendTextLayout(R.mipmap.ic_pants, R.string.detail_accessories, pants.getSubTitle()) description.setMultiLine() var colors = data.addExtendTextLayout(R.mipmap.ic_colors, R.string.detail_colors, TextUtils.join(", ", pants.getColors())) colors.setMultiLine() data.addExtendTextLayout(R.mipmap.ic_size, R.string.detail_sizes, TextUtils.join(" - ", pants.getSizes())) val file = pants.getPhoto() if (file != null) run { file.getDataInBackground(object : GetDataCallback { override fun done(data: ByteArray, e: ParseException?) { if (e == null) { val bmp = BitmapFactory.decodeByteArray( data, 0, data.size()) photo.setImageBitmap(bmp) } else { Toast.makeText(applicationContext, e.getMessage(), Toast.LENGTH_SHORT).show() } } }) } } else { finish() } } }); } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item?.itemId == android.R.id.home) finishAfterTransition() return true; } }
apache-2.0
7f99ab9c3e73ceb695d65c9566bcd94c
36.102041
142
0.573865
4.853138
false
false
false
false
cyclestreets/android
libraries/cyclestreets-fragments/src/main/java/net/cyclestreets/WebPageFragment.kt
1
2060
package net.cyclestreets import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import net.cyclestreets.fragments.R @SuppressLint("ValidFragment") open class WebPageFragment : Fragment { private val homePage: String private val layout: Int protected constructor(url: String) { homePage = url this.layout = R.layout.webpage } protected constructor(url: String, layout: Int) { homePage = url this.layout = layout } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val webPage = inflater.inflate(layout, null) val htmlView = webPage.findViewById<WebView>(R.id.html_view) htmlView.webViewClient = FragmentViewClient(requireContext(), homePage) htmlView.settings.javaScriptEnabled = true htmlView.loadUrl(homePage) return webPage } private class FragmentViewClient(private val context: Context, private val homePage: String) : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { return shouldOverrideUrlLoading(request.url.toString()) } @Deprecated("") override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { return shouldOverrideUrlLoading(url) } private fun shouldOverrideUrlLoading(url: String): Boolean { if (url == homePage) return false // Otherwise, give the default behavior (open in browser) val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) context.startActivity(intent) return true } } }
gpl-3.0
d064f60ac460aa5c1de81fbae30858fb
31.1875
116
0.7
4.881517
false
false
false
false
android/android-test
espresso/device/java/androidx/test/espresso/device/sizeclass/HeightSizeClass.kt
1
3802
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.test.espresso.device.sizeclass /** A class to create buckets for the height of a window. */ public class HeightSizeClass private constructor( private val lowerBound: Int, internal val upperBound: Int, private val description: String ) { override fun toString(): String { return description } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as HeightSizeClass if (lowerBound != other.lowerBound) return false if (upperBound != other.upperBound) return false if (description != other.description) return false return true } override fun hashCode(): Int { var result = lowerBound result = 31 * result + upperBound result = 31 * result + description.hashCode() return result } public companion object { /** A bucket to represent a compact height. One use-case is a phone that is in landscape. */ @JvmField public val COMPACT: HeightSizeClass = HeightSizeClass(0, 480, "COMPACT") /** A bucket to represent a medium height. One use-case is a phone in portrait or a tablet. */ @JvmField public val MEDIUM: HeightSizeClass = HeightSizeClass(480, 900, "MEDIUM") /** * A bucket to represent an expanded height window. One use-case is a tablet or a desktop app. */ @JvmField public val EXPANDED: HeightSizeClass = HeightSizeClass(900, Int.MAX_VALUE, "EXPANDED") /** * Returns a recommended [HeightSizeClass] for the height of a window given the height in DP. * @param dpHeight the height of the window in DP * @return A recommended size class for the height * @throws IllegalArgumentException if the height is negative */ @JvmStatic public fun compute(dpHeight: Int): HeightSizeClass { return when { dpHeight < COMPACT.lowerBound -> { throw IllegalArgumentException("Negative size: $dpHeight") } dpHeight < COMPACT.upperBound -> COMPACT dpHeight < MEDIUM.upperBound -> MEDIUM else -> EXPANDED } } /** * Returns a recommended height of a window in DP given the [HeightSizeClass]. * @param sizeClass the size class * @return A recommended height in DP in this size class */ @JvmStatic public fun getHeightDpInSizeClass(sizeClass: HeightSizeClass): Int { return when (sizeClass) { HeightSizeClass.COMPACT -> 400 HeightSizeClass.MEDIUM -> 700 else -> 1000 // HeightSizeClass.EXPANDED } } /** * Returns a [HeightSizeClassEnum] given the [HeightSizeClass]. * @param sizeClass the size class * @return the relevant HeightSizeClassEnum */ @JvmStatic public fun getEnum(sizeClass: HeightSizeClass): HeightSizeClassEnum { return when (sizeClass) { HeightSizeClass.COMPACT -> HeightSizeClassEnum.COMPACT HeightSizeClass.MEDIUM -> HeightSizeClassEnum.MEDIUM else -> HeightSizeClassEnum.EXPANDED } } public enum class HeightSizeClassEnum(val description: String) { COMPACT("COMPACT"), MEDIUM("MEDIUM"), EXPANDED("EXPANDED") } } }
apache-2.0
311fc31824700532886fe5eed244ca93
35.912621
100
0.685955
4.558753
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/intentions/OperatorToFunctionIntention.kt
2
16586
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinIdeaAnalysisBundle import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.references.readWriteAccess import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis import org.jetbrains.kotlin.psi2ir.deparenthesize import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.references.ReferenceAccess import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.utils.addToStdlib.safeAs class OperatorToFunctionIntention : SelfTargetingIntention<KtExpression>( KtExpression::class.java, KotlinIdeaAnalysisBundle.lazyMessage("replace.overloaded.operator.with.function.call"), ) { companion object { fun replaceExplicitInvokeCallWithImplicit(qualifiedExpression: KtDotQualifiedExpression): KtExpression? { /* * `a.b.invoke<>(){}` -> `a.b<>(){}` * `a.b<>(){}.invoke<>(){}` -> `a.b<>(){}<>(){}` * `b.invoke<>(){}` -> `b<>(){}` * `b<>(){}.invoke<>(){}` -> `b<>(){}<>(){}` * `invoke<>(){}` -> not applicable */ val callExpression = qualifiedExpression.selectorExpression.safeAs<KtCallExpression>()?.copied() ?: return null val calleExpression = callExpression.calleeExpression as KtNameReferenceExpression val receiverExpression = qualifiedExpression.receiverExpression val selectorInReceiver = receiverExpression.safeAs<KtDotQualifiedExpression>()?.selectorExpression return if (selectorInReceiver is KtNameReferenceExpression) { calleExpression.rawReplace(selectorInReceiver.copied()) selectorInReceiver.rawReplace(callExpression) qualifiedExpression.replaced(receiverExpression) } else { if ((receiverExpression is KtCallExpression || receiverExpression is KtDotQualifiedExpression) && callExpression.valueArgumentList == null && callExpression.typeArgumentList == null) { calleExpression.replace(receiverExpression) } else { calleExpression.rawReplace(receiverExpression) } qualifiedExpression.replaced(callExpression) } } private fun isApplicableUnary(element: KtUnaryExpression, caretOffset: Int): Boolean { if (element.baseExpression == null) return false val opRef = element.operationReference if (!opRef.textRange.containsOffset(caretOffset)) return false return when (opRef.getReferencedNameElementType()) { KtTokens.PLUS, KtTokens.MINUS, KtTokens.EXCL -> true KtTokens.PLUSPLUS, KtTokens.MINUSMINUS -> !isUsedAsExpression(element) else -> false } } // TODO: replace to `element.isUsedAsExpression(element.analyze(BodyResolveMode.PARTIAL_WITH_CFA))` after fix KT-25682 private fun isUsedAsExpression(element: KtExpression): Boolean { val parent = element.parent return if (parent is KtBlockExpression) parent.lastBlockStatementOrThis() == element && parentIsUsedAsExpression(parent.parent) else parentIsUsedAsExpression(parent) } private fun parentIsUsedAsExpression(element: PsiElement): Boolean = when (val parent = element.parent) { is KtLoopExpression, is KtFile -> false is KtIfExpression, is KtWhenExpression -> (parent as KtExpression).isUsedAsExpression(parent.analyze(BodyResolveMode.PARTIAL_WITH_CFA)) else -> true } private fun isApplicableBinary(element: KtBinaryExpression, caretOffset: Int): Boolean { if (element.left == null || element.right == null) return false val opRef = element.operationReference if (!opRef.textRange.containsOffset(caretOffset)) return false return when (opRef.getReferencedNameElementType()) { KtTokens.PLUS, KtTokens.MINUS, KtTokens.MUL, KtTokens.DIV, KtTokens.PERC, KtTokens.RANGE, KtTokens.IN_KEYWORD, KtTokens.NOT_IN, KtTokens.PLUSEQ, KtTokens.MINUSEQ, KtTokens.MULTEQ, KtTokens.DIVEQ, KtTokens.PERCEQ, KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ -> true KtTokens.EQEQ, KtTokens.EXCLEQ -> listOf(element.left, element.right).none { it?.node?.elementType == KtNodeTypes.NULL } KtTokens.EQ -> element.left is KtArrayAccessExpression else -> false } } private fun isApplicableArrayAccess(element: KtArrayAccessExpression, caretOffset: Int): Boolean { val lbracket = element.leftBracket ?: return false val rbracket = element.rightBracket ?: return false val access = element.readWriteAccess(useResolveForReadWrite = true) if (access == ReferenceAccess.READ_WRITE) return false // currently not supported return lbracket.textRange.containsOffset(caretOffset) || rbracket.textRange.containsOffset(caretOffset) } private fun isApplicableCall(element: KtCallExpression, caretOffset: Int): Boolean { val lbrace = (element.valueArgumentList?.leftParenthesis ?: element.lambdaArguments.firstOrNull()?.getLambdaExpression()?.leftCurlyBrace ?: return false) as PsiElement if (!lbrace.textRange.containsOffset(caretOffset)) return false val resolvedCall = element.resolveToCall(BodyResolveMode.FULL) val descriptor = resolvedCall?.resultingDescriptor if (descriptor is FunctionDescriptor && descriptor.getName() == OperatorNameConventions.INVOKE) { if (element.parent is KtDotQualifiedExpression && element.calleeExpression?.text == OperatorNameConventions.INVOKE.asString() ) return false return element.valueArgumentList != null || element.lambdaArguments.isNotEmpty() } return false } private fun convertUnary(element: KtUnaryExpression): KtExpression { val operatorName = when (element.operationReference.getReferencedNameElementType()) { KtTokens.PLUSPLUS, KtTokens.MINUSMINUS -> return convertUnaryWithAssignFix(element) KtTokens.PLUS -> OperatorNameConventions.UNARY_PLUS KtTokens.MINUS -> OperatorNameConventions.UNARY_MINUS KtTokens.EXCL -> OperatorNameConventions.NOT else -> return element } val transformed = KtPsiFactory(element).createExpressionByPattern("$0.$1()", element.baseExpression!!, operatorName) return element.replace(transformed) as KtExpression } private fun convertUnaryWithAssignFix(element: KtUnaryExpression): KtExpression { val operatorName = when (element.operationReference.getReferencedNameElementType()) { KtTokens.PLUSPLUS -> OperatorNameConventions.INC KtTokens.MINUSMINUS -> OperatorNameConventions.DEC else -> return element } val transformed = KtPsiFactory(element).createExpressionByPattern("$0 = $0.$1()", element.baseExpression!!, operatorName) return element.replace(transformed) as KtExpression } //TODO: don't use creation by plain text private fun convertBinary(element: KtBinaryExpression): KtExpression { val op = element.operationReference.getReferencedNameElementType() val left = element.left!! val right = element.right!! if (op == KtTokens.EQ) { if (left is KtArrayAccessExpression) { convertArrayAccess(left) } return element } val context = element.analyze(BodyResolveMode.PARTIAL) val functionCandidate = element.getResolvedCall(context) val functionName = functionCandidate?.candidateDescriptor?.name.toString() val elemType = context.getType(left) @NonNls val pattern = when (op) { KtTokens.PLUS -> "$0.plus($1)" KtTokens.MINUS -> "$0.minus($1)" KtTokens.MUL -> "$0.times($1)" KtTokens.DIV -> "$0.div($1)" KtTokens.PERC -> "$0.rem($1)" KtTokens.RANGE -> "$0.rangeTo($1)" KtTokens.IN_KEYWORD -> "$1.contains($0)" KtTokens.NOT_IN -> "!$1.contains($0)" KtTokens.PLUSEQ -> if (functionName == "plusAssign") "$0.plusAssign($1)" else "$0 = $0.plus($1)" KtTokens.MINUSEQ -> if (functionName == "minusAssign") "$0.minusAssign($1)" else "$0 = $0.minus($1)" KtTokens.MULTEQ -> if (functionName == "timesAssign") "$0.timesAssign($1)" else "$0 = $0.times($1)" KtTokens.DIVEQ -> if (functionName == "divAssign") "$0.divAssign($1)" else "$0 = $0.div($1)" KtTokens.PERCEQ -> { val remSupported = element.languageVersionSettings.supportsFeature(LanguageFeature.OperatorRem) if (remSupported && functionName == "remAssign") "$0.remAssign($1)" else if (functionName == "modAssign") "$0.modAssign($1)" else if (remSupported) "$0 = $0.rem($1)" else "$0 = $0.mod($1)" } KtTokens.EQEQ -> if (elemType?.isMarkedNullable != false) "$0?.equals($1) ?: ($1 == null)" else "$0.equals($1)" KtTokens.EXCLEQ -> if (elemType?.isMarkedNullable != false) "!($0?.equals($1) ?: ($1 == null))" else "!$0.equals($1)" KtTokens.GT -> "$0.compareTo($1) > 0" KtTokens.LT -> "$0.compareTo($1) < 0" KtTokens.GTEQ -> "$0.compareTo($1) >= 0" KtTokens.LTEQ -> "$0.compareTo($1) <= 0" else -> return element } val transformed = KtPsiFactory(element).createExpressionByPattern(pattern, left, right) return element.replace(transformed) as KtExpression } private fun convertArrayAccess(element: KtArrayAccessExpression): KtExpression { var expressionToReplace: KtExpression = element val transformed = KtPsiFactory(element).buildExpression { appendExpression(element.arrayExpression) appendFixedText(".") if (isAssignmentLeftSide(element)) { val parent = element.parent expressionToReplace = parent as KtBinaryExpression appendFixedText("set(") appendExpressions(element.indexExpressions) appendFixedText(",") appendExpression(parent.right) } else { appendFixedText("get(") appendExpressions(element.indexExpressions) } appendFixedText(")") } return expressionToReplace.replace(transformed) as KtExpression } private fun isAssignmentLeftSide(element: KtArrayAccessExpression): Boolean { val parent = element.parent return parent is KtBinaryExpression && parent.operationReference.getReferencedNameElementType() == KtTokens.EQ && element == parent.left } //TODO: don't use creation by plain text private fun convertCall(element: KtCallExpression): KtExpression { val callee = element.calleeExpression!! val receiver = element.parent?.safeAs<KtQualifiedExpression>()?.receiverExpression val isAnonymousFunctionWithReceiver = receiver != null && callee.deparenthesize() is KtNamedFunction val argumentsList = element.valueArgumentList val argumentString = argumentsList?.text?.removeSurrounding("(", ")") ?: "" val argumentsWithReceiverIfNeeded = if (isAnonymousFunctionWithReceiver) { val receiverText = receiver?.text ?: "" val delimiter = if (receiverText.isNotEmpty() && argumentString.isNotEmpty()) ", " else "" receiverText + delimiter + argumentString } else { argumentString } val funcLitArgs = element.lambdaArguments val calleeText = callee.text val transformation = "$calleeText.${OperatorNameConventions.INVOKE.asString()}" + "($argumentsWithReceiverIfNeeded)" val transformed = KtPsiFactory(element).createExpression(transformation) val callExpression = transformed.getCalleeExpressionIfAny()?.parent as? KtCallExpression if (callExpression != null && funcLitArgs.isNotEmpty()) { funcLitArgs.forEach { callExpression.add(it) } if (argumentsWithReceiverIfNeeded.isEmpty()) { callExpression.valueArgumentList?.delete() } } val elementToReplace = if (isAnonymousFunctionWithReceiver) element.parent else callee.parent return elementToReplace.replace(transformed) as KtExpression } fun convert(element: KtExpression): Pair<KtExpression, KtSimpleNameExpression> { var elementToBeReplaced = element if (element is KtArrayAccessExpression && isAssignmentLeftSide(element)) { elementToBeReplaced = element.parent as KtExpression } val commentSaver = CommentSaver(elementToBeReplaced, saveLineBreaks = true) val result = when (element) { is KtUnaryExpression -> convertUnary(element) is KtBinaryExpression -> convertBinary(element) is KtArrayAccessExpression -> convertArrayAccess(element) is KtCallExpression -> convertCall(element) else -> throw IllegalArgumentException(element.toString()) } commentSaver.restore(result) val callName = findCallName(result) ?: error("No call name found in ${result.text}") return result to callName } private fun findCallName(result: KtExpression): KtSimpleNameExpression? = when (result) { is KtBinaryExpression -> { if (KtPsiUtil.isAssignment(result)) findCallName(result.right!!) else findCallName(result.left!!) } is KtUnaryExpression -> result.baseExpression?.let { findCallName(it) } is KtParenthesizedExpression -> result.expression?.let { findCallName(it) } else -> result.getQualifiedElementSelector() as KtSimpleNameExpression? } } override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean = when (element) { is KtUnaryExpression -> isApplicableUnary(element, caretOffset) is KtBinaryExpression -> isApplicableBinary(element, caretOffset) is KtArrayAccessExpression -> isApplicableArrayAccess(element, caretOffset) is KtCallExpression -> isApplicableCall(element, caretOffset) else -> false } override fun applyTo(element: KtExpression, editor: Editor?) { convert(element) } }
apache-2.0
ba1a838ca0bb75beefadd0bb1866d1fc
51.321767
158
0.639154
5.610961
false
false
false
false
googlecodelabs/android-accessibility
BasicAndroidAccessibility-Kotlin/app/src/main/java/com/example/android/basicandroidaccessibility/InsufficientContrastFragment.kt
1
3273
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.basicandroidaccessibility import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.RelativeLayout import android.widget.TextView import androidx.core.content.ContextCompat import com.google.android.material.floatingactionbutton.FloatingActionButton class InsufficientContrastFragment : Fragment() { private lateinit var loremIpsumContainer: RelativeLayout private lateinit var loremIpsumTitle: TextView private lateinit var loremIpsumText: TextView private lateinit var addItemFab: FloatingActionButton override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_insufficient_contrast, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) loremIpsumContainer = view.findViewById(R.id.lorem_ipsum_container) loremIpsumTitle = view.findViewById(R.id.lorem_ipsum_title) loremIpsumText = view.findViewById(R.id.lorem_ipsum_text) addItemFab = view.findViewById(R.id.add_item_fab) val colorContrastCheckbox = view.findViewById<CheckBox>(R.id.color_contrast_checkbox) colorContrastCheckbox.setOnCheckedChangeListener { _, isChecked -> when (isChecked) { true -> useHighContrast() false -> useLowContrast() } } } private fun useHighContrast() { context?.let { loremIpsumContainer.setBackgroundColor(ContextCompat.getColor(it, R.color.white)) loremIpsumTitle.setTextColor(ContextCompat.getColor(it, R.color.medium_grey)) loremIpsumText.setTextColor(ContextCompat.getColor(it, R.color.dark_grey)) addItemFab.backgroundTintList = ContextCompat.getColorStateList(it, R.color.colorPrimaryDark) } } private fun useLowContrast() { context?.let { loremIpsumContainer.setBackgroundColor(ContextCompat.getColor(it, R.color.very_light_grey)) loremIpsumTitle.setTextColor(ContextCompat.getColor(it, R.color.light_grey)) loremIpsumText.setTextColor(ContextCompat.getColor(it, R.color.medium_grey)) addItemFab.backgroundTintList = ContextCompat.getColorStateList(it, R.color.colorPrimaryLight) } } }
apache-2.0
13cc3e191297968c1b456a0a9e549437
38.433735
103
0.714329
4.736614
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/intercode/IntercodeLookupGironde.kt
1
1972
/* * IntercodeTrip.kt * * Copyright 2018 Google * * This program is free software: you can redistribute it &&/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.intercode import au.id.micolous.metrodroid.card.CardType import au.id.micolous.metrodroid.multi.FormattedString import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.transit.CardInfo import au.id.micolous.metrodroid.transit.TransitRegion internal object IntercodeLookupGironde : IntercodeLookupSTR("gironde"), IntercodeLookupSingle { override val cardInfo: CardInfo get() = CardInfo( name = "TransGironde", locationId = R.string.location_gironde, imageId = R.drawable.transgironde, imageAlphaId = R.drawable.iso7810_id1_alpha, cardType = CardType.ISO7816, region = TransitRegion.FRANCE, preview = true) override fun getRouteName(routeNumber: Int?, routeVariant: Int?, agency: Int?, transport: Int?): FormattedString? { if (routeNumber == null) return null if (agency == TRANSGIRONDE) return Localizer.localizeFormatted(R.string.gironde_line, routeNumber) return super.getRouteName(routeNumber, routeNumber, agency, transport) } private const val TRANSGIRONDE = 16 }
gpl-3.0
b5abc1df9f303f0448dae9b408892a46
37.666667
95
0.706389
4.160338
false
false
false
false
florent37/Flutter-AssetsAudioPlayer
android/src/main/kotlin/com/github/florent37/assets_audio_player/stopwhencall/AudioFocusStrategy.kt
1
1076
package com.github.florent37.assets_audio_player.stopwhencall sealed class AudioFocusStrategy { object None : AudioFocusStrategy() class Request( val resumeAfterInterruption: Boolean, val resumeOthersPlayersAfterDone: Boolean ) : AudioFocusStrategy() companion object { fun from(params: Map<*, *>?): AudioFocusStrategy { if(params == null){ return AudioFocusStrategy.None } return try { val request = params["request"] if (request == false) { AudioFocusStrategy.None } else { AudioFocusStrategy.Request( resumeAfterInterruption = params["resumeAfterInterruption"] as Boolean, resumeOthersPlayersAfterDone = params["resumeOthersPlayersAfterDone"] as Boolean ) } } catch (t: Throwable){ AudioFocusStrategy.None } } } }
apache-2.0
69d4e8193755ef35a5d91771a13b2628
30.647059
108
0.526952
5.784946
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/processings/MergePropertyWithConstructorParameterProcessing.kt
1
8913
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.j2k.post.processing.processings import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.childrenOfType import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget.CONSTRUCTOR_PARAMETER import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget.FIELD import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics.findAnnotation import org.jetbrains.kotlin.idea.core.setVisibility import org.jetbrains.kotlin.idea.intentions.addUseSiteTarget import org.jetbrains.kotlin.idea.j2k.post.processing.* import org.jetbrains.kotlin.idea.util.CommentSaver import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.lexer.KtTokens.DATA_KEYWORD import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.escaped import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.asAssignment import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierTypeOrDefault import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.utils.addToStdlib.safeAs internal class MergePropertyWithConstructorParameterProcessing : ElementsBasedPostProcessing() { override fun runProcessing(elements: List<PsiElement>, converterContext: NewJ2kConverterContext) { for (klass in runReadAction { elements.descendantsOfType<KtClass>() }) { convertClass(klass) } } private fun convertClass(klass: KtClass) { val initializations = runReadAction { collectPropertyInitializations(klass) } runUndoTransparentActionInEdt(inWriteAction = true) { initializations.forEach(::convertInitialization) klass.removeEmptyInitBlocks() klass.removeRedundantEnumSemicolon() klass.removeIllegalDataModifierIfNeeded() } } private fun collectPropertyInitializations(klass: KtClass): List<Initialization<*>> { val usedParameters = mutableSetOf<KtParameter>() val usedProperties = mutableSetOf<KtProperty>() val initializations = mutableListOf<Initialization<*>>() fun KtExpression.asProperty() = unpackedReferenceToProperty()?.takeIf { it !in usedProperties && it.containingClass() == klass && it.initializer == null } fun KtReferenceExpression.asParameter() = resolve()?.safeAs<KtParameter>()?.takeIf { it !in usedParameters && it.containingClass() == klass && !it.hasValOrVar() } fun KtProperty.isSameTypeAs(parameter: KtParameter): Boolean { val propertyType = type() ?: return false val parameterType = parameter.type() ?: return false return KotlinTypeChecker.DEFAULT.equalTypes(propertyType, parameterType) } fun collectInitialization(expression: KtExpression): Boolean { val assignment = expression.asAssignment() ?: return false val property = assignment.left?.asProperty() ?: return false usedProperties += property when (val rightSide = assignment.right) { is KtReferenceExpression -> { val parameter = rightSide.asParameter() ?: return false if (!property.isSameTypeAs(parameter)) return false usedParameters += parameter initializations += ConstructorParameterInitialization(property, parameter, assignment) } is KtConstantExpression, is KtStringTemplateExpression -> { initializations += LiteralInitialization(property, rightSide, assignment) } else -> {} } return true } val initializer = klass.getAnonymousInitializers().singleOrNull() ?: return emptyList() val statements = initializer.body?.safeAs<KtBlockExpression>()?.statements ?: return emptyList() for (statement in statements) { if (!collectInitialization(statement)) break } return initializations } private fun convertInitialization(initialization: Initialization<*>) { val commentSaver = CommentSaver(initialization.assignment, saveLineBreaks = true) val restoreCommentsTarget: KtExpression when (initialization) { is ConstructorParameterInitialization -> { initialization.mergePropertyAndConstructorParameter() restoreCommentsTarget = initialization.initializer } is LiteralInitialization -> { val (property, initializer, _) = initialization property.initializer = initializer restoreCommentsTarget = property } } initialization.assignment.delete() commentSaver.restore(restoreCommentsTarget, forceAdjustIndent = false) } private fun ConstructorParameterInitialization.mergePropertyAndConstructorParameter() { val (property, parameter, _) = this parameter.addBefore(property.valOrVarKeyword, parameter.nameIdentifier!!) parameter.addAfter(KtPsiFactory(property).createWhiteSpace(), parameter.valOrVarKeyword!!) parameter.rename(property.name!!) parameter.setVisibility(property.visibilityModifierTypeOrDefault()) val commentSaver = CommentSaver(property, saveLineBreaks = true) parameter.annotationEntries.forEach { if (it.useSiteTarget == null) it.addUseSiteTarget(CONSTRUCTOR_PARAMETER, property.project) } property.annotationEntries.forEach { parameter.addAnnotationEntry(it).also { entry -> if (entry.useSiteTarget == null) entry.addUseSiteTarget(FIELD, property.project) } } property.typeReference?.annotationEntries?.forEach { entry -> if (parameter.typeReference?.annotationEntries?.all { it.shortName != entry.shortName } == true) { parameter.typeReference?.addAnnotationEntry(entry) } } property.delete() commentSaver.restore(parameter, forceAdjustIndent = false) } private fun KtCallableDeclaration.rename(newName: String) { val factory = KtPsiFactory(this) val escapedName = newName.escaped() ReferencesSearch.search(this, LocalSearchScope(containingKtFile)).forEach { it.element.replace(factory.createExpression(escapedName)) } setName(escapedName) } private fun KtClass.removeEmptyInitBlocks() { for (initBlock in getAnonymousInitializers()) { if ((initBlock.body as KtBlockExpression).statements.isEmpty()) { val commentSaver = CommentSaver(initBlock) initBlock.delete() primaryConstructor?.let { commentSaver.restore(it) } } } } private fun KtClass.removeRedundantEnumSemicolon() { if (!isEnum()) return val enumEntries = body?.childrenOfType<KtEnumEntry>().orEmpty() val otherMembers = body?.childrenOfType<KtDeclaration>()?.filterNot { it is KtEnumEntry }.orEmpty() if (otherMembers.isNotEmpty()) return if (enumEntries.isNotEmpty()) { enumEntries.lastOrNull()?.removeSemicolon() } else { body?.removeSemicolon() } } private fun KtElement.removeSemicolon() { getChildrenOfType<LeafPsiElement>().find { it.text == ";" }?.delete() } private fun KtClass.removeIllegalDataModifierIfNeeded() { if (!isData()) return if (primaryConstructorParameters.isEmpty() || primaryConstructorParameters.any { it.isVarArg || !it.hasValOrVar() } ) { removeModifier(DATA_KEYWORD) findAnnotation(declaration = this, FqName("kotlin.jvm.JvmRecord"))?.delete() } } } private sealed class Initialization<I : KtElement> { abstract val property: KtProperty abstract val initializer: I abstract val assignment: KtBinaryExpression } private data class ConstructorParameterInitialization( override val property: KtProperty, override val initializer: KtParameter, override val assignment: KtBinaryExpression ) : Initialization<KtParameter>() private data class LiteralInitialization( override val property: KtProperty, override val initializer: KtExpression, override val assignment: KtBinaryExpression ) : Initialization<KtExpression>()
apache-2.0
dd0ce8795ad321f3e2ec754d61d2437e
42.906404
120
0.691686
5.570625
false
false
false
false
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/psi/UastDescriptorLightParameter.kt
2
2048
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin.psi import com.intellij.lang.Language import com.intellij.psi.* import com.intellij.psi.impl.light.LightParameter import org.jetbrains.kotlin.descriptors.ParameterDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.components.isVararg import org.jetbrains.uast.UDeclaration import org.jetbrains.uast.UElement import org.jetbrains.uast.UastErrorType import org.jetbrains.uast.getParentOfType import org.jetbrains.uast.kotlin.analyze import org.jetbrains.uast.kotlin.toPsiType internal class UastDescriptorLightParameter( name: String, type: PsiType, parent: PsiElement, ktParameter: ValueParameterDescriptor, language: Language = parent.language, ) : UastDescriptorLightParameterBase<ValueParameterDescriptor>(name, type, parent, ktParameter, language) internal open class UastDescriptorLightParameterBase<T : ParameterDescriptor>( name: String, type: PsiType, private val parent: PsiElement, private val ktOrigin: T, language: Language = parent.language, ) : LightParameter(name, type, parent, language, ktOrigin.isVararg) { override fun getParent(): PsiElement = parent override fun getContainingFile(): PsiFile? = parent.containingFile override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other::class.java != this::class.java) return false return ktOrigin == (other as? UastDescriptorLightParameterBase<*>)?.ktOrigin } override fun hashCode(): Int = ktOrigin.hashCode() }
apache-2.0
960276ddde631ccef78a6bcea845c2fa
39.96
158
0.789063
4.4814
false
false
false
false
andrsim66/Timetable-Kotlin
app/src/main/java/com/sevenander/timetable/addEditLesson/AddEditPresenter.kt
1
3355
package com.sevenander.timetable.addEditLesson import android.app.TimePickerDialog import android.widget.TimePicker import com.sevenander.timetable.App import com.sevenander.timetable.R import com.sevenander.timetable.data.cache.LessonCache import com.sevenander.timetable.data.model.LessonDay import com.sevenander.timetable.data.model.LessonEntity /** * Created by andrii on 6/1/17. */ class AddEditPresenter(val view: AddEditView) : TimePickerDialog.OnTimeSetListener { private var startTimePicking: Boolean = false private var cache = LessonCache(App.instance.getDatabase()) override fun onTimeSet(picker: TimePicker?, hourOfDay: Int, minute: Int) { val time = "${"%02d".format(hourOfDay)}:${"%02d".format(minute)}" if (startTimePicking) { view.setStartTime(time) } else { view.setEndTime(time) } } fun init(lessonId: Int) { view.showProgress() loadData(lessonId) } fun destroy() { view.hideTimePickerDialog() } fun pickTimeClick(startTime: Boolean) { view.hideTimePickerDialog() startTimePicking = startTime view.showTimePickerDialog() } fun saveClicked(lessonId: Int, name: String, teacher: String, dayNumber: Int, start: String, end: String) { if (!validate(name, teacher, dayNumber, start, end)) return if (lessonId == -1) { addLesson(name, teacher, dayNumber, start, end) } else { updateLesson(lessonId, name, teacher, dayNumber, start, end) } view.onLessonSaved() } private fun addLesson(name: String, teacher: String, dayNumber: Int, start: String, end: String) { val lesson = LessonEntity(name, teacher, LessonDay.values()[dayNumber]) lesson.startTime = start lesson.endTime = end cache.addLessonEntity(lesson) } private fun updateLesson(lessonId: Int, name: String, teacher: String, dayNumber: Int, start: String, end: String) { val lesson = LessonEntity(name, teacher, LessonDay.values()[dayNumber]) lesson.id = lessonId lesson.startTime = start lesson.endTime = end cache.updateLessonEntity(lesson) } private fun validate(name: String, teacher: String, dayNumber: Int, start: String, end: String) : Boolean { if (name.isNullOrBlank()) return false if (teacher.isNullOrBlank()) return false if (dayNumber == -1) return false if (start.isTimeNullOrBlank()) return false if (end.isTimeNullOrBlank()) return false return true } private fun loadData(id: Int) { view.hideError() view.showProgress() val data = cache.getLesson(id) dataReceived(data) } private fun dataReceived(data: LessonEntity?) { if (data == null) { view.showError(view.context().getString(R.string.no_data_to_show)) view.hideLesson() } else { view.showLesson(data) view.hideError() } view.hideProgress() } private fun CharSequence?.isTimeNullOrBlank(): Boolean = this == null || this.isBlank() || this == "00:00" }
mit
a5b601fe8bde3b63ebd5f31b7402d99a
28.182609
102
0.614605
4.317889
false
false
false
false
programmerr47/ganalytics
ganalytics-core/src/main/java/com/github/programmerr47/ganalytics/core/AnalyticsGroupWrapper.kt
1
3731
package com.github.programmerr47.ganalytics.core import java.lang.reflect.Method import kotlin.reflect.KClass import kotlin.reflect.KProperty1 import kotlin.reflect.full.memberProperties internal typealias Annotations = List<Annotation> class AnalyticsGroupWrapper @JvmOverloads constructor( private val eventProvider: EventProvider, private val globalSettings: GanalyticsSettings = GanalyticsSettings()) : AnalyticsWrapper { internal val nameCache: MutableMap<String, AnalyticsWrapper> by lazy { HashMap<String, AnalyticsWrapper>() } internal val smartCache: MutableMap<String, AnalyticsWrapper> by lazy { HashMap<String, AnalyticsWrapper>() } private val notSmartAnnotations = listOf( HasPrefix::class, NoPrefix::class, HasPostfix::class, NoPostfix::class, Convention::class) private val requiredAnnotations = notSmartAnnotations + Category::class @Suppress("unchecked_cast") override fun <T : Any> create(kClass: KClass<T>): T { return kClass.run { createProxy(java, memberProperties) } as T } @Suppress("unchecked_cast") override fun <T : Any> create(clazz: Class<T>) = createProxy(clazz) as T private fun createProxy(clazz: Class<*>, props: Iterable<KProperty1<*, *>> = listOf()): Any { return wrapObjMethods(clazz) { _, method, _ -> val prop = props.find(method) val propAnnotations = prop?.annotations ?: listOf() val transform: (KClass<out Annotation>) -> Annotation? = { val annClass = it propAnnotations.find { annClass.isInstance(it) } ?: it.getFrom(method, clazz) } val methodAnnotations = requiredAnnotations.mapNotNull(transform) val notSmartMethodAnnotations = notSmartAnnotations.mapNotNull(transform) val defAnnotations = AnalyticsDefAnnotations(methodAnnotations.toTypedArray()) getWrapper(prop, method, clazz, notSmartMethodAnnotations, defAnnotations).create(method.returnType) } } private fun Iterable<KProperty1<*, *>>.find(method: Method): KProperty1<*, *>? { if (method.parameterTypes.isNotEmpty()) return null return find { convert(it.getter.name) == method.name } } private fun convert(getter: String) = getter .substringAfter("<") .substringBefore(">") .split('-') .map(String::capitalize) .joinToString(separator = "") .decapitalize() private fun getWrapper(prop: KProperty1<*,*>?, method: Method, clazz: Class<*>, notSmartAnnotations: Annotations, defAnnotations: AnalyticsDefAnnotations): AnalyticsWrapper { return if (notSmartAnnotations.isEmpty()) { val category = Category::class.run { prop?.annotations?.find { isInstance(it) } as Category? ?: getFrom(method, clazz) } smartCache.getOrPut({ category?.name ?: "" }, defAnnotations) } else { nameCache.getOrPut({ generateKey(clazz, method) }, defAnnotations) } } private inline fun <K> MutableMap<K, AnalyticsWrapper>.getOrPut(keygen: () -> K, defAnnotations: AnalyticsDefAnnotations): AnalyticsWrapper { return synchronized(this) { getOrPut(keygen()) { CacheWrapper(AnalyticsSingleWrapper(eventProvider, globalSettings, defAnnotations)) } } } private fun generateKey(clazz: Class<*>, method: Method) = "${clazz.simpleName}.${method.name}" } inline fun AnalyticsGroupWrapper(crossinline provider: (Event) -> Unit, globalSettings: GanalyticsSettings = GanalyticsSettings()) = AnalyticsGroupWrapper(EventProvider(provider), globalSettings)
mit
c814d824314725333302a2592d2d35fe
46.227848
178
0.670866
4.80799
false
false
false
false
google/ground-android
ground/src/main/java/com/google/android/ground/repository/SurveyRepository.kt
1
6074
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.repository import com.google.android.ground.model.Survey import com.google.android.ground.model.User import com.google.android.ground.model.job.Job import com.google.android.ground.model.mutation.Mutation import com.google.android.ground.persistence.local.LocalDataStore import com.google.android.ground.persistence.local.LocalValueStore import com.google.android.ground.persistence.remote.NotFoundException import com.google.android.ground.persistence.remote.RemoteDataStore import com.google.android.ground.rx.Loadable import com.google.android.ground.rx.annotations.Cold import com.google.android.ground.rx.annotations.Hot import com.google.android.ground.ui.map.CameraPosition import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableMap import io.reactivex.Flowable import io.reactivex.Single import io.reactivex.processors.BehaviorProcessor import io.reactivex.processors.FlowableProcessor import io.reactivex.processors.PublishProcessor import java.util.concurrent.TimeUnit import java8.util.Optional import javax.inject.Inject import javax.inject.Singleton import timber.log.Timber private const val LOAD_REMOTE_SURVEY_TIMEOUT_SECS: Long = 15 private const val LOAD_REMOTE_SURVEY_SUMMARIES_TIMEOUT_SECS: Long = 30 /** * Coordinates persistence and retrieval of [Survey] instances from remote, local, and in memory * data stores. For more details on this pattern and overall architecture, see * https://developer.android.com/jetpack/docs/guide. */ @Singleton class SurveyRepository @Inject constructor( private val localDataStore: LocalDataStore, private val remoteDataStore: RemoteDataStore, private val localValueStore: LocalValueStore ) { /** Emits a survey id on {@see #activateSurvey} and empty on {@see #clearActiveSurvey}. */ private val selectSurveyEvent: @Hot FlowableProcessor<String> = PublishProcessor.create() /** Emits the latest loading state of the current survey on subscribe and on change. */ val surveyLoadingState: @Hot(replays = true) FlowableProcessor<Loadable<Survey>> = BehaviorProcessor.create() var lastActiveSurveyId: String get() = localValueStore.lastActiveSurveyId set(value) { localValueStore.lastActiveSurveyId = value } val activeSurvey: @Hot(replays = true) Flowable<Optional<Survey>> get() = surveyLoadingState.map { obj: Loadable<Survey> -> obj.value() } val offlineSurveys: @Cold Single<ImmutableList<Survey>> get() = localDataStore.surveys init { // Kicks off the loading process whenever a new survey id is selected. selectSurveyEvent .distinctUntilChanged() .switchMap { selectSurvey(it) } .onBackpressureLatest() .subscribe(surveyLoadingState) } private fun selectSurvey(surveyId: String): @Cold Flowable<Loadable<Survey>> { // Empty id indicates intent to deactivate the current survey or first login. return if (surveyId.isEmpty()) Flowable.never() else syncSurveyWithRemote(surveyId) .onErrorResumeNext { getSurvey(surveyId) } .map { attachJobPermissions(it) } .doOnSuccess { lastActiveSurveyId = surveyId } .toFlowable() .compose { Loadable.loadingOnceAndWrap(it) } } private fun attachJobPermissions(survey: Survey): Survey { // TODO: Use Map once migration of dependencies to Kotlin is complete. val jobs: ImmutableMap.Builder<String, Job> = ImmutableMap.builder() for (job in survey.jobs) { jobs.put(job.id, job) } return survey.copy(jobMap = jobs.build()) } /** This only works if the survey is already cached to local db. */ fun getSurvey(surveyId: String): @Cold Single<Survey> = localDataStore .getSurveyById(surveyId) .switchIfEmpty(Single.error { NotFoundException("Survey not found $surveyId") }) private fun syncSurveyWithRemote(id: String): @Cold Single<Survey> = remoteDataStore .loadSurvey(id) .timeout(LOAD_REMOTE_SURVEY_TIMEOUT_SECS, TimeUnit.SECONDS) .flatMap { localDataStore.insertOrUpdateSurvey(it).toSingleDefault(it) } .doOnSubscribe { Timber.d("Loading survey $id") } .doOnError { err -> Timber.d(err, "Error loading survey from remote") } fun loadLastActiveSurvey() = activateSurvey(lastActiveSurveyId) fun activateSurvey(surveyId: String) = selectSurveyEvent.onNext(surveyId) fun clearActiveSurvey() = selectSurveyEvent.onNext("") fun getSurveySummaries(user: User): @Cold Flowable<Loadable<List<Survey>>> = loadSurveySummariesFromRemote(user) .doOnSubscribe { Timber.d("Loading survey list from remote") } .doOnError { Timber.d(it, "Failed to load survey list from remote") } .onErrorResumeNext { offlineSurveys } .toFlowable() .compose { Loadable.loadingOnceAndWrap(it) } private fun loadSurveySummariesFromRemote(user: User): @Cold Single<List<Survey>> = remoteDataStore .loadSurveySummaries(user) .timeout(LOAD_REMOTE_SURVEY_SUMMARIES_TIMEOUT_SECS, TimeUnit.SECONDS) fun getMutationsOnceAndStream( survey: Survey ): @Cold(terminates = false) Flowable<ImmutableList<Mutation>> { return localDataStore.getMutationsOnceAndStream(survey) } fun setCameraPosition(surveyId: String, cameraPosition: CameraPosition) = localValueStore.setLastCameraPosition(surveyId, cameraPosition) fun getLastCameraPosition(surveyId: String): CameraPosition? = localValueStore.getLastCameraPosition(surveyId) }
apache-2.0
391b82a24d9d46c05501a307df0c4c3b
38.699346
96
0.755186
4.232753
false
false
false
false
theapache64/Mock-API
src/com/theah64/mock_api/servlets/FetchJSONServlet.kt
1
4410
package com.theah64.mock_api.servlets import com.theah64.mock_api.database.Params import com.theah64.mock_api.database.Responses import com.theah64.mock_api.database.Routes import com.theah64.mock_api.utils.APIResponse import com.theah64.mock_api.utils.TimeUtils import com.theah64.webengine.database.querybuilders.QueryBuilderException import com.theah64.webengine.utils.PathInfo import com.theah64.webengine.utils.Request import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.io.IOException import java.sql.SQLException import java.text.SimpleDateFormat import java.time.LocalDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.* import javax.servlet.annotation.WebServlet import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * Created by theapache64 on 14/5/17. */ @WebServlet(urlPatterns = ["/fetch_json/*"]) class FetchJSONServlet : AdvancedBaseServlet() { override val isSecureServlet: Boolean get() = false override val requiredParameters: Array<String>? get() = null @Throws( Request.RequestException::class, IOException::class, JSONException::class, SQLException::class, PathInfo.PathInfoException::class, QueryBuilderException::class ) override fun doAdvancedPost() { val pathInfo = PathInfo(httpServletRequest!!.pathInfo, 2, PathInfo.UNLIMITED) val projectName = pathInfo.getPart(1) val routeName = pathInfo.getPartFrom(2) val route = Routes.instance.get(projectName, routeName)!! val joJson = JSONObject() val jaResponses = JSONArray() val responses = Responses.instance.getAll(Responses.COLUMN_ROUTE_ID, route.id!!) for (response in responses) { val joResponse = JSONObject() joResponse.put(Responses.COLUMN_ID, response.id) joResponse.put(Responses.COLUMN_NAME, response.name) jaResponses.put(joResponse) } joJson.put(KEY_RESPONSES, jaResponses) val jaParams = JSONArray() //Adding required params for (param in route.params!!) { val joParam = JSONObject() joParam.put(Params.COLUMN_ID, param.id) joParam.put(Params.COLUMN_NAME, param.name) joParam.put(Params.COLUMN_DATA_TYPE, param.dataType) joParam.put(Params.COLUMN_DEFAULT_VALUE, param.defaultValue) joParam.put(Params.COLUMN_DESCRIPTION, param.description) joParam.put(Params.COLUMN_IS_REQUIRED, param.isRequired) jaParams.put(joParam) } joJson.put(Routes.KEY_PARAMS, jaParams) joJson.put(Routes.COLUMN_EXTERNAL_API_URL, route.externalApiUrl) joJson.put(Routes.COLUMN_IS_SECURE, route.isSecure) joJson.put(Routes.COLUMN_REQUEST_BODY_TYPE, route.requestBodyType) joJson.put(Routes.COLUMN_JSON_REQ_BODY, route.jsonReqBody) joJson.put(Routes.COLUMN_DELAY, route.delay) joJson.put(Routes.COLUMN_DESCRIPTION, route.description) joJson.put(Routes.COLUMN_METHOD, route.method) joJson.put(Routes.COLUMN_STATUS_CODE, route.statusCode) joJson.put(KEY_DUMMY_PARAMS, route.dummyRequiredParams) joJson.put(KEY_LAST_MODIFIED, TimeUtils.millisToLongDHMS(route.updatedInMillis) + " ago") joJson.put(KEY_LAST_MODIFIED_DATE, getIndianDate(route.updatedInMillis)) writer!!.write(APIResponse("Response loaded", joJson).response) } @Throws(javax.servlet.ServletException::class, IOException::class) override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) { super.doPost(req, resp) } private fun getIndianDate(updatedInMillis: Long): String { val ldt = LocalDateTime.parse(DATE_FORMAT.format(Date(updatedInMillis)), DateTimeFormatter.ofPattern(DATE_FORMAT.toPattern())) return DATE_FORMAT.format(Date.from(ldt.atZone(ZoneId.of("Asia/Kolkata")).toInstant())) } companion object { val KEY_DUMMY_PARAMS = "dummy_params" private val KEY_LAST_MODIFIED = "last_modified" private val KEY_LAST_MODIFIED_DATE = "last_modified_date" private val KEY_RESPONSES = "responses" private val DATE_FORMAT = SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss") } }
apache-2.0
a774fc6e8b40359c39a74de079e5d11c
37.017241
134
0.700227
4.038462
false
false
false
false
pflammertsma/cryptogram
app/src/main/java/com/pixplicity/cryptogram/utils/SavegameManager.kt
1
5806
package com.pixplicity.cryptogram.utils import android.content.Context import com.google.android.gms.games.SnapshotsClient import com.google.android.gms.games.snapshot.Snapshot import com.google.android.gms.games.snapshot.SnapshotMetadata import com.google.android.gms.games.snapshot.SnapshotMetadataChange import com.google.firebase.crashlytics.FirebaseCrashlytics import com.pixplicity.cryptogram.R import java.io.IOException import java.math.BigInteger import java.util.* object SavegameManager { private val lastSavegameName: String get() { var savegameName: String? = PrefsUtils.lastSavegameName if (savegameName == null) { val unique = BigInteger(281, Random()).toString(13) savegameName = "snapshot-$unique" } return savegameName } interface OnSaveResult { fun onSaveSuccess() fun onSaveFailure(reason: String) } interface OnLoadResult { fun onLoadSuccess() fun onLoadFailure(reason: String) } fun load(context: Context, snapshotsClient: SnapshotsClient, snapshotName: String, callback: (Snapshot?) -> Unit?) { val task = snapshotsClient.open(snapshotName, false) task.addOnFailureListener { e -> FirebaseCrashlytics.getInstance().recordException(e) callback.invoke(null) } task.addOnSuccessListener { dataOrConflict -> if (hadConflictResolution(snapshotsClient, dataOrConflict)) { // Conflict was resolved; give it another go load(context, snapshotsClient, snapshotName, callback) return@addOnSuccessListener } val snapshot = dataOrConflict.data ?: throw IllegalStateException("Empty snapshot") try { val progressJson = String(snapshot.snapshotContents.readFully()) PuzzleProvider.getInstance(context).setProgressFromJson(progressJson) PrefsUtils.lastSavegameName = snapshotName callback.invoke(snapshot) } catch (e: IOException) { FirebaseCrashlytics.getInstance().recordException(e) callback.invoke(null) } } } fun save(context: Context, snapshotsClient: SnapshotsClient, callback: (SnapshotMetadata?) -> Unit?) { save(context, snapshotsClient, lastSavegameName, callback) } private fun save(context: Context, snapshotsClient: SnapshotsClient, snapshotName: String, callback: (SnapshotMetadata?) -> Unit?) { val task = snapshotsClient.open(snapshotName, true) task.addOnFailureListener { e -> FirebaseCrashlytics.getInstance().recordException(e) callback.invoke(null) } task.addOnSuccessListener { dataOrConflict -> if (hadConflictResolution(snapshotsClient, dataOrConflict)) { // Conflict was resolved; give it another go save(context, snapshotsClient, snapshotName, callback) return@addOnSuccessListener } val snapshot: Snapshot = dataOrConflict.data ?: throw IllegalStateException("Empty snapshot") // Set the data payload for the snapshot val provider = PuzzleProvider.getInstance(context) val progressJson = provider.progressJson val data = progressJson.toByteArray() snapshot.snapshotContents.writeBytes(data) var count = 0 for (c in provider.all) { if (!c.isInstruction && c.isCompleted) { count++ } } // Create the change operation val metadataChange = SnapshotMetadataChange.Builder() .setDescription(context.getString(R.string.saved_game_name, count, SystemUtils.deviceName)) .build() // Commit the operation val saveTask = snapshotsClient.commitAndClose(snapshot, metadataChange) saveTask.addOnFailureListener { e -> FirebaseCrashlytics.getInstance().recordException(e) callback.invoke(null) } saveTask.addOnSuccessListener { if (it.isDataValid) { PrefsUtils.lastSavegameName = snapshotName callback.invoke(snapshot.metadata) } else { FirebaseCrashlytics.getInstance().recordException(IllegalStateException("snapshot save failed with invalid data")) callback.invoke(null) } } } } private fun hadConflictResolution(snapshotsClient: SnapshotsClient, dataOrConflict: SnapshotsClient.DataOrConflict<Snapshot>): Boolean { if (dataOrConflict.isConflict) { dataOrConflict.conflict.let { if (it == null) throw java.lang.IllegalStateException("Snapshot is in conflict but snapshot is null") val conflictId = it.conflictId val serverSnapshot = it.snapshot val localSnapshot = it.conflictingSnapshot val resolvedSnapshot = if (serverSnapshot.metadata.lastModifiedTimestamp < localSnapshot.metadata.lastModifiedTimestamp) { localSnapshot } else { serverSnapshot } snapshotsClient.resolveConflict(conflictId, resolvedSnapshot) return true } } return false } }
mit
ee7384b1358b91d163bf977884aabd29
37.706667
140
0.597658
5.604247
false
false
false
false
PlanBase/PdfLayoutMgr2
src/test/java/com/planbase/pdf/lm2/contents/WrappedTextTest.kt
1
3150
package com.planbase.pdf.lm2.contents import com.planbase.pdf.lm2.attributes.TextStyle import com.planbase.pdf.lm2.lineWrapping.ConTerm import com.planbase.pdf.lm2.lineWrapping.ConTermNone import com.planbase.pdf.lm2.lineWrapping.Continuing import com.planbase.pdf.lm2.lineWrapping.None import com.planbase.pdf.lm2.utils.CMYK_BLACK import junit.framework.TestCase import org.apache.pdfbox.pdmodel.font.PDType1Font import org.junit.Assert.assertEquals import org.junit.Test import kotlin.test.assertTrue class WrappedTextTest { /** Related to [com.planbase.pdf.lm2.lineWrapping.MultiLineWrappedTest.testSpaceBeforeLastWord] This was a long-standing bug where if there were multiple items on a line (MultiLineWrapped) and the last one was text, and there was room left for one more item on the line, but only by removing the space before that item, it would nuke the last space before the last word. This showed up in Chapter 3 of Alice which this test is taken from. */ @Test fun testSpaceBeforeLastWord2() { val titleStyle = TextStyle(PDType1Font.TIMES_ROMAN, 16.0, CMYK_BLACK) // This tests a too-long line that breaks on a hyphen (not a white-space). // It used to adjust the index wrong and always return index=0 and return the first half of the line. val maxWidth = 174.0 val txt = Text(titleStyle, "A Caucus-Race and a Long Tale") // Make sure that "Long" doesn't fit on the first line (the rest of this test rests on this assumption). assertTrue(titleStyle.stringWidthInDocUnits("A Caucus-Race and a Long") > maxWidth) // Test the exact length just for completeness, but doesn't matter for rest of test. assertEquals(175.952, titleStyle.stringWidthInDocUnits("A Caucus-Race and a Long"), 0.0005) val wrapper = txt.lineWrapper() var conTerm: ConTerm = wrapper.getSomething(maxWidth) // println("conTerm=$conTerm") // This should always be true assertTrue(conTerm is Continuing) assertTrue(conTerm.item is WrappedText) assertTrue(conTerm.item.dim.width <= maxWidth) TestCase.assertEquals("A Caucus-Race and a", // Should this have a space at the end of it? (conTerm.item as WrappedText).string) TestCase.assertEquals(138.176, conTerm.item.dim.width, 0.0005) // The word "Long" plus a space should not fit on the current line. val conTermNone: ConTermNone = wrapper.getIfFits(174.0 - (138.176 + titleStyle.stringWidthInDocUnits(" "))) // println("conTermNone=$conTermNone") assertEquals(None, conTermNone) // OK, "Long Tale" should come out on the next line. conTerm = wrapper.getSomething(maxWidth) // println("conTerm=$conTerm") // This should always be true assertTrue(conTerm is Continuing) assertTrue(conTerm.item is WrappedText) assertTrue(conTerm.item.dim.width <= maxWidth) TestCase.assertEquals("Long Tale", (conTerm.item as WrappedText).string) TestCase.assertEquals(66.208, conTerm.item.dim.width, 0.0005) } }
agpl-3.0
fe6286da9d713afa57b6573708d0ae6b
45.338235
117
0.706032
3.952321
false
true
false
false
google/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/PerFileAnalysisCache.kt
5
25663
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.caches.resolve import com.google.common.collect.ImmutableMap import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicatorProvider import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.util.ModificationTracker import com.intellij.psi.PsiElement import com.intellij.psi.util.findParentInFile import com.intellij.psi.util.findTopmostParentInFile import com.intellij.psi.util.findTopmostParentOfType import org.jetbrains.kotlin.analyzer.AnalysisResult import org.jetbrains.kotlin.cfg.ControlFlowInformationProviderImpl import org.jetbrains.kotlin.container.ComponentProvider import org.jetbrains.kotlin.container.get import org.jetbrains.kotlin.context.GlobalContext import org.jetbrains.kotlin.context.withModule import org.jetbrains.kotlin.context.withProject import org.jetbrains.kotlin.descriptors.InvalidModuleException import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactoryWithPsiElement import org.jetbrains.kotlin.diagnostics.DiagnosticSink import org.jetbrains.kotlin.diagnostics.DiagnosticUtils import org.jetbrains.kotlin.diagnostics.PositioningStrategies.DECLARATION_WITH_BODY import org.jetbrains.kotlin.frontend.di.createContainerForLazyBodyResolve import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.findAnalyzerServices import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo import org.jetbrains.kotlin.idea.caches.trackers.clearInBlockModifications import org.jetbrains.kotlin.idea.caches.trackers.inBlockModifications import org.jetbrains.kotlin.idea.compiler.IdeMainFunctionDetectorFactory import org.jetbrains.kotlin.idea.compiler.IdeSealedClassInheritorsProvider import org.jetbrains.kotlin.idea.project.IdeaModuleStructureOracle import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.resolve.* import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import org.jetbrains.kotlin.resolve.diagnostics.DiagnosticsElementsCache import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.lazy.ResolveSession import org.jetbrains.kotlin.storage.CancellableSimpleLock import org.jetbrains.kotlin.storage.guarded import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.util.slicedMap.ReadOnlySlice import org.jetbrains.kotlin.util.slicedMap.WritableSlice import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.kotlin.utils.checkWithAttachment import java.util.concurrent.locks.ReentrantLock internal class PerFileAnalysisCache(val file: KtFile, componentProvider: ComponentProvider) { private val globalContext = componentProvider.get<GlobalContext>() private val moduleDescriptor = componentProvider.get<ModuleDescriptor>() private val resolveSession = componentProvider.get<ResolveSession>() private val codeFragmentAnalyzer = componentProvider.get<CodeFragmentAnalyzer>() private val bodyResolveCache = componentProvider.get<BodyResolveCache>() private val cache = HashMap<PsiElement, AnalysisResult>() private var fileResult: AnalysisResult? = null private val lock = ReentrantLock() private val guardLock = CancellableSimpleLock(lock, checkCancelled = { ProgressIndicatorProvider.checkCanceled() }, interruptedExceptionHandler = { throw ProcessCanceledException(it) }) private fun check(element: KtElement) { checkWithAttachment(element.containingFile == file, { "Expected $file, but was ${element.containingFile} for ${if (element.isValid) "valid" else "invalid"} $element " }) { it.withPsiAttachment("element.kt", element) it.withPsiAttachment("file.kt", element.containingFile) it.withPsiAttachment("original.kt", file) } } internal val isValid: Boolean get() = moduleDescriptor.isValid internal fun fetchAnalysisResults(element: KtElement): AnalysisResult? { check(element) if (lock.tryLock()) { try { updateFileResultFromCache() return fileResult?.takeIf { file.inBlockModifications.isEmpty() } } finally { lock.unlock() } } return null } internal fun getAnalysisResults(element: KtElement, callback: DiagnosticSink.DiagnosticsCallback? = null): AnalysisResult { check(element) val analyzableParent = KotlinResolveDataProvider.findAnalyzableParent(element) ?: return AnalysisResult.EMPTY fun handleResult(result: AnalysisResult, callback: DiagnosticSink.DiagnosticsCallback?): AnalysisResult { callback?.let { result.bindingContext.diagnostics.forEach(it::callback) } return result } return guardLock.guarded { // step 1: perform incremental analysis IF it is applicable getIncrementalAnalysisResult(callback)?.let { return@guarded handleResult(it, callback) } // cache does not contain AnalysisResult per each kt/psi element // instead it looks up analysis for its parents - see lookUp(analyzableElement) // step 2: return result if it is cached lookUp(analyzableParent)?.let { return@guarded handleResult(it, callback) } val localDiagnostics = mutableSetOf<Diagnostic>() val localCallback = if (callback != null) { d: Diagnostic -> localDiagnostics.add(d) callback.callback(d) } else null // step 3: perform analyze of analyzableParent as nothing has been cached yet val result = try { analyze(analyzableParent, null, localCallback) } catch (e: Throwable) { e.throwAsInvalidModuleException { ProcessCanceledException(it) } throw e } // some diagnostics could be not handled with a callback - send out the rest callback?.let { c -> result.bindingContext.diagnostics.filterNot { it in localDiagnostics }.forEach(c::callback) } cache[analyzableParent] = result return@guarded result } } private fun getIncrementalAnalysisResult(callback: DiagnosticSink.DiagnosticsCallback?): AnalysisResult? { updateFileResultFromCache() val inBlockModifications = file.inBlockModifications if (inBlockModifications.isNotEmpty()) { try { // IF there is a cached result for ktFile and there are inBlockModifications fileResult = fileResult?.let { result -> var analysisResult = result // Force full analysis when existed is erroneous if (analysisResult.isError()) return@let null for (inBlockModification in inBlockModifications) { val resultCtx = analysisResult.bindingContext val stackedCtx = if (resultCtx is StackedCompositeBindingContextTrace.StackedCompositeBindingContext) resultCtx else null // no incremental analysis IF it is not applicable if (stackedCtx?.isIncrementalAnalysisApplicable() == false) return@let null val trace: StackedCompositeBindingContextTrace = if (stackedCtx != null && stackedCtx.element() == inBlockModification) { val trace = stackedCtx.bindingTrace() trace.clear() trace } else { // to reflect a depth of stacked binding context val depth = (stackedCtx?.depth() ?: 0) + 1 StackedCompositeBindingContextTrace( depth, element = inBlockModification, resolveContext = resolveSession.bindingContext, parentContext = resultCtx ) } callback?.let { trace.parentDiagnosticsApartElement.forEach(it::callback) } val newResult = analyze(inBlockModification, trace, callback) analysisResult = wrapResult(result, newResult, trace) } file.clearInBlockModifications() analysisResult } } catch (e: Throwable) { e.throwAsInvalidModuleException { clearFileResultCache() ProcessCanceledException(it) } if (e !is ControlFlowException) { clearFileResultCache() } throw e } } if (fileResult == null) { file.clearInBlockModifications() } return fileResult } private fun updateFileResultFromCache() { // move fileResult from cache if it is stored there if (fileResult == null && cache.containsKey(file)) { fileResult = cache[file] // drop existed results for entire cache: // if incremental analysis is applicable it will produce a single value for file // otherwise those results are potentially stale cache.clear() } } private fun lookUp(analyzableElement: KtElement): AnalysisResult? { // Looking for parent elements that are already analyzed // Also removing all elements whose parents are already analyzed, to guarantee consistency val descendantsOfCurrent = arrayListOf<PsiElement>() val toRemove = hashSetOf<PsiElement>() var result: AnalysisResult? = null for (current in analyzableElement.parentsWithSelf) { val cached = cache[current] if (cached != null) { result = cached toRemove.addAll(descendantsOfCurrent) descendantsOfCurrent.clear() } descendantsOfCurrent.add(current) } cache.keys.removeAll(toRemove) return result } private fun wrapResult( oldResult: AnalysisResult, newResult: AnalysisResult, elementBindingTrace: StackedCompositeBindingContextTrace ): AnalysisResult { val newBindingCtx = elementBindingTrace.stackedContext return when { oldResult.isError() -> { oldResult.error.throwAsInvalidModuleException() AnalysisResult.internalError(newBindingCtx, oldResult.error) } newResult.isError() -> { newResult.error.throwAsInvalidModuleException() AnalysisResult.internalError(newBindingCtx, newResult.error) } else -> { AnalysisResult.success( newBindingCtx, oldResult.moduleDescriptor, oldResult.shouldGenerateCode ) } } } private fun analyze( analyzableElement: KtElement, bindingTrace: BindingTrace?, callback: DiagnosticSink.DiagnosticsCallback? ): AnalysisResult { ProgressIndicatorProvider.checkCanceled() val project = analyzableElement.project if (DumbService.isDumb(project)) { return AnalysisResult.EMPTY } moduleDescriptor.assertValid() try { return KotlinResolveDataProvider.analyze( project, globalContext, moduleDescriptor, resolveSession, codeFragmentAnalyzer, bodyResolveCache, analyzableElement, bindingTrace, callback ) } catch (e: ProcessCanceledException) { throw e } catch (e: IndexNotReadyException) { throw e } catch (e: Throwable) { e.throwAsInvalidModuleException() DiagnosticUtils.throwIfRunningOnServer(e) LOG.warn(e) return AnalysisResult.internalError(BindingContext.EMPTY, e) } } private fun clearFileResultCache() { file.clearInBlockModifications() fileResult = null } } private fun Throwable.asInvalidModuleException(): InvalidModuleException? { return when (this) { is InvalidModuleException -> this is AssertionError -> // temporary workaround till 1.6.0 / KT-48977 if (message?.contains("contained in his own dependencies, this is probably a misconfiguration") == true) InvalidModuleException(message!!) else null else -> cause?.takeIf { it != this }?.asInvalidModuleException() } } private inline fun Throwable.throwAsInvalidModuleException(crossinline action: (InvalidModuleException) -> Throwable = { it }) { asInvalidModuleException()?.let { throw action(it) } } private class MergedDiagnostics( val diagnostics: Collection<Diagnostic>, val noSuppressionDiagnostics: Collection<Diagnostic>, override val modificationTracker: ModificationTracker ) : Diagnostics { private val elementsCache = DiagnosticsElementsCache(this) { true } override fun all() = diagnostics override fun forElement(psiElement: PsiElement): MutableCollection<Diagnostic> = elementsCache.getDiagnostics(psiElement) override fun noSuppression() = if (noSuppressionDiagnostics.isEmpty()) { this } else { MergedDiagnostics(noSuppressionDiagnostics, emptyList(), modificationTracker) } } /** * Keep in mind: trace fallbacks to [resolveContext] (is used during resolve) that does not have any * traces of earlier resolve for this [element] * * When trace turned into [BindingContext] it fallbacks to [parentContext]: * It is expected that all slices specific to [element] (and its descendants) are stored in this binding context * and for the rest elements it falls back to [parentContext]. */ private class StackedCompositeBindingContextTrace( val depth: Int, // depth of stack over original ktFile bindingContext val element: KtElement, val resolveContext: BindingContext, val parentContext: BindingContext ) : DelegatingBindingTrace( resolveContext, "Stacked trace for resolution of $element", allowSliceRewrite = true ) { /** * Effectively StackedCompositeBindingContext holds up-to-date and partially outdated contexts (parentContext) * * The most up-to-date results for element are stored here (in a DelegatingBindingTrace#map) * * Note: It does not delete outdated results rather hide it therefore there is some extra memory footprint. * * Note: stackedContext differs from DelegatingBindingTrace#bindingContext: * if result is not present in this context it goes to parentContext rather to resolveContext * diagnostics are aggregated from this context and parentContext */ val stackedContext = StackedCompositeBindingContext() /** * All diagnostics from parentContext apart this diagnostics this belongs to the element or its descendants */ val parentDiagnosticsApartElement: Collection<Diagnostic> = (resolveContext.diagnostics.all() + parentContext.diagnostics.all()).filterApartElement() val parentDiagnosticsNoSuppressionApartElement: Collection<Diagnostic> = (resolveContext.diagnostics.noSuppression() + parentContext.diagnostics.noSuppression()).filterApartElement() private fun Collection<Diagnostic>.filterApartElement() = toSet().let { s -> s.filter { it.psiElement == element && selfDiagnosticToHold(it) } + s.filter { it.psiElement.parentsWithSelf.none { e -> e == element } } } inner class StackedCompositeBindingContext : BindingContext { var cachedDiagnostics: Diagnostics? = null fun bindingTrace(): StackedCompositeBindingContextTrace = this@StackedCompositeBindingContextTrace fun element(): KtElement = [email protected] fun depth(): Int = [email protected] // to prevent too deep stacked binding context fun isIncrementalAnalysisApplicable(): Boolean = [email protected] < 16 override fun getDiagnostics(): Diagnostics { if (cachedDiagnostics == null) { val mergedDiagnostics = mutableSetOf<Diagnostic>() mergedDiagnostics.addAll(parentDiagnosticsApartElement) [email protected]?.all()?.let { mergedDiagnostics.addAll(it) } val mergedNoSuppressionDiagnostics = mutableSetOf<Diagnostic>() mergedNoSuppressionDiagnostics += parentDiagnosticsNoSuppressionApartElement [email protected]?.noSuppression()?.let { mergedNoSuppressionDiagnostics.addAll(it) } cachedDiagnostics = MergedDiagnostics(mergedDiagnostics, mergedNoSuppressionDiagnostics, parentContext.diagnostics.modificationTracker) } return cachedDiagnostics!! } override fun <K : Any?, V : Any?> get(slice: ReadOnlySlice<K, V>, key: K): V? { return selfGet(slice, key) ?: parentContext.get(slice, key) } override fun getType(expression: KtExpression): KotlinType? { val typeInfo = get(BindingContext.EXPRESSION_TYPE_INFO, expression) return typeInfo?.type } override fun <K, V> getKeys(slice: WritableSlice<K, V>): Collection<K> { val keys = map.getKeys(slice) val fromParent = parentContext.getKeys(slice) if (keys.isEmpty()) return fromParent if (fromParent.isEmpty()) return keys return keys + fromParent } override fun <K : Any?, V : Any?> getSliceContents(slice: ReadOnlySlice<K, V>): ImmutableMap<K, V> { return ImmutableMap.copyOf(parentContext.getSliceContents(slice) + map.getSliceContents(slice)) } override fun addOwnDataTo(trace: BindingTrace, commitDiagnostics: Boolean) = throw UnsupportedOperationException() } override fun clear() { super.clear() stackedContext.cachedDiagnostics = null } companion object { private fun selfDiagnosticToHold(d: Diagnostic): Boolean { @Suppress("MoveVariableDeclarationIntoWhen") val positioningStrategy = d.factory.safeAs<DiagnosticFactoryWithPsiElement<*, *>>()?.positioningStrategy return when (positioningStrategy) { DECLARATION_WITH_BODY -> false else -> true } } } } private object KotlinResolveDataProvider { fun findAnalyzableParent(element: KtElement): KtElement? { if (element is KtFile) return element val topmostElement = element.findTopmostParentInFile { it is KtNamedFunction || it is KtAnonymousInitializer || it is KtProperty || it is KtImportDirective || it is KtPackageDirective || it is KtCodeFragment || // TODO: Non-analyzable so far, add more granular analysis it is KtAnnotationEntry || it is KtTypeConstraint || it is KtSuperTypeList || it is KtTypeParameter || it is KtParameter || it is KtTypeAlias } as KtElement? // parameters and supertype lists are not analyzable by themselves, but if we don't count them as topmost, we'll stop inside, say, // object expressions inside arguments of super constructors of classes (note that classes themselves are not topmost elements) val analyzableElement = when (topmostElement) { is KtAnnotationEntry, is KtTypeConstraint, is KtSuperTypeList, is KtTypeParameter, is KtParameter -> topmostElement.findParentInFile { it is KtClassOrObject || it is KtCallableDeclaration } as? KtElement? else -> topmostElement } // Primary constructor should never be returned if (analyzableElement is KtPrimaryConstructor) return analyzableElement.getContainingClassOrObject() // Class initializer should be replaced by containing class to provide full analysis if (analyzableElement is KtClassInitializer) return analyzableElement.containingDeclaration return analyzableElement // if none of the above worked, take the outermost declaration ?: element.findTopmostParentOfType<KtDeclaration>() // if even that didn't work, take the whole file ?: element.containingFile as? KtFile } fun analyze( project: Project, globalContext: GlobalContext, moduleDescriptor: ModuleDescriptor, resolveSession: ResolveSession, codeFragmentAnalyzer: CodeFragmentAnalyzer, bodyResolveCache: BodyResolveCache, analyzableElement: KtElement, bindingTrace: BindingTrace?, callback: DiagnosticSink.DiagnosticsCallback? ): AnalysisResult { try { if (analyzableElement is KtCodeFragment) { val bodyResolveMode = BodyResolveMode.PARTIAL_FOR_COMPLETION val trace: BindingTrace = codeFragmentAnalyzer.analyzeCodeFragment(analyzableElement, bodyResolveMode) val bindingContext = trace.bindingContext return AnalysisResult.success(bindingContext, moduleDescriptor) } val trace = bindingTrace ?: BindingTraceForBodyResolve( resolveSession.bindingContext, "Trace for resolution of $analyzableElement" ) val moduleInfo = analyzableElement.containingKtFile.moduleInfo val targetPlatform = moduleInfo.platform var callbackSet = false try { callbackSet = callback?.let(trace::setCallbackIfNotSet) ?: false /* Note that currently we *have* to re-create LazyTopDownAnalyzer with custom trace in order to disallow resolution of bodies in top-level trace (trace from DI-container). Resolving bodies in top-level trace may lead to memory leaks and incorrect resolution, because top-level trace isn't invalidated on in-block modifications (while body resolution surely does) Also note that for function bodies, we'll create DelegatingBindingTrace in ResolveElementCache anyways (see 'functionAdditionalResolve'). However, this trace is still needed, because we have other codepaths for other KtDeclarationWithBodies (like property accessors/secondary constructors/class initializers) */ val lazyTopDownAnalyzer = createContainerForLazyBodyResolve( //TODO: should get ModuleContext globalContext.withProject(project).withModule(moduleDescriptor), resolveSession, trace, targetPlatform, bodyResolveCache, targetPlatform.findAnalyzerServices(project), analyzableElement.languageVersionSettings, IdeaModuleStructureOracle(), IdeMainFunctionDetectorFactory(), IdeSealedClassInheritorsProvider, ControlFlowInformationProviderImpl.Factory, ).get<LazyTopDownAnalyzer>() lazyTopDownAnalyzer.analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, listOf(analyzableElement)) } finally { if (callbackSet) { trace.resetCallback() } } return AnalysisResult.success(trace.bindingContext, moduleDescriptor) } catch (e: ProcessCanceledException) { throw e } catch (e: IndexNotReadyException) { throw e } catch (e: Throwable) { e.throwAsInvalidModuleException() DiagnosticUtils.throwIfRunningOnServer(e) LOG.warn(e) return AnalysisResult.internalError(BindingContext.EMPTY, e) } } }
apache-2.0
9795b98fa07e20dc7aaa07c1343e60b9
42.423012
151
0.651171
5.694032
false
false
false
false
google/intellij-community
plugins/repository-search/src/main/kotlin/org/jetbrains/idea/packagesearch/http/ApiResult.kt
2
1546
/* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.packagesearch.http internal sealed class ApiResult<T : Any> { data class Success<T : Any>(val result: T) : ApiResult<T>() data class Failure<T : Any>(val throwable: Throwable) : ApiResult<T>() val isSuccess: Boolean get() = this is Success val isFailure: Boolean get() = this !is Success inline fun <V : Any> mapSuccess(action: (T) -> V) = if (isSuccess) { Success(action((this as Success<T>).result)) } else { @Suppress("UNCHECKED_CAST") this as Failure<V> } inline fun onFailure(action: (Throwable) -> Unit) = apply { if (this is Failure<*>) action(throwable) } inline fun onSuccess(action: (T) -> Unit) = apply { if (this is Success<T>) action(result) } fun getOrNull(): T? = when (this) { is Failure -> null is Success -> result } }
apache-2.0
0f320e8590b9328f7a2631c4d21cc9c1
29.313725
75
0.641009
4.036554
false
false
false
false
breandan/idear
src/main/java/org/openasr/idear/tts/JavaPronouncer.kt
2
1198
package org.openasr.idear.tts import com.intellij.codeInsight.intention.IntentionAction import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiFile import org.openasr.idear.CodeToTextConverter import org.openasr.idear.ide.isTextCurrentlySelected class JavaPronouncer : IntentionAction { override fun getText() = "Pronounce" override fun getFamilyName() = "Pronounce" override fun isAvailable(project: Project, editor: Editor, psiFile: PsiFile) = psiFile.language === JavaLanguage.INSTANCE && editor.isTextCurrentlySelected() override fun invoke(project: Project, editor: Editor, psiFile: PsiFile) { val start = editor.selectionModel.selectionStart val end = editor.selectionModel.selectionEnd var range: TextRange? = null if (end > start) range = TextRange(start, end) val caretOffset = editor.caretModel.offset val converter = CodeToTextConverter(psiFile, range, caretOffset) TTSService.say(converter.toText()) } override fun startInWriteAction() = false }
apache-2.0
d93049b1c85449d7177b60bfe0483647
35.30303
86
0.752087
4.404412
false
false
false
false
JetBrains/intellij-community
plugins/full-line/src/org/jetbrains/completion/full/line/platform/diagnostics/FullLineDiagnosticsToolWindowFactory.kt
1
1950
package org.jetbrains.completion.full.line.platform.diagnostics import com.intellij.openapi.Disposable import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.ui.content.ContentFactory internal const val FULL_LINE_TOOL_WINDOW_ID = "Full Line Diagnostics" class FullLineDiagnosticsToolWindowFactory : ToolWindowFactory, DumbAware { @NlsSafe val title = "Log" private lateinit var windowContent: FullLineToolWindowContent override fun init(toolWindow: ToolWindow) { super.init(toolWindow) windowContent = FullLineToolWindowContent(toolWindow.project) Disposer.register(toolWindow.disposable, windowContent) } override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { val content = ContentFactory.getInstance().createContent(windowContent.component, title, true) toolWindow.contentManager.apply { addContent(content) setSelectedContent(content) } toolWindow.setToHideOnEmptyContent(false) } override fun isApplicable(project: Project): Boolean { return Registry.`is`("full.line.enable.diagnostics") } } private class FullLineToolWindowContent(project: Project) : SimpleToolWindowPanel(false, true), Disposable { private val consoleLog: DiagnosticsLogConsole = DiagnosticsLogConsole(project) init { Disposer.register(this, consoleLog) setContent(consoleLog.component) DiagnosticsService.getInstance().subscribe(object : DiagnosticsListener { override fun messageReceived(message: DiagnosticsListener.Message) { consoleLog.addMessage(message) } }, this) } override fun dispose() { } }
apache-2.0
d5a63d6cd14500c9bd7e8e97a635f503
34.454545
108
0.788718
4.577465
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/domain/course_list/interactor/CourseListUserInteractor.kt
1
2813
package org.stepik.android.domain.course_list.interactor import io.reactivex.Completable import io.reactivex.Single import okhttp3.ResponseBody import org.stepic.droid.preferences.SharedPreferenceHelper import ru.nobird.app.core.model.PagedList import org.stepic.droid.util.then import org.stepik.android.domain.base.DataSourceType import org.stepik.android.domain.course.analytic.CourseViewSource import org.stepik.android.domain.course.model.SourceTypeComposition import org.stepik.android.domain.course_list.model.CourseListItem import org.stepik.android.domain.course_list.model.UserCourseQuery import org.stepik.android.domain.user_courses.model.UserCourse import org.stepik.android.domain.user_courses.repository.UserCoursesRepository import retrofit2.HttpException import retrofit2.Response import java.net.HttpURLConnection import javax.inject.Inject class CourseListUserInteractor @Inject constructor( private val sharedPreferenceHelper: SharedPreferenceHelper, private val userCoursesRepository: UserCoursesRepository, private val courseListInteractor: CourseListInteractor ) { companion object { private val UNAUTHORIZED_EXCEPTION_STUB = HttpException(Response.error<Nothing>(HttpURLConnection.HTTP_UNAUTHORIZED, ResponseBody.create(null, ""))) } private val requireAuthorization: Completable = Completable.create { emitter -> if (sharedPreferenceHelper.authResponseFromStore != null) { emitter.onComplete() } else { emitter.onError(UNAUTHORIZED_EXCEPTION_STUB) } } fun getAllUserCourses(userCourseQuery: UserCourseQuery, sourceType: DataSourceType = DataSourceType.CACHE): Single<List<UserCourse>> = requireAuthorization then userCoursesRepository .getAllUserCourses(userCourseQuery, sourceType) fun getCourseListItems(courseId: List<Long>, sourceType: DataSourceType = DataSourceType.CACHE): Single<Pair<PagedList<CourseListItem.Data>, DataSourceType>> = courseListInteractor .getCourseListItems( courseId, courseViewSource = CourseViewSource.MyCourses, sourceTypeComposition = SourceTypeComposition(sourceType, enrollmentSourceType = DataSourceType.CACHE) ) .map { it to sourceType } fun getUserCourse(courseId: Long, sourceType: DataSourceType = DataSourceType.CACHE): Single<CourseListItem.Data> = courseListInteractor .getCourseListItems( listOf(courseId), courseViewSource = CourseViewSource.MyCourses, sourceTypeComposition = SourceTypeComposition(sourceType, enrollmentSourceType = DataSourceType.CACHE) ) .map { it.first() } }
apache-2.0
f306f518c05a7d4d2675f826fce4cad3
42.96875
163
0.738358
5.441006
false
false
false
false
evant/binding-collection-adapter
app/src/main/java/me/tatarka/bindingcollectionadapter/sample/ImmutableViewModel.kt
1
6857
package me.tatarka.bindingcollectionadapter.sample import androidx.lifecycle.* import androidx.paging.* import androidx.recyclerview.widget.DiffUtil import kotlinx.coroutines.delay import me.tatarka.bindingcollectionadapter2.ItemBinding import me.tatarka.bindingcollectionadapter2.itembindings.OnItemBindLoadState import me.tatarka.bindingcollectionadapter2.itemBindingOf import me.tatarka.bindingcollectionadapter2.itembindings.OnItemBindClass import me.tatarka.bindingcollectionadapter2.map import me.tatarka.bindingcollectionadapter2.toItemBinding import kotlin.random.Random class ImmutableViewModel : ViewModel(), ImmutableListeners { private val mutList = MutableLiveData<List<ImmutableItem>>().apply { value = (0 until 3).map { i -> ImmutableItem(index = i, checked = false) } } private val headerFooterList = Transformations.map<List<ImmutableItem>, List<Any>>(mutList) { input -> val list = ArrayList<Any>(input.size + 2) list.add("Header") list.addAll(input) list.add("Footer") list } val list: LiveData<List<Any>> = headerFooterList val pagedList: LiveData<PagedList<Any>> = LivePagedListBuilder(object : DataSource.Factory<Int, Any>() { override fun create(): DataSource<Int, Any> = object : PositionalDataSource<Any>() { override fun loadInitial( params: LoadInitialParams, callback: LoadInitialCallback<Any> ) { val list = (0 until params.requestedLoadSize).map { ImmutableItem( index = it + params.requestedStartPosition, checked = false ) } // Pretend we are slow Thread.sleep(1000) callback.onResult(list, params.requestedStartPosition, 200) } override fun loadRange( params: LoadRangeParams, callback: LoadRangeCallback<Any> ) { val list = (0 until params.loadSize).map { ImmutableItem( index = it + params.startPosition, checked = false ) } // Pretend we are slow Thread.sleep(1000) callback.onResult(list) } } }, PAGE_SIZE).build() val pagedListV3: LiveData<PagingData<Any>> = Pager<Int, Any>(PagingConfig( pageSize = PAGE_SIZE, maxSize = 100, prefetchDistance = PAGE_SIZE * 2, enablePlaceholders = false)) { object : PagingSource<Int, Any>() { private val random = Random(TOTAL_COUNT) override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Any> { val safeKey = params.key ?: 0 val list = (0 until params.loadSize).map { ImmutableItem( index = it + safeKey, checked = false ) } // Pretend we are slow delay(1000) if (random.nextBoolean()) { return LoadResult.Error(IllegalAccessError("Error plz try again")) } return LoadResult.Page( data = list, prevKey = if (safeKey == 0) null else (safeKey - params.loadSize), nextKey = if (safeKey >= TOTAL_COUNT - params.loadSize) null else (safeKey + params.loadSize), itemsBefore = safeKey, itemsAfter = TOTAL_COUNT - params.loadSize - safeKey ) } override fun getRefreshKey(state: PagingState<Int, Any>): Int = 0 } }.flow.asLiveData() val items = itemBindingOf<Any>(BR.item, R.layout.item_immutable) val loadStateItems = OnItemBindLoadState.Builder<Any>() .item(BR.item, R.layout.item_immutable) .headerLoadState(OnItemBindClass<LoadState>().apply { map<LoadState.Loading>(ItemBinding.VAR_NONE, R.layout.network_state_item_progress) map<LoadState.Error>(BR.item, R.layout.network_state_item_error) }) .footerLoadState(OnItemBindClass<LoadState>().apply { map<LoadState.Loading>(ItemBinding.VAR_NONE, R.layout.network_state_item_progress) map<LoadState.Error>(BR.item, R.layout.network_state_item_error) }) .pagingCallbackVariableId(BR.callback) .build() val multipleItems = OnItemBindClass<Any>().apply { map<String>(BR.item, R.layout.item_header_footer) map<ImmutableItem>(BR.item, R.layout.item_immutable) }.toItemBinding().bindExtra(BR.listeners, this) val diff: DiffUtil.ItemCallback<Any> = object : DiffUtil.ItemCallback<Any>() { override fun areItemsTheSame(oldItem: Any, newItem: Any): Boolean { return if (oldItem is ImmutableItem && newItem is ImmutableItem) { oldItem.index == newItem.index } else oldItem == newItem } override fun areContentsTheSame(oldItem: Any, newItem: Any): Boolean { return oldItem == newItem } } override fun onToggleChecked(index: Int): Boolean { mutList.value = mutList.value!!.replaceAt(index) { item -> item.copy(checked = !item.checked) } return true } override fun onAddItem() { mutList.value = mutList.value!!.let { list -> list + ImmutableItem(index = list.size, checked = false) } } override fun onRemoveItem() { mutList.value!!.let { list -> if (list.size > 1) { mutList.value = list.dropLast(1) } } } companion object { private val TOTAL_COUNT = 200 private val PAGE_SIZE = 20 } }
apache-2.0
be81a94ded5a9b338a87dad3dc18b87f
41.067485
118
0.503281
5.437748
false
false
false
false
raybritton/json-query
lib/src/main/kotlin/com/raybritton/jsonquery/printers/SelectPrinter.kt
1
3224
package com.raybritton.jsonquery.printers import com.google.gson.GsonBuilder import com.raybritton.jsonquery.ext.isValue import com.raybritton.jsonquery.ext.sort import com.raybritton.jsonquery.models.JsonArray import com.raybritton.jsonquery.models.JsonObject import com.raybritton.jsonquery.models.Query import com.raybritton.jsonquery.models.SelectProjection import com.raybritton.jsonquery.tools.navigateToProjection internal object SelectPrinter : Printer { override fun print(json: Any, query: Query): String { return if (query.flags.isAsJson) { JsonPrinter().print(json, query) } else { json.printSelect(query) } } private fun Any?.printSelect(query: Query): String { if (this == null) return "null" return when (this) { is JsonArray -> this.print(query) is JsonObject -> this.print(query) else -> this.wrap() } } private fun Any?.wrap(): String { if (this is String) { return '"' + this + '"' } else { return this.toString() } } private fun JsonObject.print(query: Query): String { if (isEmpty()) return "{}" val showMarkers = (size != 1) val builder = StringBuilder(if (showMarkers) "{" else "") for (key in keys) { val output = get(key).printSelect(query) if (output.isNotBlank()) { when { query.flags.isOnlyPrintKeys -> builder.append(key) query.flags.isOnlyPrintValues -> builder.append(output) else -> { if (get(key).isValue() || (query.select?.projection == SelectProjection.All)) { builder.append(key) builder.append(": ") } builder.append(output) } } builder.append(", ") } } if (builder.length > 1) { builder.setLength(builder.length - 2) } if (showMarkers) { builder.append("}") } return builder.toString() } private fun JsonArray.print(query: Query): String { this.sort(query) if (isEmpty()) return "[]" val showMarkers = (size != 1) val builder = StringBuilder(if (showMarkers) "[" else "") for (element in this) { val startingLength = builder.length builder.append(element.printSelect(query)) if (builder.length > startingLength) { builder.append(", ") } } if (builder.length > 1) { builder.setLength(builder.length - 2) } if (showMarkers) { builder.append("]") } return builder.toString() } } private class JsonPrinter : Printer { override fun print(json: Any, query: Query): String { val gson = GsonBuilder().apply { if (query.flags.isPrettyPrinted) { this.setPrettyPrinting() } this.serializeNulls() }.create() return gson.toJson(json) } }
apache-2.0
bcce4f7997dadcc29cb0244f562873fc
30.617647
103
0.536911
4.652237
false
false
false
false
allotria/intellij-community
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/AbstractEntitiesTest.kt
1
2345
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage import com.intellij.testFramework.UsefulTestCase.assertOneElement import com.intellij.workspaceModel.storage.entities.* import org.junit.Assert.assertEquals import org.junit.Test class AbstractEntitiesTest { @Test fun `simple adding`() { val builder = WorkspaceEntityStorageBuilder.create() val middleEntity = builder.addMiddleEntity() builder.addLeftEntity(sequenceOf(middleEntity)) val storage = builder.toStorage() val leftEntity = assertOneElement(storage.entities(LeftEntity::class.java).toList()) assertOneElement(leftEntity.children.toList()) } @Test fun `modifying left entity`() { val builder = WorkspaceEntityStorageBuilder.create() val middleEntity = builder.addMiddleEntity("first") val leftEntity = builder.addLeftEntity(sequenceOf(middleEntity)) val anotherMiddleEntity = builder.addMiddleEntity("second") builder.modifyEntity(ModifiableLeftEntity::class.java, leftEntity) { this.children = sequenceOf(anotherMiddleEntity) } val storage = builder.toStorage() val actualLeftEntity = assertOneElement(storage.entities(LeftEntity::class.java).toList()) val actualChild = assertOneElement(actualLeftEntity.children.toList()) assertEquals(anotherMiddleEntity, actualChild) assertEquals(anotherMiddleEntity.property, (actualChild as MiddleEntity).property) } @Test fun `modifying abstract entity`() { val builder = WorkspaceEntityStorageBuilder.create() val middleEntity = builder.addMiddleEntity() val leftEntity: CompositeBaseEntity = builder.addLeftEntity(sequenceOf(middleEntity)) val anotherMiddleEntity = builder.addMiddleEntity() builder.modifyEntity(ModifiableCompositeBaseEntity::class.java, leftEntity) { this.children = sequenceOf(anotherMiddleEntity) } val storage = builder.toStorage() val actualLeftEntity = assertOneElement(storage.entities(LeftEntity::class.java).toList()) val actualChild = assertOneElement(actualLeftEntity.children.toList()) assertEquals(anotherMiddleEntity, actualChild) assertEquals(anotherMiddleEntity.property, (actualChild as MiddleEntity).property) } }
apache-2.0
904e80947f93bd6cacb0a5eeb43ba2e3
36.822581
140
0.772281
5.120087
false
true
false
false
Homes-MinecraftServerMod/Homes
src/main/kotlin/com/masahirosaito/spigot/homes/commands/subcommands/console/reloadcommands/ConsoleReloadCommand.kt
1
1136
package com.masahirosaito.spigot.homes.commands.subcommands.console.reloadcommands import com.masahirosaito.spigot.homes.Homes.Companion.homes import com.masahirosaito.spigot.homes.commands.BaseCommand import com.masahirosaito.spigot.homes.commands.CommandUsage import com.masahirosaito.spigot.homes.commands.subcommands.console.ConsoleCommand import com.masahirosaito.spigot.homes.strings.commands.ReloadCommandStrings.DESCRIPTION import com.masahirosaito.spigot.homes.strings.commands.ReloadCommandStrings.USAGE_RELOAD import org.bukkit.command.ConsoleCommandSender class ConsoleReloadCommand : ConsoleCommand { override val name: String = "reload" override val description: String = DESCRIPTION() override val commands: List<BaseCommand> = listOf() override val usage: CommandUsage = CommandUsage(this, listOf( "home reload" to USAGE_RELOAD() )) override fun execute(consoleCommandSender: ConsoleCommandSender, args: List<String>) { homes.reload() } override fun configs(): List<Boolean> = listOf() override fun isValidArgs(args: List<String>): Boolean = args.isEmpty() }
apache-2.0
b1def6fa6966633ac9cf3b837117818a
42.692308
90
0.786972
4.544
false
false
false
false
square/okio
okio/src/jvmMain/kotlin/okio/AsyncTimeout.kt
1
11515
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okio import java.io.IOException import java.io.InterruptedIOException import java.util.concurrent.TimeUnit /** * This timeout uses a background thread to take action exactly when the timeout occurs. Use this to * implement timeouts where they aren't supported natively, such as to sockets that are blocked on * writing. * * Subclasses should override [timedOut] to take action when a timeout occurs. This method will be * invoked by the shared watchdog thread so it should not do any long-running operations. Otherwise * we risk starving other timeouts from being triggered. * * Use [sink] and [source] to apply this timeout to a stream. The returned value will apply the * timeout to each operation on the wrapped stream. * * Callers should call [enter] before doing work that is subject to timeouts, and [exit] afterwards. * The return value of [exit] indicates whether a timeout was triggered. Note that the call to * [timedOut] is asynchronous, and may be called after [exit]. */ open class AsyncTimeout : Timeout() { /** True if this node is currently in the queue. */ private var inQueue = false /** The next node in the linked list. */ private var next: AsyncTimeout? = null /** If scheduled, this is the time that the watchdog should time this out. */ private var timeoutAt = 0L fun enter() { val timeoutNanos = timeoutNanos() val hasDeadline = hasDeadline() if (timeoutNanos == 0L && !hasDeadline) { return // No timeout and no deadline? Don't bother with the queue. } scheduleTimeout(this, timeoutNanos, hasDeadline) } /** Returns true if the timeout occurred. */ fun exit(): Boolean { return cancelScheduledTimeout(this) } /** * Returns the amount of time left until the time out. This will be negative if the timeout has * elapsed and the timeout should occur immediately. */ private fun remainingNanos(now: Long) = timeoutAt - now /** * Invoked by the watchdog thread when the time between calls to [enter] and [exit] has exceeded * the timeout. */ protected open fun timedOut() {} /** * Returns a new sink that delegates to [sink], using this to implement timeouts. This works * best if [timedOut] is overridden to interrupt [sink]'s current operation. */ fun sink(sink: Sink): Sink { return object : Sink { override fun write(source: Buffer, byteCount: Long) { checkOffsetAndCount(source.size, 0, byteCount) var remaining = byteCount while (remaining > 0L) { // Count how many bytes to write. This loop guarantees we split on a segment boundary. var toWrite = 0L var s = source.head!! while (toWrite < TIMEOUT_WRITE_SIZE) { val segmentSize = s.limit - s.pos toWrite += segmentSize.toLong() if (toWrite >= remaining) { toWrite = remaining break } s = s.next!! } // Emit one write. Only this section is subject to the timeout. withTimeout { sink.write(source, toWrite) } remaining -= toWrite } } override fun flush() { withTimeout { sink.flush() } } override fun close() { withTimeout { sink.close() } } override fun timeout() = this@AsyncTimeout override fun toString() = "AsyncTimeout.sink($sink)" } } /** * Returns a new source that delegates to [source], using this to implement timeouts. This works * best if [timedOut] is overridden to interrupt [source]'s current operation. */ fun source(source: Source): Source { return object : Source { override fun read(sink: Buffer, byteCount: Long): Long { return withTimeout { source.read(sink, byteCount) } } override fun close() { withTimeout { source.close() } } override fun timeout() = this@AsyncTimeout override fun toString() = "AsyncTimeout.source($source)" } } /** * Surrounds [block] with calls to [enter] and [exit], throwing an exception from * [newTimeoutException] if a timeout occurred. */ inline fun <T> withTimeout(block: () -> T): T { var throwOnTimeout = false enter() try { val result = block() throwOnTimeout = true return result } catch (e: IOException) { throw if (!exit()) e else `access$newTimeoutException`(e) } finally { val timedOut = exit() if (timedOut && throwOnTimeout) throw `access$newTimeoutException`(null) } } @PublishedApi // Binary compatible trampoline function internal fun `access$newTimeoutException`(cause: IOException?) = newTimeoutException(cause) /** * Returns an [IOException] to represent a timeout. By default this method returns * [InterruptedIOException]. If [cause] is non-null it is set as the cause of the * returned exception. */ protected open fun newTimeoutException(cause: IOException?): IOException { val e = InterruptedIOException("timeout") if (cause != null) { e.initCause(cause) } return e } private class Watchdog internal constructor() : Thread("Okio Watchdog") { init { isDaemon = true } override fun run() { while (true) { try { var timedOut: AsyncTimeout? = null synchronized(AsyncTimeout::class.java) { timedOut = awaitTimeout() // The queue is completely empty. Let this thread exit and let another watchdog thread // get created on the next call to scheduleTimeout(). if (timedOut === head) { head = null return } } // Close the timed out node, if one was found. timedOut?.timedOut() } catch (ignored: InterruptedException) { } } } } companion object { /** * Don't write more than 64 KiB of data at a time, give or take a segment. Otherwise slow * connections may suffer timeouts even when they're making (slow) progress. Without this, * writing a single 1 MiB buffer may never succeed on a sufficiently slow connection. */ private const val TIMEOUT_WRITE_SIZE = 64 * 1024 /** Duration for the watchdog thread to be idle before it shuts itself down. */ private val IDLE_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(60) private val IDLE_TIMEOUT_NANOS = TimeUnit.MILLISECONDS.toNanos(IDLE_TIMEOUT_MILLIS) /** * The watchdog thread processes a linked list of pending timeouts, sorted in the order to be * triggered. This class synchronizes on AsyncTimeout.class. This lock guards the queue. * * Head's 'next' points to the first element of the linked list. The first element is the next * node to time out, or null if the queue is empty. The head is null until the watchdog thread * is started and also after being idle for [AsyncTimeout.IDLE_TIMEOUT_MILLIS]. */ private var head: AsyncTimeout? = null private fun scheduleTimeout(node: AsyncTimeout, timeoutNanos: Long, hasDeadline: Boolean) { synchronized(AsyncTimeout::class.java) { check(!node.inQueue) { "Unbalanced enter/exit" } node.inQueue = true // Start the watchdog thread and create the head node when the first timeout is scheduled. if (head == null) { head = AsyncTimeout() Watchdog().start() } val now = System.nanoTime() if (timeoutNanos != 0L && hasDeadline) { // Compute the earliest event; either timeout or deadline. Because nanoTime can wrap // around, minOf() is undefined for absolute values, but meaningful for relative ones. node.timeoutAt = now + minOf(timeoutNanos, node.deadlineNanoTime() - now) } else if (timeoutNanos != 0L) { node.timeoutAt = now + timeoutNanos } else if (hasDeadline) { node.timeoutAt = node.deadlineNanoTime() } else { throw AssertionError() } // Insert the node in sorted order. val remainingNanos = node.remainingNanos(now) var prev = head!! while (true) { if (prev.next == null || remainingNanos < prev.next!!.remainingNanos(now)) { node.next = prev.next prev.next = node if (prev === head) { // Wake up the watchdog when inserting at the front. (AsyncTimeout::class.java as Object).notify() } break } prev = prev.next!! } } } /** Returns true if the timeout occurred. */ private fun cancelScheduledTimeout(node: AsyncTimeout): Boolean { synchronized(AsyncTimeout::class.java) { if (!node.inQueue) return false node.inQueue = false // Remove the node from the linked list. var prev = head while (prev != null) { if (prev.next === node) { prev.next = node.next node.next = null return false } prev = prev.next } // The node wasn't found in the linked list: it must have timed out! return true } } /** * Removes and returns the node at the head of the list, waiting for it to time out if * necessary. This returns [head] if there was no node at the head of the list when starting, * and there continues to be no node after waiting [IDLE_TIMEOUT_NANOS]. It returns null if a * new node was inserted while waiting. Otherwise this returns the node being waited on that has * been removed. */ @Throws(InterruptedException::class) internal fun awaitTimeout(): AsyncTimeout? { // Get the next eligible node. val node = head!!.next // The queue is empty. Wait until either something is enqueued or the idle timeout elapses. if (node == null) { val startNanos = System.nanoTime() (AsyncTimeout::class.java as Object).wait(IDLE_TIMEOUT_MILLIS) return if (head!!.next == null && System.nanoTime() - startNanos >= IDLE_TIMEOUT_NANOS) { head // The idle timeout elapsed. } else { null // The situation has changed. } } var waitNanos = node.remainingNanos(System.nanoTime()) // The head of the queue hasn't timed out yet. Await that. if (waitNanos > 0) { // Waiting is made complicated by the fact that we work in nanoseconds, // but the API wants (millis, nanos) in two arguments. val waitMillis = waitNanos / 1000000L waitNanos -= waitMillis * 1000000L (AsyncTimeout::class.java as Object).wait(waitMillis, waitNanos.toInt()) return null } // The head of the queue has timed out. Remove it. head!!.next = node.next node.next = null return node } } }
apache-2.0
2bbc42a57106124329de17327f4147fb
34.106707
100
0.63465
4.459721
false
false
false
false
xranby/modern-jogl-examples
src/main/kotlin/main/tut03/cpuPositionOffset.kt
1
3755
package main.tut03 import buffer.destroy import com.jogamp.newt.event.KeyEvent import com.jogamp.opengl.GL.* import com.jogamp.opengl.GL2ES3.GL_COLOR import com.jogamp.opengl.GL3 import extensions.intBufferBig import extensions.toFloatBuffer import glsl.programOf import main.* import main.framework.Framework import main.framework.Semantic import vec._2.Vec2 import vec._4.Vec4 /** * Created by GBarbieri on 21.02.2017. */ fun main(args: Array<String>) { CpuPositionOffset_() } class CpuPositionOffset_ : Framework("Tutorial 03 - CPU Position Offset") { var theProgram = 0 val positionBufferObject = intBufferBig(1) val vao = intBufferBig(1) val vertexPositions = floatArrayOf( +0.25f, +0.25f, 0.0f, 1.0f, +0.25f, -0.25f, 0.0f, 1.0f, -0.25f, -0.25f, 0.0f, 1.0f) var startingTime = 0L override fun init(gl: GL3) = with(gl) { initializeProgram(gl) initializeVertexBuffer(gl) glGenVertexArrays(1, vao) glBindVertexArray(vao[0]) startingTime = System.currentTimeMillis() } fun initializeProgram(gl: GL3) { theProgram = programOf(gl, this::class.java, "tut03", "standard.vert", "standard.frag") } fun initializeVertexBuffer(gl: GL3) = with(gl) { val vertexBuffer = vertexPositions.toFloatBuffer() glGenBuffers(1, positionBufferObject) glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject[0]) glBufferData(GL_ARRAY_BUFFER, vertexPositions.size * Float.BYTES.L, vertexBuffer, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, 0) vertexBuffer.destroy() } override fun display(gl: GL3) = with(gl) { val offset = Vec2(0f) computePositionOffsets(offset) adjustVertexData(gl, offset) glClearBufferfv(GL_COLOR, 0, clearColor.put(0, 0f).put(1, 0f).put(2, 0f).put(3, 1f)) glUseProgram(theProgram) glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject[0]) glEnableVertexAttribArray(Semantic.Attr.POSITION) glVertexAttribPointer(Semantic.Attr.POSITION, 4, GL_FLOAT, false, Vec4.SIZE, 0) glDrawArrays(GL3.GL_TRIANGLES, 0, 3) glDisableVertexAttribArray(Semantic.Attr.POSITION) glUseProgram(0) } fun computePositionOffsets(offset: Vec2) { val loopDuration = 5.0f val scale = (Math.PI * 2.0f / loopDuration).f val elapsedTime = (System.currentTimeMillis() - startingTime) / 1_000f val fCurrTimeThroughLoop = elapsedTime % loopDuration offset.x = glm.cos(fCurrTimeThroughLoop * scale) * 0.5f offset.y = glm.sin(fCurrTimeThroughLoop * scale) * 0.5f } fun adjustVertexData(gl: GL3, offset: Vec2) = with(gl) { val newData = vertexPositions.clone() for (iVertex in vertexPositions.indices step 4) { newData[iVertex + 0] += offset.x newData[iVertex + 1] += offset.y } val buffer = newData.toFloatBuffer() glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject[0]) glBufferSubData(GL_ARRAY_BUFFER, 0, buffer.SIZE.L, buffer) glBindBuffer(GL_ARRAY_BUFFER, 0) buffer.destroy() } override fun reshape(gl: GL3, w: Int, h: Int) { gl.glViewport(0, 0, w, h) } override fun end(gl: GL3) = with(gl) { glDeleteProgram(theProgram) glDeleteBuffers(1, positionBufferObject) glDeleteVertexArrays(1, vao) positionBufferObject.destroy() vao.destroy() } override fun keyPressed(keyEvent: KeyEvent) { when (keyEvent.keyCode) { KeyEvent.VK_ESCAPE -> { animator.remove(window) window.destroy() } } } }
mit
658833465c80d0cf5ff65c467bc65d23
25.828571
105
0.641545
3.919624
false
false
false
false
ylemoigne/ReactKT
subprojects/material/src/main/kotlin/fr/javatic/reactkt/material/components/TextareaProps.kt
1
1195
/* * Copyright 2015 Yann Le Moigne * * 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 fr.javatic.reactkt.material.components class TextareaProps( val cols: Int? = null, val rows: Int? = null, val defaultValue: String? = null, className: String? = null, id: String? = null, label: String? = null, floatingLabel: Boolean? = null, error: String? = null, expandable: Boolean? = null, button: Boolean? = null, icon: Boolean? = null, expandableHolder: Boolean? = null ) : AbstractInputfieldProps(className, id, label, floatingLabel, error, expandable, button, icon, expandableHolder)
apache-2.0
c6cd9cd054554ed42c3f5471c1230792
36.375
115
0.678661
4.092466
false
false
false
false
RichoDemus/chronicler
server/dropwizard/src/main/kotlin/com/richodemus/chronicler/server/dropwizard/ServerSentEventResource.kt
1
1911
package com.richodemus.chronicler.server.dropwizard import com.richodemus.chronicler.server.core.Chronicle import com.richodemus.chronicler.server.core.Event import com.richodemus.chronicler.server.core.EventCreationListener import org.glassfish.jersey.media.sse.EventOutput import org.glassfish.jersey.media.sse.OutboundEvent import org.glassfish.jersey.media.sse.SseFeature import org.slf4j.Logger import org.slf4j.LoggerFactory import javax.inject.Inject import javax.ws.rs.GET import javax.ws.rs.Path import javax.ws.rs.Produces @Path("event-stream") internal class ServerSentEventResource @Inject constructor(val chronicle: Chronicle) : EventCreationListener { val logger: Logger = LoggerFactory.getLogger(javaClass) //todo figure out how to remove disconnected clients val outputs = mutableListOf<EventOutput>() @GET @Produces(SseFeature.SERVER_SENT_EVENTS) fun getServerSentEvents(): EventOutput { val output = EventOutput() chronicle.getEvents().forEach { output.sendEvent(it) } //to do there is the possibility to miss events here, need to remake this :) outputs.add(output) return output } //todo investigate jersey sse broadcast override fun onEvent(event: Event) { logger.debug("Broadcasting event ${event.id} to ${outputs.size} listeners") val deadOutPuts = mutableListOf<EventOutput>() outputs.forEach { try { it.sendEvent(event) } catch (e: Exception) { logger.error("failed sending event to some listener, removing it", e) deadOutPuts.add(it) } } outputs.removeAll(deadOutPuts) } private fun EventOutput.sendEvent(event: Event) { val builder = OutboundEvent.Builder() builder.id(event.id) builder.data(event.data) this.write(builder.build()) } }
gpl-3.0
b9614da1a99c686194a92700d009c20f
35.056604
110
0.69911
4.136364
false
false
false
false
leafclick/intellij-community
platform/projectModel-impl/src/com/intellij/openapi/components/service.kt
1
1184
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.components import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.project.Project import com.intellij.project.ProjectStoreOwner inline fun <reified T : Any> service(): T = ApplicationManager.getApplication().getService(T::class.java) inline fun <reified T : Any> serviceOrNull(): T? = ApplicationManager.getApplication().getService(T::class.java) inline fun <reified T : Any> serviceIfCreated(): T? = ApplicationManager.getApplication().getServiceIfCreated(T::class.java) inline fun <reified T : Any> Project.service(): T = getService(T::class.java) inline fun <reified T : Any> Project.serviceIfCreated(): T? = getServiceIfCreated(T::class.java) val ComponentManager.stateStore: IComponentStore get() { return when (this) { is ProjectStoreOwner -> this.getComponentStore() else -> { // module or application service getService(IComponentStore::class.java) } } }
apache-2.0
b99ceba37c47509a4109eaf8487c6968
41.321429
140
0.752534
4.258993
false
false
false
false
intellij-purescript/intellij-purescript
src/main/kotlin/org/purescript/psi/exports/ExportedModuleReference.kt
1
1209
package org.purescript.psi.exports import com.intellij.psi.PsiElement import com.intellij.psi.PsiReferenceBase import org.purescript.psi.PSPsiFactory import org.purescript.psi.imports.PSImportDeclaration class ExportedModuleReference(exportedModule: PSExportedModule) : PsiReferenceBase<PSExportedModule>( exportedModule, exportedModule.moduleName.textRangeInParent, false ) { override fun getVariants(): Array<String> { return candidates.mapNotNull { it.name } .toTypedArray() } override fun resolve(): PsiElement? { if (element.name == myElement.module?.name) { return myElement.module } else { return candidates.firstOrNull { it.name == myElement.name } ?.run { importAlias ?: importedModule } } } override fun handleElementRename(name: String): PsiElement? { val newProperName = PSPsiFactory(element.project).createModuleName(name) ?: return null element.moduleName.replace(newProperName) return element } private val candidates: Array<PSImportDeclaration> get() = myElement.module?.importDeclarations ?: emptyArray() }
bsd-3-clause
29b229a3590073fad20865eb27aa47b0
31.675676
101
0.683209
4.894737
false
false
false
false
hannesa2/owncloud-android
owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt
2
2085
/** * ownCloud Android client application * * @author David González Verdugo * @author Abel García de Prada * Copyright (C) 2021 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * 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.owncloud.android.testutil import android.accounts.Account const val OC_ACCOUNT_ID = "username" const val OC_ACCOUNT_NAME = "[email protected]" /** * Accounts */ val OC_ACCOUNT = getAccount() fun getAccount(name: String = OC_ACCOUNT_NAME, type: String = "owncloud"): Account { val account = Account(name, type) // We need reflection or account will be Account(null, null) because name and type are final with(account.javaClass.getDeclaredField("name")) { isAccessible = true set(account, name) } with(account.javaClass.getDeclaredField("type")) { isAccessible = true set(account, type) } return account } /** * BasicCredentials */ const val OC_BASIC_USERNAME = "user" const val OC_BASIC_PASSWORD = "password" /** * OAuth */ const val OC_OAUTH_SUPPORTED_TRUE = "TRUE" const val OC_AUTH_TOKEN_TYPE = "owncloud.oauth2.access_token" const val OC_ACCESS_TOKEN = "Asqweh12p93yehd10eu" const val OC_REFRESH_TOKEN = "P3sd19DSsjdp1jwdd1" const val OC_SCOPE = "email" const val OC_REDIRECT_URI = "oc:android.owncloud.com" const val OC_TOKEN_ENDPOINT = "https://owncloud.server/token" const val OC_CLIENT_AUTH = "cl13nt4uth" const val OC_CLIENT_SECRET = "cl13nts3cr3t" const val OC_CLIENT_ID = "cl13nt1d" const val OC_CLIENT_SECRET_EXPIRATION = 1611251163
gpl-2.0
5a78ff2dd6c7048705e1f4ae14972445
30.089552
96
0.720595
3.566781
false
false
false
false
Xenoage/Zong
utils-kotlin/src/com/xenoage/utils/log/Report.kt
1
3417
package com.xenoage.utils.log import com.xenoage.utils.lang.VocID import com.xenoage.utils.log.Report.Companion.createReport /** * A logging or error report. */ class Report( /** The severity of the report */ val level: Level, /** The [VocID] of the message, or null */ val messageID: VocID? = null, /** The raw text message, or null */ val message: String? = null, /** The stack trace element where the report was made, or null */ val caller: String? = null, //TODO: StrackTraceElement /** The error object, or null */ val error: Throwable? = null, /** The paths of the files which belong to this report, or null */ val filePaths: List<String>? = null) { override fun toString(): String { val ret = StringBuilder() ret.append("[") ret.append("level: $level; ") if (messageID != null) ret.append("messageID: <$messageID>; ") if (message != null) ret.append("message: <$message>; ") if (filePaths != null) ret.append("filePaths: $filePaths; ") if (caller != null) ret.append("caller: <$caller>; ") if (error != null) ret.append("error: <" + error + ">") /* TODO , stack trace: <" + platformUtils().getStackTraceString(error) + ">; ") */ return ret.toString() } companion object { fun createReport(level: Level, findCaller: Boolean, messageID: VocID? = null, message: String? = null, error: Throwable? = null, filePaths: List<String>? = null): Report { //only find caller, if log level is high enough /* TODO if (level.isIncludedIn(Log.getLoggingLevel()) == false) findCaller = false //get stack trace, if requested and if possible var caller: String? = null //TODO: StrackTraceElement if (findCaller) { caller = platformUtils().getCaller(1) } */ return Report(level, messageID, message, null /* caller */, error, filePaths) } } } fun fatal(messageID: VocID? = null, error: Throwable? = null, filePaths: List<String>? = null): Report { return createReport(Level.Fatal, true, messageID, null, error, filePaths) } fun fatal(message: String?, error: Throwable? = null, filePaths: List<String>? = null): Report { return createReport(Level.Fatal, true, null, message, error, filePaths) } fun error(messageID: VocID? = null, error: Throwable? = null, filePaths: List<String>? = null): Report { return createReport(Level.Error, true, messageID, null, error, filePaths) } fun error(message: String? = null, error: Throwable? = null, filePaths: List<String>? = null): Report { return createReport(Level.Error, true, null, message, error, filePaths) } fun warning(messageID: VocID? = null, error: Throwable? = null, filePaths: List<String>? = null): Report { return createReport(Level.Warning, true, messageID, null, error, filePaths) } fun warning(message: String? = null, error: Throwable? = null, filePaths: List<String>? = null): Report { return createReport(Level.Warning, true, null, message, error, filePaths) } fun remark(messageID: VocID? = null, error: Throwable? = null, filePaths: List<String>? = null): Report { return createReport(Level.Remark, false, messageID, null, error, filePaths) } fun remark(message: String? = null, error: Throwable? = null, filePaths: List<String>? = null): Report { return createReport(Level.Remark, false, null, message, error, filePaths) }
agpl-3.0
0a672e0bd652b28fc231a563b808294b
33.525253
120
0.659643
3.472561
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/unifier/equivalence/expressions/misc/misc3.kt
13
288
// DISABLE-ERRORS fun foo() { <selection>a > b[n] && (a < foo(x.bar(n + 2)) || a == n) && b[n - 1] != foo(a + 2)</selection> a > b[n] && a < foo(x.bar(n + 2)) || (a == n) && (b[n - 1] != foo(a + 2)) a > b[n] && (a < foo(x.bar(n + 2)) || (a == n)) && (b[n - 1] != foo(a + 2)) }
apache-2.0
c74f431b894ad2b21c5d6a35f6b6fdbf
47.166667
98
0.368056
2.071942
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/RemoveUselessIsCheckFix.kt
1
1880
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinPsiOnlyQuickFixAction import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.PsiElementSuitabilityCheckers import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.QuickFixesPsiBasedFactory import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtIsExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType class RemoveUselessIsCheckFix(element: KtIsExpression) : KotlinPsiOnlyQuickFixAction<KtIsExpression>(element) { override fun getFamilyName() = KotlinBundle.message("remove.useless.is.check") override fun getText(): String = familyName override fun invoke(project: Project, editor: Editor?, file: KtFile) { element?.run { val expressionsText = this.isNegated.not().toString() val newExpression = KtPsiFactory(project).createExpression(expressionsText) replace(newExpression) } } companion object : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) { override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> { val expression = psiElement.getNonStrictParentOfType<KtIsExpression>() ?: return emptyList() return listOf(RemoveUselessIsCheckFix(expression)) } } }
apache-2.0
8af57bbc84315df3349302691b117f1d
49.810811
158
0.78617
4.783715
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/ui/navigation/library/artists/BrowseArtistFragment.kt
1
3751
package com.kelsos.mbrc.ui.navigation.library.artists import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.core.view.isGone import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import butterknife.BindView import butterknife.ButterKnife import com.google.android.material.snackbar.Snackbar import com.kelsos.mbrc.R import com.kelsos.mbrc.adapters.ArtistEntryAdapter import com.kelsos.mbrc.adapters.ArtistEntryAdapter.MenuItemSelectedListener import com.kelsos.mbrc.annotations.Queue import com.kelsos.mbrc.data.library.Artist import com.kelsos.mbrc.helper.PopupActionHandler import com.kelsos.mbrc.ui.navigation.library.LibraryActivity.Companion.LIBRARY_SCOPE import com.kelsos.mbrc.ui.widgets.EmptyRecyclerView import com.raizlabs.android.dbflow.list.FlowCursorList import toothpick.Scope import toothpick.Toothpick import javax.inject.Inject class BrowseArtistFragment : Fragment(), BrowseArtistView, MenuItemSelectedListener { @BindView(R.id.library_data_list) lateinit var recycler: EmptyRecyclerView @BindView(R.id.empty_view) lateinit var emptyView: View @BindView(R.id.list_empty_title) lateinit var emptyTitle: TextView @Inject lateinit var adapter: ArtistEntryAdapter @Inject lateinit var actionHandler: PopupActionHandler @Inject lateinit var presenter: BrowseArtistPresenter private var scope: Scope? = null private lateinit var syncButton: Button override fun search(term: String) { syncButton.isGone = term.isNotEmpty() } override fun queue(success: Boolean, tracks: Int) { val message = if (success) { getString(R.string.queue_result__success, tracks) } else { getString(R.string.queue_result__failure) } Snackbar.make(recycler, R.string.queue_result__success, Snackbar.LENGTH_SHORT) .setText(message) .show() } override fun onCreate(savedInstanceState: Bundle?) { scope = Toothpick.openScopes(requireActivity().application, LIBRARY_SCOPE, activity, this) scope?.installModules(BrowseArtistModule()) super.onCreate(savedInstanceState) Toothpick.inject(this, scope) } override fun onStart() { super.onStart() presenter.attach(this) adapter.refresh() } override fun onStop() { super.onStop() presenter.detach() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_library_search, container, false) ButterKnife.bind(this, view) emptyTitle.setText(R.string.artists_list_empty) syncButton = view.findViewById<Button>(R.id.list_empty_sync) syncButton.setOnClickListener { presenter.sync() } return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recycler.setHasFixedSize(true) recycler.adapter = adapter recycler.emptyView = emptyView recycler.layoutManager = LinearLayoutManager(recycler.context) adapter.setMenuItemSelectedListener(this) presenter.attach(this) presenter.load() } override fun onMenuItemSelected(menuItem: MenuItem, artist: Artist) { val action = actionHandler.artistSelected(menuItem, artist, requireActivity()) if (action != Queue.PROFILE) { presenter.queue(action, artist) } } override fun onItemClicked(artist: Artist) { actionHandler.artistSelected(artist, requireActivity()) } override fun update(data: FlowCursorList<Artist>) { adapter.update(data) } }
gpl-3.0
90328c646d856059a192195cb4cd0f53
29.495935
94
0.761397
4.257662
false
false
false
false
JetBrains/xodus
environment/src/main/kotlin/jetbrains/exodus/log/Log.kt
1
45983
/** * Copyright 2010 - 2022 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.log import jetbrains.exodus.ArrayByteIterable import jetbrains.exodus.ByteIterable import jetbrains.exodus.ExodusException import jetbrains.exodus.InvalidSettingException import jetbrains.exodus.crypto.cryptBlocksMutable import jetbrains.exodus.io.DataReader import jetbrains.exodus.io.DataWriter import jetbrains.exodus.io.FileDataReader import jetbrains.exodus.io.RemoveBlockType import jetbrains.exodus.kotlin.notNull import jetbrains.exodus.util.DeferredIO import jetbrains.exodus.util.IdGenerator import mu.KLogging import java.io.Closeable import java.io.File import java.util.concurrent.atomic.AtomicReference import kotlin.experimental.xor class Log(val config: LogConfig, expectedEnvironmentVersion: Int) : Closeable { val created = System.currentTimeMillis() @JvmField internal val cache: LogCache @Volatile var isClosing: Boolean = false private set var identity: Int = 0 private set private val reader: DataReader = config.reader private val writer: DataWriter = config.writer private val internalTip: AtomicReference<LogTip> val tip: LogTip get() = internalTip.get() private var bufferedWriter: BufferedDataWriter? = null /** Last ticks when the sync operation was performed. */ private var lastSyncTicks: Long = 0 private val blockListeners = ArrayList<BlockListener>(2) private val readBytesListeners = ArrayList<ReadBytesListener>(2) var startupMetadata: StartupMetadata val isClossedCorrectly: Boolean get() = startupMetadata.isCorrectlyClosed /** Size of single page in log cache. */ var cachePageSize: Int /** * Indicate whether it is needed to perform migration to the format which contains * hash codes of content inside of the pages. */ val formatWithHashCodeIsUsed: Boolean /** Size of a single file of the log in bytes. * @return size of a single log file in bytes. */ val fileLengthBound: Long @Deprecated("for tests only") private var testConfig: LogTestConfig? = null val location: String get() = reader.location val numberOfFiles: Long get() = tip.blockSet.size().toLong() /** * Returns addresses of log files from the newest to the oldest ones. */ val allFileAddresses: LongArray get() = tip.blockSet.array val highAddress: Long get() = tip.highAddress val writtenHighAddress: Long get() = ensureWriter().highAddress val lowAddress: Long get() { val result = tip.blockSet.minimum return result ?: Loggable.NULL_ADDRESS } val highFileAddress: Long get() = getFileAddress(highAddress) val diskUsage: Long get() { val allFiles = tip.allFiles val filesCount = allFiles.size return if (filesCount == 0) 0L else (filesCount - 1) * fileLengthBound + getLastFileSize( allFiles[filesCount - 1], tip ) } val cacheHitRate: Float get() = cache.hitRate() val isReadOnly: Boolean get() = rwIsReadonly private val nullPage: ByteArray @Volatile private var rwIsReadonly: Boolean init { tryLock() try { rwIsReadonly = config.readerWriterProvider?.isReadonly ?: false val fileLength = config.fileSize * 1024L if (reader is FileDataReader) { reader.setLog(this) } val metadata = if (reader is FileDataReader) { StartupMetadata.open(reader, rwIsReadonly) } else { StartupMetadata.createStub(config.cachePageSize, expectedEnvironmentVersion, fileLength) } var needToPerformMigration = false if (metadata != null) { startupMetadata = metadata } else { startupMetadata = StartupMetadata.createStub( config.cachePageSize, expectedEnvironmentVersion, fileLength ) needToPerformMigration = reader.blocks.iterator().hasNext() } if (config.cachePageSize != startupMetadata.pageSize) { logger.warn( "Environment $location was created with cache page size equals to " + "${startupMetadata.pageSize} but provided page size is ${config.cachePageSize} " + "page size will be updated to ${startupMetadata.pageSize}" ) config.cachePageSize = startupMetadata.pageSize } if (fileLength != startupMetadata.fileLengthBoundary) { logger.warn( "Environment $location was created with maximum files size equals to " + "${startupMetadata.fileLengthBoundary} but provided file size is $fileLength " + "file size will be updated to ${startupMetadata.fileLengthBoundary}" ) config.fileSize = startupMetadata.fileLengthBoundary / 1024 } fileLengthBound = startupMetadata.fileLengthBoundary if (fileLengthBound % config.cachePageSize != 0L) { throw InvalidSettingException("File size should be a multiple of cache page size.") } cachePageSize = startupMetadata.pageSize if (expectedEnvironmentVersion != startupMetadata.environmentFormatVersion) { throw ExodusException( "For environment $location expected format version is $expectedEnvironmentVersion " + "but data are stored using version ${startupMetadata.environmentFormatVersion}" ) } val blockSetMutable = BlockSet.Immutable(fileLength).beginWrite() if (!rwIsReadonly && !startupMetadata.isCorrectlyClosed || needToPerformMigration) { if (!startupMetadata.isCorrectlyClosed) { logger.error( "Environment located at ${reader.location} has been closed incorrectly. " + "Data check routine is started to assess data consistency ..." ) } checkLogConsistency(blockSetMutable) if (!startupMetadata.isCorrectlyClosed) { logger.error("Data check is completed for environment ${reader.location}.") } } else { val blockIterator = reader.blocks.iterator() while (blockIterator.hasNext()) { val block = blockIterator.next() blockSetMutable.add(block.address, block) } } val blockSetImmutable = blockSetMutable.endWrite() val memoryUsage = config.memoryUsage val nonBlockingCache = config.isNonBlockingCache val useSoftReferences = config.cacheUseSoftReferences val generationCount = config.cacheGenerationCount cache = if (memoryUsage != 0L) { if (config.isSharedCache) getSharedCache(memoryUsage, cachePageSize, nonBlockingCache, useSoftReferences, generationCount) else SeparateLogCache(memoryUsage, cachePageSize, nonBlockingCache, useSoftReferences, generationCount) } else { val memoryUsagePercentage = config.memoryUsagePercentage if (config.isSharedCache) getSharedCache( memoryUsagePercentage, cachePageSize, nonBlockingCache, useSoftReferences, generationCount ) else SeparateLogCache( memoryUsagePercentage, cachePageSize, nonBlockingCache, useSoftReferences, generationCount ) } DeferredIO.getJobProcessor() isClosing = false val lastFileAddress = blockSetMutable.maximum updateLogIdentity() if (lastFileAddress == null) { internalTip = AtomicReference(LogTip(fileLengthBound)) } else { val lastFileLength = blockSetMutable.getBlock(lastFileAddress).length() val currentHighAddress = lastFileAddress + lastFileLength val highPageAddress = getHighPageAddress(currentHighAddress) val highPageContent = ByteArray(cachePageSize) val tmpTip = LogTip( highPageContent, highPageAddress, cachePageSize, currentHighAddress, currentHighAddress, blockSetImmutable ) this.internalTip = AtomicReference(tmpTip) val highPageSize = if (currentHighAddress == 0L) { 0 } else { readBytes(highPageContent, highPageAddress) } val proposedTip = LogTip( highPageContent, highPageAddress, highPageSize, currentHighAddress, currentHighAddress, blockSetImmutable ) this.internalTip.set(proposedTip) tmpTip.xxHash64.close() if (!startupMetadata.isCorrectlyClosed || needToPerformMigration) { // here we should check whether last loggable is written correctly val lastFileLoggables = LoggableIterator(this, lastFileAddress) var approvedHighAddress: Long = lastFileAddress try { while (lastFileLoggables.hasNext()) { val loggable = lastFileLoggables.next() val dataLength = if (NullLoggable.isNullLoggable(loggable)) 0 else loggable.dataLength if (dataLength > 0) { // if not null loggable read all data to the end val data = loggable.data.iterator() for (i in 0 until dataLength) { if (!data.hasNext()) { throw ExodusException( "Can't read loggable fully" + LogUtil.getWrongAddressErrorMessage( data.address, fileLengthBound ) ) } data.next() } } else if (dataLength < 0) { // XD-728: // this is either data corruption or encrypted database // anyway recovery should stop at this point break } val approvedHighAddressCandidate = loggable.end() if (approvedHighAddressCandidate > currentHighAddress) { // XD-728: // this is either data corruption or encrypted database // anyway recovery should stop at this point break } approvedHighAddress = approvedHighAddressCandidate } } catch (e: ExodusException) { // if an exception is thrown then last loggable wasn't read correctly logger.info(e) { "Exception on Log recovery. Approved high address = $approvedHighAddress" } } this.internalTip.set(proposedTip.withApprovedAddress(approvedHighAddress)) } sync() } if (needToPerformMigration) { val highAddress = highAddress val writtenInPage = highAddress and (cachePageSize - 1).toLong() if (writtenInPage > 0) { padWholePageWithNulls() } } formatWithHashCodeIsUsed = !needToPerformMigration nullPage = BufferedDataWriter.generateNullPage(cachePageSize) if (config.isWarmup) { warmup() } } catch (ex: RuntimeException) { release() throw ex } } private fun padWholePageWithNulls() { beginWrite() val writer = ensureWriter() beforeWrite(writer) try { writer.padWholePageWithNulls() writer.commit(false) writer.flush(false) } finally { endWrite() } } fun dataSpaceLeftInPage(address: Long): Int { val pageAddress = (cachePageSize - 1).toLong().inv() and address val writtenSpace = address - pageAddress assert(writtenSpace >= 0 && writtenSpace < cachePageSize - BufferedDataWriter.LOGGABLE_DATA) return cachePageSize - BufferedDataWriter.LOGGABLE_DATA - writtenSpace.toInt() } fun switchToReadOnlyMode() { rwIsReadonly = true } fun updateStartUpDbRoot(rootAddress: Long) { startupMetadata.rootAddress = rootAddress } fun getStartUpDbRoot(): Long { return startupMetadata.rootAddress } private fun checkLogConsistency(blockSetMutable: BlockSet.Mutable) { val blockIterator = reader.blocks.iterator() if (!blockIterator.hasNext()) { return } if (config.isCleanDirectoryExpected) { throw ExodusException("Clean log is expected") } val clearInvalidLog = config.isClearInvalidLog var hasNext: Boolean do { val block = blockIterator.next() val address = block.address val blockLength = block.length() var clearLogReason: String? = null // if it is not the last file and its size is not as expected hasNext = blockIterator.hasNext() if (blockLength > fileLengthBound || hasNext && blockLength != fileLengthBound) { clearLogReason = "Unexpected file length" + LogUtil.getWrongAddressErrorMessage(address, fileLengthBound) } // if the file address is not a multiple of fileLengthBound if (clearLogReason == null && address != getFileAddress(address)) { if (rwIsReadonly || !clearInvalidLog) { throw ExodusException( "Unexpected file address " + LogUtil.getLogFilename(address) + LogUtil.getWrongAddressErrorMessage( address, fileLengthBound ) ) } clearLogReason = "Unexpected file address " + LogUtil.getLogFilename(address) + LogUtil.getWrongAddressErrorMessage(address, fileLengthBound) } if (clearLogReason != null) { if (rwIsReadonly || !clearInvalidLog) { throw ExodusException(clearLogReason) } logger.error("Clearing log due to: $clearLogReason") blockSetMutable.clear() writer.clear() break } val page = ByteArray(cachePageSize) for (pageAddress in 0 until blockLength step cachePageSize.toLong()) { if (formatWithHashCodeIsUsed) { val read = block.read(page, block.address + pageAddress, 0, cachePageSize) if (hasNext || !rwIsReadonly) { if (read != cachePageSize) { DataCorruptionException.raise( "Page is broken. Expected and actual" + " page sizes are different. {expected: $cachePageSize , actual: $read}", this, pageAddress ) } BufferedDataWriter.checkPageConsistency(pageAddress, page, cachePageSize, this) } } } blockSetMutable.add(address, block) } while (hasNext) } private fun closeWriter() { if (bufferedWriter != null) { throw IllegalStateException("Unexpected write in progress") } writer.close() } fun beginWrite(): LogTip { val writer = BufferedDataWriter(this, this.writer, tip) this.bufferedWriter = writer return writer.startingTip } fun abortWrite() { this.bufferedWriter = null } fun endWrite(): LogTip { val writer = ensureWriter() val logTip = writer.startingTip val updatedTip = writer.updatedTip compareAndSetTip(logTip, updatedTip) bufferedWriter = null return updatedTip } fun compareAndSetTip(logTip: LogTip, updatedTip: LogTip): LogTip { if (!internalTip.compareAndSet(logTip, updatedTip)) { throw ExodusException("write start/finish mismatch") } if (logTip.xxHash64 != updatedTip.xxHash64) { logTip.xxHash64.close() } return updatedTip } fun getFileAddress(address: Long): Long { return address - address % fileLengthBound } fun getNextFileAddress(fileAddress: Long): Long { val files = tip.blockSet.getFilesFrom(fileAddress) if (files.hasNext()) { val result = files.nextLong() if (result != fileAddress) { throw ExodusException("There is no file by address $fileAddress") } if (files.hasNext()) { return files.nextLong() } } return Loggable.NULL_ADDRESS } private fun isLastFileAddress(address: Long, logTip: LogTip): Boolean { return getFileAddress(address) == getFileAddress(logTip.highAddress) } fun isLastWrittenFileAddress(address: Long): Boolean { return getFileAddress(address) == getFileAddress(writtenHighAddress) } fun adjustLoggableAddress(address: Long, offset: Long): Long { if (!formatWithHashCodeIsUsed) { return address + offset } val cachePageReminderMask = (cachePageSize - 1).toLong() val writtenInPage = address and cachePageReminderMask val pageAddress = address and (cachePageReminderMask.inv()) val adjustedPageSize = cachePageSize - BufferedDataWriter.LOGGABLE_DATA val writtenSincePageStart = writtenInPage + offset val fullPages = writtenSincePageStart / adjustedPageSize return pageAddress + writtenSincePageStart + fullPages * BufferedDataWriter.LOGGABLE_DATA } fun hasAddress(address: Long): Boolean { val fileAddress = getFileAddress(address) val logTip = tip val files = logTip.blockSet.getFilesFrom(fileAddress) if (!files.hasNext()) { return false } val leftBound = files.nextLong() return leftBound == fileAddress && leftBound + getFileSize(leftBound, logTip) > address } fun hasAddressRange(from: Long, to: Long): Boolean { var fileAddress = getFileAddress(from) val logTip = tip val files = logTip.blockSet.getFilesFrom(fileAddress) do { if (!files.hasNext() || files.nextLong() != fileAddress) { return false } fileAddress += getFileSize(fileAddress, logTip) } while (fileAddress in (from + 1)..to) return true } @JvmOverloads fun getFileSize(fileAddress: Long, logTip: LogTip = tip): Long { // readonly files (not last ones) all have the same size return if (!isLastFileAddress(fileAddress, logTip)) { fileLengthBound } else getLastFileSize(fileAddress, logTip) } private fun getLastFileSize(fileAddress: Long, logTip: LogTip): Long { val highAddress = logTip.highAddress val result = highAddress % fileLengthBound return if (result == 0L && highAddress != fileAddress) { fileLengthBound } else result } fun getHighPage(alignedAddress: Long): ByteArray? { val tip = tip return if (tip.pageAddress == alignedAddress && tip.count >= 0) { tip.bytes } else null } fun getCachedPage(pageAddress: Long): ByteArray { return cache.getPage(this, pageAddress) } fun addBlockListener(listener: BlockListener) { synchronized(blockListeners) { blockListeners.add(listener) } } fun addReadBytesListener(listener: ReadBytesListener) { synchronized(readBytesListeners) { readBytesListeners.add(listener) } } /** * Reads a random access loggable by specified address in the log. * * @param address - location of a loggable in the log. * @return instance of a loggable. */ fun read(address: Long): RandomAccessLoggable { return read(readIteratorFrom(address), address) } fun getWrittenLoggableType(address: Long, max: Byte): Byte { return ensureWriter().getByte(address, max) } @JvmOverloads fun read(it: ByteIteratorWithAddress, address: Long = it.address): RandomAccessLoggable { val type = it.next() xor 0x80.toByte() return if (NullLoggable.isNullLoggable(type)) { NullLoggable.create(address, adjustLoggableAddress(address, 1)) } else read(type, it, address) } /** * Just like [.read] reads loggable which never can be a [NullLoggable]. * * @return a loggable which is not[NullLoggable] */ fun readNotNull(it: ByteIteratorWithAddress, address: Long): RandomAccessLoggable { return read(it.next() xor 0x80.toByte(), it, address) } private fun read(type: Byte, it: ByteIteratorWithAddress, address: Long): RandomAccessLoggable { val structureId = CompressedUnsignedLongByteIterable.getInt(it) val dataLength = CompressedUnsignedLongByteIterable.getInt(it) val dataAddress = it.address if (dataLength > 0 && it.availableInCurrentPage(dataLength)) { val end = dataAddress + dataLength return SinglePageLoggable( address, end, type, structureId, dataAddress, it.currentPage, it.offset, dataLength ) } val data = MultiPageByteIterableWithAddress(dataAddress, dataLength, this) return MultiPageLoggable( address, type, data, dataLength, structureId, this ) } fun getLoggableIterator(startAddress: Long): LoggableIterator { return LoggableIterator(this, startAddress) } fun tryWrite(type: Byte, structureId: Int, data: ByteIterable): Long { // allow new file creation only if new file starts loggable val result = writeContinuously(type, structureId, data) if (result < 0) { // rollback loggable and pad last file with nulls doPadWithNulls() } return result } /** * Writes a loggable to the end of the log padding the log with nulls if necessary. * So auto-alignment guarantees the loggable to be placed in a single file. * * @param loggable - loggable to write. * @return address where the loggable was placed. */ fun write(loggable: Loggable): Long { return write(loggable.type, loggable.structureId, loggable.data) } fun write(type: Byte, structureId: Int, data: ByteIterable): Long { // allow new file creation only if new file starts loggable var result = writeContinuously(type, structureId, data) if (result < 0) { // rollback loggable and pad last file with nulls doPadWithNulls() result = writeContinuously(type, structureId, data) if (result < 0) { throw TooBigLoggableException() } } return result } /** * Returns the first loggable in the log of specified type. * * @param type type of loggable. * @return loggable or null if it doesn't exists. */ fun getFirstLoggableOfType(type: Int): Loggable? { val logTip = tip val files = logTip.blockSet.getFilesFrom(0) val approvedHighAddress = logTip.approvedHighAddress while (files.hasNext()) { val fileAddress = files.nextLong() val it = getLoggableIterator(fileAddress) while (it.hasNext()) { val loggable = it.next() if (loggable == null || loggable.address >= fileAddress + fileLengthBound) { break } if (loggable.type.toInt() == type) { return loggable } if (loggable.end() == approvedHighAddress) { break } } } return null } /** * Returns the last loggable in the log of specified type. * * @param type type of loggable. * @return loggable or null if it doesn't exists. */ fun getLastLoggableOfType(type: Int): Loggable? { var result: Loggable? = null val logTip = tip val approvedHighAddress = logTip.approvedHighAddress for (fileAddress in logTip.blockSet.array) { if (result != null) { break } val it = getLoggableIterator(fileAddress) while (it.hasNext()) { val loggable = it.next() if (loggable == null || loggable.address >= fileAddress + fileLengthBound) { break } if (loggable.type.toInt() == type) { result = loggable } if (loggable.end() == approvedHighAddress) { break } } } return result } /** * Returns the last loggable in the log of specified type which address is less than beforeAddress. * * @param type type of loggable. * @return loggable or null if it doesn't exists. */ fun getLastLoggableOfTypeBefore(type: Int, beforeAddress: Long, logTip: LogTip): Loggable? { var result: Loggable? = null for (fileAddress in logTip.blockSet.array) { if (result != null) { break } if (fileAddress >= beforeAddress) { continue } val it = getLoggableIterator(fileAddress) while (it.hasNext()) { val loggable = it.next() ?: break val address = loggable.address if (address >= beforeAddress || address >= fileAddress + fileLengthBound) { break } if (loggable.type.toInt() == type) { result = loggable } } } return result } fun isImmutableFile(fileAddress: Long): Boolean { return fileAddress + fileLengthBound <= tip.approvedHighAddress } @JvmOverloads fun flush(forceSync: Boolean = false) { ensureWriter().flush(true) if (forceSync || config.isDurableWrite) { sync() } } fun sync() { writer.sync() lastSyncTicks = System.currentTimeMillis() } override fun close() { isClosing = true if (!rwIsReadonly) { if (formatWithHashCodeIsUsed) { beginWrite() try { val writer = ensureWriter() beforeWrite(writer) //we pad page with nulls to ensure that all pages could be checked on consistency //by hash code which is stored at the end of the page. val written = writer.padPageWithNulls() if (written > 0) { writer.commit(true) writer.flush(true) closeFullFileIfNecessary(writer) } } finally { endWrite() } } sync() if (reader is FileDataReader) { startupMetadata.closeAndUpdate(reader) } } reader.close() closeWriter() val logTip = tip //remove all files from log, so access to them become impossible if read of data //will be concurrently happen compareAndSetTip(logTip, LogTip(fileLengthBound, logTip.pageAddress, logTip.highAddress)) release() } fun release() { writer.release() } fun clear(): LogTip { val logTip = tip cache.clear() reader.close() closeWriter() writer.clear() val updatedTip = LogTip(fileLengthBound) compareAndSetTip(logTip, updatedTip) this.bufferedWriter = null updateLogIdentity() return updatedTip } // for tests only @Deprecated("for tests only") fun forgetFile(address: Long) { beginWrite() forgetFiles(longArrayOf(address)) endWrite() } @Deprecated("for tests only") fun clearCache() { cache.clear() } fun forgetFiles(files: LongArray) { val blockSetMutable = ensureWriter().blockSetMutable for (file in files) { blockSetMutable.remove(file) } } @JvmOverloads fun removeFile( address: Long, rbt: RemoveBlockType = RemoveBlockType.Delete, blockSetMutable: BlockSet.Mutable? = null ) { val block = tip.blockSet.getBlock(address) val listeners = blockListeners.notifyListeners { it.beforeBlockDeleted(block, reader, writer) } try { if (!rwIsReadonly) { writer.removeBlock(address, rbt) } // remove address of file of the list blockSetMutable?.remove(address) // clear cache clearFileFromLogCache(address) } finally { listeners.forEach { it.afterBlockDeleted(address, reader, writer) } } } fun ensureWriter(): BufferedDataWriter { return bufferedWriter ?: throw ExodusException("write not in progress") } fun clearFileFromLogCache(address: Long, offset: Long = 0L) { var off = offset while (off < fileLengthBound) { cache.removePage(this, address + off) off += cachePageSize } } fun doPadWithNulls() { val writer = ensureWriter() if (writer.padWithNulls(fileLengthBound, nullPage)) { writer.commit(true) closeFullFileIfNecessary(writer) } } fun readBytes(output: ByteArray, pageAddress: Long): Int { val fileAddress = getFileAddress(pageAddress) val logTip = tip val files = logTip.blockSet.getFilesFrom(fileAddress) if (files.hasNext()) { val leftBound = files.nextLong() val fileSize = getFileSize(leftBound, logTip) if (leftBound == fileAddress && fileAddress + fileSize > pageAddress) { val block = logTip.blockSet.getBlock(fileAddress) val readBytes = block.read(output, pageAddress - fileAddress, 0, output.size) val checkConsistency = config.isCheckPagesAtRuntime && formatWithHashCodeIsUsed && (!rwIsReadonly || pageAddress < (highAddress and ((cachePageSize - 1).inv()).toLong())) if (checkConsistency) { if (readBytes < cachePageSize) { DataCorruptionException.raise( "Page size less than expected. " + "{actual : $readBytes, expected $cachePageSize }.", this, pageAddress ) } BufferedDataWriter.checkPageConsistency(pageAddress, output, cachePageSize, this) } val cipherProvider = config.cipherProvider if (cipherProvider != null) { val encryptedBytes = if (readBytes < cachePageSize) { readBytes } else { if (formatWithHashCodeIsUsed) { cachePageSize - BufferedDataWriter.HASH_CODE_SIZE } else { cachePageSize } } cryptBlocksMutable( cipherProvider, config.cipherKey, config.cipherBasicIV, pageAddress, output, 0, encryptedBytes, LogUtil.LOG_BLOCK_ALIGNMENT ) } notifyReadBytes(output, readBytes) return readBytes } if (fileAddress < (logTip.blockSet.minimum ?: -1L)) { BlockNotFoundException.raise("Address is out of log space, underflow", this, pageAddress) } if (fileAddress >= (logTip.blockSet.maximum ?: -1L)) { BlockNotFoundException.raise("Address is out of log space, overflow", this, pageAddress) } } BlockNotFoundException.raise(this, pageAddress) return 0 } /** * Returns iterator which reads raw bytes of the log starting from specified address. * * @param address * @return instance of ByteIterator */ fun readIteratorFrom(address: Long): DataIterator { return DataIterator(this, address) } private fun tryLock() { if (!config.isLockIgnored) { val lockTimeout = config.lockTimeout if (!writer.lock(lockTimeout)) { throw ExodusException( "Can't acquire environment lock after " + lockTimeout + " ms.\n\n Lock owner info: \n" + writer.lockInfo() ) } } } fun getHighPageAddress(highAddress: Long): Long { var alignment = highAddress.toInt() and cachePageSize - 1 if (alignment == 0 && highAddress > 0) { alignment = cachePageSize } return highAddress - alignment // aligned address } fun writeContinuously(type: Byte, structureId: Int, data: ByteIterable): Long { if (rwIsReadonly) { throw ExodusException("Environment is working in read-only mode. No writes are allowed") } val writer = ensureWriter() var result = beforeWrite(writer) val isNull = NullLoggable.isNullLoggable(type) var recordLength = 1 if (isNull) { writer.write(type xor 0x80.toByte(), result) } else { val structureIdIterable = CompressedUnsignedLongByteIterable.getIterable(structureId.toLong()) val dataLength = data.length val dataLengthIterable = CompressedUnsignedLongByteIterable.getIterable(dataLength.toLong()) recordLength += structureIdIterable.length recordLength += dataLengthIterable.length recordLength += dataLength val leftInPage = cachePageSize - (result.toInt() and (cachePageSize - 1)) - BufferedDataWriter.LOGGABLE_DATA val delta = if (leftInPage in 1 until recordLength && recordLength < (cachePageSize shr 4)) { leftInPage + BufferedDataWriter.LOGGABLE_DATA } else { 0 } if (!writer.fitsIntoSingleFile(fileLengthBound, recordLength + delta)) { return -1L } if (delta > 0) { val written = writer.padPageWithNulls() assert(written == delta) result += written assert(result % cachePageSize.toLong() == 0L) } writer.write(type xor 0x80.toByte(), result) writeByteIterable(writer, structureIdIterable) writeByteIterable(writer, dataLengthIterable) if (dataLength > 0) { writeByteIterable(writer, data) } } writer.commit(true) closeFullFileIfNecessary(writer) return result } private fun beforeWrite(writer: BufferedDataWriter): Long { val result = writer.highAddress // begin of test-only code @Suppress("DEPRECATION") val testConfig = this.testConfig if (testConfig != null) { val maxHighAddress = testConfig.maxHighAddress if (maxHighAddress in 0..result) { throw ExodusException("Can't write more than $maxHighAddress") } } // end of test-only code if (!this.writer.isOpen) { val fileAddress = getFileAddress(result) val block = if (writer.highAddress <= highAddress) { writer.openOrCreateBlock(fileAddress, highAddress % fileLengthBound) } else { assert(writer.highAddress % fileLengthBound == 0L) writer.openOrCreateBlock(fileAddress, 0) } val fileCreated = !writer.blockSetMutable.contains(fileAddress) if (fileCreated) { writer.blockSetMutable.add(fileAddress, block) // fsync the directory to ensure we will find the log file in the directory after system crash this.writer.syncDirectory() notifyBlockCreated(fileAddress) } else { notifyBlockModified(fileAddress) } } return result } private fun closeFullFileIfNecessary(writer: BufferedDataWriter) { val shouldCreateNewFile = writer.isFileFull(fileLengthBound) if (shouldCreateNewFile) { // Don't forget to fsync the old file before closing it, otherwise will get a corrupted DB in the case of a // system failure: flush(true) this.writer.close() // verify if last block is consistent val blockSet = writer.blockSetMutable val lastFile = blockSet.maximum if (lastFile != null) { val block = blockSet.getBlock(lastFile) val refreshed = block.refresh() if (block !== refreshed) { blockSet.add(lastFile, refreshed) } val length = refreshed.length() if (length < fileLengthBound) { throw IllegalStateException( "File's too short (" + LogUtil.getLogFilename(lastFile) + "), block.length() = " + length + ", fileLengthBound = " + fileLengthBound ) } if (config.isFullFileReadonly && block is File) { block.setReadOnly() } } } else if (System.currentTimeMillis() > lastSyncTicks + config.syncPeriod) { flush(true) } } /** * Sets LogTestConfig. * Is destined for tests only, please don't set a not-null value in application code. */ @Deprecated("for tests only") fun setLogTestConfig(testConfig: LogTestConfig?) { @Suppress("DEPRECATION") this.testConfig = testConfig } private fun notifyBlockCreated(address: Long) { val block = tip.blockSet.getBlock(address) blockListeners.notifyListeners { it.blockCreated(block, reader, writer) } } private fun notifyBlockModified(address: Long) { val block = tip.blockSet.getBlock(address) blockListeners.notifyListeners { it.blockModified(block, reader, writer) } } private fun notifyReadBytes(bytes: ByteArray, count: Int) { readBytesListeners.notifyListeners { it.bytesRead(bytes, count) } } private inline fun <reified T> List<T>.notifyListeners(call: (T) -> Unit): Array<T> { val listeners = synchronized(this) { this.toTypedArray() } listeners.forEach { call(it) } return listeners } private fun updateLogIdentity() { identity = identityGenerator.nextId() } companion object : KLogging() { private val identityGenerator = IdGenerator() @Volatile private var sharedCache: SharedLogCache? = null /** * For tests only!!! */ @JvmStatic @Deprecated("for tests only") fun invalidateSharedCache() { synchronized(Log::class.java) { sharedCache = null } } private fun getSharedCache( memoryUsage: Long, pageSize: Int, nonBlocking: Boolean, useSoftReferences: Boolean, cacheGenerationCount: Int ): LogCache { var result = sharedCache if (result == null) { synchronized(Log::class.java) { if (sharedCache == null) { sharedCache = SharedLogCache( memoryUsage, pageSize, nonBlocking, useSoftReferences, cacheGenerationCount ) } result = sharedCache } } return result.notNull.also { cache -> checkCachePageSize(pageSize, cache) checkUseSoftReferences(useSoftReferences, cache) } } private fun getSharedCache( memoryUsagePercentage: Int, pageSize: Int, nonBlocking: Boolean, useSoftReferences: Boolean, cacheGenerationCount: Int ): LogCache { var result = sharedCache if (result == null) { synchronized(Log::class.java) { if (sharedCache == null) { sharedCache = SharedLogCache( memoryUsagePercentage, pageSize, nonBlocking, useSoftReferences, cacheGenerationCount ) } result = sharedCache } } return result.notNull.also { cache -> checkCachePageSize(pageSize, cache) checkUseSoftReferences(useSoftReferences, cache) } } private fun checkCachePageSize(pageSize: Int, cache: LogCache) { if (cache.pageSize != pageSize) { throw ExodusException( "SharedLogCache was created with page size ${cache.pageSize}" + " and then requested with page size $pageSize. EnvironmentConfig.LOG_CACHE_PAGE_SIZE is set manually." ) } } private fun checkUseSoftReferences(useSoftReferences: Boolean, cache: SharedLogCache) { if (cache.useSoftReferences != useSoftReferences) { throw ExodusException( "SharedLogCache was created with useSoftReferences = ${cache.useSoftReferences}" + " and then requested with useSoftReferences = $useSoftReferences. EnvironmentConfig.LOG_CACHE_USE_SOFT_REFERENCES is set manually." ) } } /** * Writes byte iterator to the log returning its length. * * @param writer a writer * @param iterable byte iterable to write. * @return */ private fun writeByteIterable(writer: BufferedDataWriter, iterable: ByteIterable) { val length = iterable.length if (iterable is ArrayByteIterable) { val bytes = iterable.baseBytes val offset = iterable.baseOffset() if (length == 1) { writer.write(bytes[0], -1) } else { writer.write(bytes, offset, length) } } else if (length >= 3) { val bytes = iterable.baseBytes val offset = iterable.baseOffset() writer.write(bytes, offset, length) } else { val iterator = iterable.iterator() writer.write(iterator.next(), -1) if (length == 2) { writer.write(iterator.next(), -1) } } } } }
apache-2.0
ba1f367db344a684a75670fdc241e96c
34.618125
159
0.558533
5.209948
false
false
false
false
siosio/intellij-community
plugins/git4idea/src/git4idea/config/GitVcsPanel.kt
1
21912
// 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 git4idea.config import com.intellij.application.options.editor.CheckboxDescriptor import com.intellij.application.options.editor.checkBox import com.intellij.dvcs.branch.DvcsSyncSettings import com.intellij.dvcs.repo.VcsRepositoryManager import com.intellij.dvcs.repo.VcsRepositoryMappingListener import com.intellij.dvcs.ui.DvcsBundle import com.intellij.ide.ui.search.OptionDescription import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.application.runInEdt import com.intellij.openapi.components.service import com.intellij.openapi.options.BoundCompositeConfigurable import com.intellij.openapi.options.SearchableConfigurable import com.intellij.openapi.options.UnnamedConfigurable import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.options.advanced.AdvancedSettingsChangeListener import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsEnvCustomizer import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager import com.intellij.openapi.vcs.update.AbstractCommonUpdateAction import com.intellij.ui.* import com.intellij.ui.components.TextComponentEmptyText import com.intellij.ui.components.fields.ExpandableTextField import com.intellij.ui.layout.* import com.intellij.util.Function import com.intellij.util.execution.ParametersListUtil import com.intellij.util.ui.UIUtil import com.intellij.util.ui.VcsExecutablePathSelector import com.intellij.vcs.commit.CommitModeManager import com.intellij.vcs.log.VcsLogFilterCollection.STRUCTURE_FILTER import com.intellij.vcs.log.impl.MainVcsLogUiProperties import com.intellij.vcs.log.ui.VcsLogColorManagerImpl import com.intellij.vcs.log.ui.filter.StructureFilterPopupComponent import com.intellij.vcs.log.ui.filter.VcsLogClassicFilterUi import git4idea.GitVcs import git4idea.branch.GitBranchIncomingOutgoingManager import git4idea.config.gpg.GpgSignConfigurableRow.Companion.createGpgSignRow import git4idea.i18n.GitBundle.message import git4idea.index.canEnableStagingArea import git4idea.index.enableStagingArea import git4idea.repo.GitRepositoryManager import git4idea.update.GitUpdateProjectInfoLogProperties import git4idea.update.getUpdateMethods import org.jetbrains.annotations.CalledInAny import java.awt.Color import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import javax.swing.border.Border private fun gitSharedSettings(project: Project) = GitSharedSettings.getInstance(project) private fun projectSettings(project: Project) = GitVcsSettings.getInstance(project) private val applicationSettings get() = GitVcsApplicationSettings.getInstance() private val gitOptionGroupName get() = message("settings.git.option.group") // @formatter:off private fun cdSyncBranches(project: Project) = CheckboxDescriptor(DvcsBundle.message("sync.setting"), PropertyBinding({ projectSettings(project).syncSetting == DvcsSyncSettings.Value.SYNC }, { projectSettings(project).syncSetting = if (it) DvcsSyncSettings.Value.SYNC else DvcsSyncSettings.Value.DONT_SYNC }), groupName = gitOptionGroupName) private fun cdAddCherryPickSuffix(project: Project) = CheckboxDescriptor(message("settings.add.suffix"), PropertyBinding({ projectSettings(project).shouldAddSuffixToCherryPicksOfPublishedCommits() }, { projectSettings(project).setAddSuffixToCherryPicks(it) }), groupName = gitOptionGroupName) private fun cdWarnAboutCrlf(project: Project) = CheckboxDescriptor(message("settings.crlf"), PropertyBinding({ projectSettings(project).warnAboutCrlf() }, { projectSettings(project).setWarnAboutCrlf(it) }), groupName = gitOptionGroupName) private fun cdWarnAboutDetachedHead(project: Project) = CheckboxDescriptor(message("settings.detached.head"), PropertyBinding({ projectSettings(project).warnAboutDetachedHead() }, { projectSettings(project).setWarnAboutDetachedHead(it) }), groupName = gitOptionGroupName) private fun cdAutoUpdateOnPush(project: Project) = CheckboxDescriptor(message("settings.auto.update.on.push.rejected"), PropertyBinding({ projectSettings(project).autoUpdateIfPushRejected() }, { projectSettings(project).setAutoUpdateIfPushRejected(it) }), groupName = gitOptionGroupName) private fun cdShowCommitAndPushDialog(project: Project) = CheckboxDescriptor(message("settings.push.dialog"), PropertyBinding({ projectSettings(project).shouldPreviewPushOnCommitAndPush() }, { projectSettings(project).setPreviewPushOnCommitAndPush(it) }), groupName = gitOptionGroupName) private fun cdHidePushDialogForNonProtectedBranches(project: Project) = CheckboxDescriptor(message("settings.push.dialog.for.protected.branches"), PropertyBinding({ projectSettings(project).isPreviewPushProtectedOnly }, { projectSettings(project).isPreviewPushProtectedOnly = it }), groupName = gitOptionGroupName) private val cdOverrideCredentialHelper get() = CheckboxDescriptor(message("settings.credential.helper"), PropertyBinding({ applicationSettings.isUseCredentialHelper }, { applicationSettings.isUseCredentialHelper = it }), groupName = gitOptionGroupName) private fun synchronizeBranchProtectionRules(project: Project) = CheckboxDescriptor(message("settings.synchronize.branch.protection.rules"), PropertyBinding({gitSharedSettings(project).isSynchronizeBranchProtectionRules}, { gitSharedSettings(project).isSynchronizeBranchProtectionRules = it }), groupName = gitOptionGroupName, comment = message("settings.synchronize.branch.protection.rules.description")) private val cdEnableStagingArea get() = CheckboxDescriptor(message("settings.enable.staging.area"), PropertyBinding({ applicationSettings.isStagingAreaEnabled }, { enableStagingArea(it) }), groupName = gitOptionGroupName, comment = message("settings.enable.staging.area.comment")) // @formatter:on internal fun gitOptionDescriptors(project: Project): List<OptionDescription> { val list = mutableListOf( cdAutoUpdateOnPush(project), cdWarnAboutCrlf(project), cdWarnAboutDetachedHead(project), cdEnableStagingArea ) val manager = GitRepositoryManager.getInstance(project) if (manager.moreThanOneRoot()) { list += cdSyncBranches(project) } return list.map(CheckboxDescriptor::asOptionDescriptor) } internal class GitVcsPanel(private val project: Project) : BoundCompositeConfigurable<UnnamedConfigurable>(message("settings.git.option.group"), "project.propVCSSupport.VCSs.Git"), SearchableConfigurable { private val projectSettings by lazy { GitVcsSettings.getInstance(project) } @Volatile private var versionCheckRequested = false private val currentUpdateInfoFilterProperties = MyLogProperties(project.service<GitUpdateProjectInfoLogProperties>()) private val pathSelector: VcsExecutablePathSelector by lazy { VcsExecutablePathSelector(GitVcs.NAME, disposable!!, object : VcsExecutablePathSelector.ExecutableHandler { override fun patchExecutable(executable: String): String? { return GitExecutableDetector.patchExecutablePath(executable) } override fun testExecutable(executable: String) { testGitExecutable(executable) } }) } private fun testGitExecutable(pathToGit: String) { val modalityState = ModalityState.stateForComponent(pathSelector.mainPanel) val errorNotifier = InlineErrorNotifierFromSettings( GitExecutableInlineComponent(pathSelector.errorComponent, modalityState, null), modalityState, disposable!! ) object : Task.Modal(project, message("git.executable.version.progress.title"), true) { private lateinit var gitVersion: GitVersion override fun run(indicator: ProgressIndicator) { val executableManager = GitExecutableManager.getInstance() val executable = executableManager.getExecutable(pathToGit) executableManager.dropVersionCache(executable) gitVersion = executableManager.identifyVersion(executable) } override fun onThrowable(error: Throwable) { val problemHandler = findGitExecutableProblemHandler(project) problemHandler.showError(error, errorNotifier) } override fun onSuccess() { if (gitVersion.isSupported) { errorNotifier.showMessage(message("git.executable.version.is", gitVersion.presentation)) } else { showUnsupportedVersionError(project, gitVersion, errorNotifier) } } }.queue() } private inner class InlineErrorNotifierFromSettings(inlineComponent: InlineComponent, private val modalityState: ModalityState, disposable: Disposable) : InlineErrorNotifier(inlineComponent, modalityState, disposable) { @CalledInAny override fun showError(text: String, description: String?, fixOption: ErrorNotifier.FixOption?) { if (fixOption is ErrorNotifier.FixOption.Configure) { super.showError(text, description, null) } else { super.showError(text, description, fixOption) } } override fun resetGitExecutable() { super.resetGitExecutable() GitExecutableManager.getInstance().getDetectedExecutable(project) // populate cache invokeAndWaitIfNeeded(modalityState) { resetPathSelector() } } } private fun getCurrentExecutablePath(): String? = pathSelector.currentPath?.takeIf { it.isNotBlank() } private fun RowBuilder.gitExecutableRow() = row { pathSelector.mainPanel(growX) .onReset { resetPathSelector() } .onIsModified { val projectSettingsPathToGit = projectSettings.pathToGit val currentPath = getCurrentExecutablePath() if (pathSelector.isOverridden) { currentPath != projectSettingsPathToGit } else { currentPath != applicationSettings.savedPathToGit || projectSettingsPathToGit != null } } .onApply { val executablePathOverridden = pathSelector.isOverridden val currentPath = getCurrentExecutablePath() if (executablePathOverridden) { projectSettings.pathToGit = currentPath } else { applicationSettings.setPathToGit(currentPath) projectSettings.pathToGit = null } validateExecutableOnceAfterClose() VcsDirtyScopeManager.getInstance(project).markEverythingDirty() } } private fun resetPathSelector() { val projectSettingsPathToGit = projectSettings.pathToGit val detectedExecutable = try { GitExecutableManager.getInstance().getDetectedExecutable(project) } catch (e: ProcessCanceledException) { GitExecutableDetector.getDefaultExecutable() } pathSelector.reset(applicationSettings.savedPathToGit, projectSettingsPathToGit != null, projectSettingsPathToGit, detectedExecutable) } /** * Special method to check executable after it has been changed through settings */ private fun validateExecutableOnceAfterClose() { if (versionCheckRequested) return versionCheckRequested = true runInEdt(ModalityState.NON_MODAL) { versionCheckRequested = false runBackgroundableTask(message("git.executable.version.progress.title"), project, true) { GitExecutableManager.getInstance().testGitExecutableVersionValid(project) } } } private fun RowBuilder.branchUpdateInfoRow() { row { cell { label(message("settings.explicitly.check") + " ") comboBox( EnumComboBoxModel(GitIncomingCheckStrategy::class.java), { projectSettings.incomingCheckStrategy }, { selectedStrategy -> projectSettings.incomingCheckStrategy = selectedStrategy as GitIncomingCheckStrategy if (!project.isDefault) { GitBranchIncomingOutgoingManager.getInstance(project).updateIncomingScheduling() } }) } enableIf(AdvancedSettingsPredicate("git.update.incoming.outgoing.info", disposable!!)) } } private fun RowBuilder.protectedBranchesRow() { row { cell { label(message("settings.protected.branched")) val sharedSettings = gitSharedSettings(project) val protectedBranchesField = ExpandableTextFieldWithReadOnlyText(ParametersListUtil.COLON_LINE_PARSER, ParametersListUtil.COLON_LINE_JOINER) if (sharedSettings.isSynchronizeBranchProtectionRules) { protectedBranchesField.readOnlyText = ParametersListUtil.COLON_LINE_JOINER.`fun`(sharedSettings.additionalProhibitedPatterns) } protectedBranchesField(growX) .withBinding<List<String>>( { ParametersListUtil.COLON_LINE_PARSER.`fun`(it.text) }, { component, value -> component.text = ParametersListUtil.COLON_LINE_JOINER.`fun`(value) }, PropertyBinding( { sharedSettings.forcePushProhibitedPatterns }, { sharedSettings.forcePushProhibitedPatterns = it }) ) } row { checkBox(synchronizeBranchProtectionRules(project)) } } } override fun getId() = "vcs.${GitVcs.NAME}" override fun createConfigurables(): List<UnnamedConfigurable> { return VcsEnvCustomizer.EP_NAME.extensions.mapNotNull { it.getConfigurable(project) } } override fun createPanel(): DialogPanel = panel { gitExecutableRow() titledRow(message("settings.commit.group.title")) { row { checkBox(cdEnableStagingArea) .enableIf(StagingAreaAvailablePredicate(project, disposable!!)) } row { checkBox(cdWarnAboutCrlf(project)) } row { checkBox(cdWarnAboutDetachedHead(project)) } row { checkBox(cdAddCherryPickSuffix(project)) } createGpgSignRow(project, disposable!!) } titledRow(message("settings.push.group.title")) { row { checkBox(cdAutoUpdateOnPush(project)) } row { val previewPushOnCommitAndPush = checkBox(cdShowCommitAndPushDialog(project)) row { checkBox(cdHidePushDialogForNonProtectedBranches(project)) .enableIf(previewPushOnCommitAndPush.selected) } } protectedBranchesRow() } titledRow(message("settings.update.group.title")) { row { cell { label(message("settings.update.method")) comboBox( CollectionComboBoxModel(getUpdateMethods()), { projectSettings.updateMethod }, { projectSettings.updateMethod = it!! }, renderer = SimpleListCellRenderer.create<UpdateMethod>("", UpdateMethod::getName) ) } } row { cell { label(message("settings.clean.working.tree")) buttonGroup({ projectSettings.saveChangesPolicy }, { projectSettings.saveChangesPolicy = it }) { GitSaveChangesPolicy.values().forEach { saveSetting -> radioButton(saveSetting.text, saveSetting) } } } } row { checkBox(cdAutoUpdateOnPush(project)) } } if (project.isDefault || GitRepositoryManager.getInstance(project).moreThanOneRoot()) { row { checkBox(cdSyncBranches(project)).applyToComponent { toolTipText = DvcsBundle.message("sync.setting.description", GitVcs.DISPLAY_NAME.get()) } } } branchUpdateInfoRow() row { val previewPushOnCommitAndPush = checkBox(cdShowCommitAndPushDialog(project)) row { checkBox(cdHidePushDialogForNonProtectedBranches(project)) .enableIf(previewPushOnCommitAndPush.selected) } } row { checkBox(cdOverrideCredentialHelper) } for (configurable in configurables) { appendDslConfigurableRow(configurable) } if (AbstractCommonUpdateAction.showsCustomNotification(listOf(GitVcs.getInstance(project)))) { updateProjectInfoFilter() } } private fun RowBuilder.updateProjectInfoFilter() { row { cell { val storedProperties = project.service<GitUpdateProjectInfoLogProperties>() val roots = ProjectLevelVcsManager.getInstance(project).getRootsUnderVcs(GitVcs.getInstance(project)).toSet() val model = VcsLogClassicFilterUi.FileFilterModel(roots, currentUpdateInfoFilterProperties, null) val component = object : StructureFilterPopupComponent(currentUpdateInfoFilterProperties, model, VcsLogColorManagerImpl(roots)) { override fun shouldDrawLabel(): Boolean = false override fun shouldIndicateHovering(): Boolean = false override fun getDefaultSelectorForeground(): Color = UIUtil.getLabelForeground() override fun createUnfocusedBorder(): Border { return FilledRoundedBorder(JBColor.namedColor("Component.borderColor", Gray.xBF), ARC_SIZE, 1) } }.initUi() label(message("settings.filter.update.info") + " ") component() .onIsModified { storedProperties.getFilterValues(STRUCTURE_FILTER.name) != currentUpdateInfoFilterProperties.structureFilter } .onApply { storedProperties.saveFilterValues(STRUCTURE_FILTER.name, currentUpdateInfoFilterProperties.structureFilter) } .onReset { currentUpdateInfoFilterProperties.structureFilter = storedProperties.getFilterValues(STRUCTURE_FILTER.name) model.updateFilterFromProperties() } } } } private class MyLogProperties(mainProperties: GitUpdateProjectInfoLogProperties) : MainVcsLogUiProperties by mainProperties { var structureFilter: List<String>? = null override fun getFilterValues(filterName: String): List<String>? = structureFilter.takeIf { filterName == STRUCTURE_FILTER.name } override fun saveFilterValues(filterName: String, values: MutableList<String>?) { if (filterName == STRUCTURE_FILTER.name) { structureFilter = values } } } } private typealias ParserFunction = Function<String, List<String>> private typealias JoinerFunction = Function<List<String>, String> internal class ExpandableTextFieldWithReadOnlyText(lineParser: ParserFunction, private val lineJoiner: JoinerFunction) : ExpandableTextField(lineParser, lineJoiner) { var readOnlyText = "" init { addFocusListener(object : FocusAdapter() { override fun focusLost(e: FocusEvent) { val myComponent = this@ExpandableTextFieldWithReadOnlyText if (e.component == myComponent) { val document = myComponent.document val documentText = document.getText(0, document.length) updateReadOnlyText(documentText) } } }) } override fun setText(t: String?) { if (!t.isNullOrBlank() && t != text) { updateReadOnlyText(t) } super.setText(t) } private fun updateReadOnlyText(@NlsSafe text: String) { if (readOnlyText.isBlank()) return val readOnlySuffix = if (text.isBlank()) readOnlyText else lineJoiner.join("", readOnlyText) // NON-NLS with(emptyText as TextComponentEmptyText) { clear() appendText(text, SimpleTextAttributes.REGULAR_ATTRIBUTES) appendText(readOnlySuffix, SimpleTextAttributes.GRAYED_ATTRIBUTES) setTextToTriggerStatus(text) //this will force status text rendering in case if the text field is not empty } } fun JoinerFunction.join(vararg items: String): String = `fun`(items.toList()) } class StagingAreaAvailablePredicate(val project: Project, val disposable: Disposable) : ComponentPredicate() { override fun addListener(listener: (Boolean) -> Unit) { project.messageBus.connect(disposable).subscribe(CommitModeManager.SETTINGS, object : CommitModeManager.SettingsListener { override fun settingsChanged() { listener(invoke()) } }) } override fun invoke(): Boolean = canEnableStagingArea() } class HasGitRootsPredicate(val project: Project, val disposable: Disposable) : ComponentPredicate() { override fun addListener(listener: (Boolean) -> Unit) { project.messageBus.connect(disposable).subscribe(VcsRepositoryManager.VCS_REPOSITORY_MAPPING_UPDATED, VcsRepositoryMappingListener { listener(invoke()) }) } override fun invoke(): Boolean = GitRepositoryManager.getInstance(project).repositories.size != 0 } class AdvancedSettingsPredicate(val id: String, val disposable: Disposable) : ComponentPredicate() { override fun addListener(listener: (Boolean) -> Unit) { ApplicationManager.getApplication().messageBus.connect(disposable) .subscribe(AdvancedSettingsChangeListener.TOPIC, object : AdvancedSettingsChangeListener { override fun advancedSettingChanged(id: String, oldValue: Any, newValue: Any) { listener(invoke()) } }) } override fun invoke(): Boolean = AdvancedSettings.getBoolean(id) }
apache-2.0
dd3d83c2d2ece918ef6f3f9f1bd90a1e
43.446247
420
0.724854
5.160622
false
false
false
false
siosio/intellij-community
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/ModuleBridgeLoaderService.kt
1
4686
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.ide.impl.legacyBridge.module import com.intellij.diagnostic.Activity import com.intellij.diagnostic.ActivityCategory import com.intellij.diagnostic.StartUpMeasurer import com.intellij.openapi.application.WriteAction import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.impl.ProjectServiceContainerInitializedListener import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.workspaceModel.ide.JpsProjectLoadedListener import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.ide.impl.WorkspaceModelImpl import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsProjectModelSynchronizer import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.project.ProjectRootManagerBridge import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.WorkspaceEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity internal class ModuleBridgeLoaderService(private val project: Project) { private var storeToEntitySources: Pair<WorkspaceEntityStorage, List<EntitySource>>? = null private var activity: Activity? = null init { if (!project.isDefault) { val workspaceModel = WorkspaceModel.getInstance(project) as WorkspaceModelImpl val projectModelSynchronizer = JpsProjectModelSynchronizer.getInstance(project) if (projectModelSynchronizer != null) { if (projectModelSynchronizer.blockCidrDelayedUpdate()) workspaceModel.blockDelayedLoading() if (!workspaceModel.loadedFromCache) { LOG.info("Workspace model loaded without cache. Loading real project state into workspace model. ${Thread.currentThread()}") activity = StartUpMeasurer.startActivity("modules loading without cache", ActivityCategory.DEFAULT) storeToEntitySources = projectModelSynchronizer.loadProjectToEmptyStorage(project) } else { activity = StartUpMeasurer.startActivity("modules loading with cache", ActivityCategory.DEFAULT) loadModules() } } } } private fun loadModules() { val childActivity = activity?.startChild("modules instantiation") val moduleManager = ModuleManager.getInstance(project) as ModuleManagerComponentBridge val entities = moduleManager.entityStore.current.entities(ModuleEntity::class.java) moduleManager.loadModules(entities) childActivity?.setDescription("modules count: ${moduleManager.modules.size}") childActivity?.end() val librariesActivity = StartUpMeasurer.startActivity("project libraries loading", ActivityCategory.DEFAULT) (LibraryTablesRegistrar.getInstance().getLibraryTable(project) as ProjectLibraryTableBridgeImpl).loadLibraries() librariesActivity.end() activity?.end() activity = null } class ModuleBridgeProjectServiceInitializedListener : ProjectServiceContainerInitializedListener { override fun serviceCreated(project: Project) { LOG.debug { "Project component initialized" } if (project.isDefault) return val workspaceModel = WorkspaceModel.getInstance(project) as WorkspaceModelImpl if (!workspaceModel.loadedFromCache) { val moduleLoaderService = project.getService(ModuleBridgeLoaderService::class.java) val projectModelSynchronizer = JpsProjectModelSynchronizer.getInstance(project) if (projectModelSynchronizer == null) return projectModelSynchronizer.applyLoadedStorage(moduleLoaderService.storeToEntitySources) project.messageBus.syncPublisher(JpsProjectLoadedListener.LOADED).loaded() moduleLoaderService.storeToEntitySources = null moduleLoaderService.loadModules() } WriteAction.runAndWait<RuntimeException> { (ProjectRootManager.getInstance(project) as ProjectRootManagerBridge).setupTrackedLibrariesAndJdks() } WorkspaceModelTopics.getInstance(project).notifyModulesAreLoaded() } companion object { private val LOG = logger<ModuleBridgeProjectServiceInitializedListener>() } } companion object { private val LOG = logger<ModuleBridgeLoaderService>() } }
apache-2.0
030b5f582d11ea410c250f9e4020df7e
50.505495
140
0.795775
5.442509
false
false
false
false
jwren/intellij-community
plugins/kotlin/uast/uast-kotlin-base/test/org/jetbrains/uast/test/common/kotlin/ValueLogger.kt
4
1331
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.test.common.kotlin import org.jetbrains.uast.UElement import org.jetbrains.uast.UExpression import org.jetbrains.uast.evaluation.UEvaluationContext import org.jetbrains.uast.visitor.UastVisitor class ValueLogger(val evaluationContext: UEvaluationContext) : UastVisitor { val builder = StringBuilder() var level = 0 override fun visitElement(node: UElement): Boolean { val initialLine = node.asLogString() + " [" + run { val renderString = node.asRenderString().lines() if (renderString.size == 1) { renderString.single() } else { renderString.first() + "..." + renderString.last() } } + "]" (1..level).forEach { builder.append(" ") } builder.append(initialLine) if (node is UExpression) { val value = evaluationContext.valueOf(node) builder.append(" = ").append(value) } builder.appendLine() level++ return false } override fun afterVisitElement(node: UElement) { level-- } override fun toString() = builder.toString() }
apache-2.0
7399fff3017e964ca3bff979c8005dd7
30.690476
158
0.630353
4.542662
false
false
false
false
SimpleMobileTools/Simple-Calendar
app/src/main/kotlin/com/simplemobiletools/calendar/pro/helpers/Formatter.kt
1
5939
package com.simplemobiletools.calendar.pro.helpers import android.content.Context import com.simplemobiletools.calendar.pro.R import com.simplemobiletools.calendar.pro.extensions.config import com.simplemobiletools.calendar.pro.extensions.seconds import org.joda.time.DateTime import org.joda.time.DateTimeZone import org.joda.time.LocalDate import org.joda.time.format.DateTimeFormat object Formatter { const val DAYCODE_PATTERN = "YYYYMMdd" const val YEAR_PATTERN = "YYYY" const val TIME_PATTERN = "HHmmss" private const val MONTH_PATTERN = "MMM" private const val DAY_PATTERN = "d" private const val DAY_OF_WEEK_PATTERN = "EEE" private const val LONGEST_PATTERN = "MMMM d YYYY (EEEE)" private const val DATE_DAY_PATTERN = "d EEEE" private const val PATTERN_TIME_12 = "hh:mm a" private const val PATTERN_TIME_24 = "HH:mm" private const val PATTERN_HOURS_12 = "h a" private const val PATTERN_HOURS_24 = "HH" fun getDateFromCode(context: Context, dayCode: String, shortMonth: Boolean = false): String { val dateTime = getDateTimeFromCode(dayCode) val day = dateTime.toString(DAY_PATTERN) val year = dateTime.toString(YEAR_PATTERN) val monthIndex = Integer.valueOf(dayCode.substring(4, 6)) var month = getMonthName(context, monthIndex) if (shortMonth) { month = month.substring(0, Math.min(month.length, 3)) } var date = "$month $day" if (year != DateTime().toString(YEAR_PATTERN)) { date += " $year" } return date } fun getDayTitle(context: Context, dayCode: String, addDayOfWeek: Boolean = true): String { val date = getDateFromCode(context, dayCode) val dateTime = getDateTimeFromCode(dayCode) val day = dateTime.toString(DAY_OF_WEEK_PATTERN) return if (addDayOfWeek) "$date ($day)" else date } fun getDateDayTitle(dayCode: String): String { val dateTime = getDateTimeFromCode(dayCode) return dateTime.toString(DATE_DAY_PATTERN) } fun getLongMonthYear(context: Context, dayCode: String): String { val dateTime = getDateTimeFromCode(dayCode) val monthIndex = Integer.valueOf(dayCode.substring(4, 6)) val month = getMonthName(context, monthIndex) val year = dateTime.toString(YEAR_PATTERN) var date = month if (year != DateTime().toString(YEAR_PATTERN)) { date += " $year" } return date } fun getLongestDate(ts: Long) = getDateTimeFromTS(ts).toString(LONGEST_PATTERN) fun getDate(context: Context, dateTime: DateTime, addDayOfWeek: Boolean = true) = getDayTitle(context, getDayCodeFromDateTime(dateTime), addDayOfWeek) fun getFullDate(context: Context, dateTime: DateTime): String { val day = dateTime.toString(DAY_PATTERN) val year = dateTime.toString(YEAR_PATTERN) val monthIndex = dateTime.monthOfYear val month = getMonthName(context, monthIndex) return "$month $day $year" } fun getTodayCode() = getDayCodeFromTS(getNowSeconds()) fun getTodayDayNumber() = getDateTimeFromTS(getNowSeconds()).toString(DAY_PATTERN) fun getCurrentMonthShort() = getDateTimeFromTS(getNowSeconds()).toString(MONTH_PATTERN) fun getHours(context: Context, dateTime: DateTime) = dateTime.toString(getHourPattern(context)) fun getTime(context: Context, dateTime: DateTime) = dateTime.toString(getTimePattern(context)) fun getDateTimeFromCode(dayCode: String) = DateTimeFormat.forPattern(DAYCODE_PATTERN).withZone(DateTimeZone.UTC).parseDateTime(dayCode) fun getLocalDateTimeFromCode(dayCode: String) = DateTimeFormat.forPattern(DAYCODE_PATTERN).withZone(DateTimeZone.getDefault()).parseLocalDate(dayCode).toDateTimeAtStartOfDay() fun getTimeFromTS(context: Context, ts: Long) = getTime(context, getDateTimeFromTS(ts)) fun getDayStartTS(dayCode: String) = getLocalDateTimeFromCode(dayCode).seconds() fun getDayEndTS(dayCode: String) = getLocalDateTimeFromCode(dayCode).plusDays(1).minusMinutes(1).seconds() fun getDayCodeFromDateTime(dateTime: DateTime) = dateTime.toString(DAYCODE_PATTERN) fun getDateFromTS(ts: Long) = LocalDate(ts * 1000L, DateTimeZone.getDefault()) fun getDateTimeFromTS(ts: Long) = DateTime(ts * 1000L, DateTimeZone.getDefault()) fun getUTCDateTimeFromTS(ts: Long) = DateTime(ts * 1000L, DateTimeZone.UTC) // use manually translated month names, as DateFormat and Joda have issues with a lot of languages fun getMonthName(context: Context, id: Int) = context.resources.getStringArray(R.array.months)[id - 1] fun getHourPattern(context: Context) = if (context.config.use24HourFormat) PATTERN_HOURS_24 else PATTERN_HOURS_12 fun getTimePattern(context: Context) = if (context.config.use24HourFormat) PATTERN_TIME_24 else PATTERN_TIME_12 fun getExportedTime(ts: Long): String { val dateTime = DateTime(ts, DateTimeZone.UTC) return "${dateTime.toString(DAYCODE_PATTERN)}T${dateTime.toString(TIME_PATTERN)}Z" } fun getDayCodeFromTS(ts: Long): String { val daycode = getDateTimeFromTS(ts).toString(DAYCODE_PATTERN) return if (daycode.isNotEmpty()) { daycode } else { "0" } } fun getUTCDayCodeFromTS(ts: Long) = getUTCDateTimeFromTS(ts).toString(DAYCODE_PATTERN) fun getYearFromDayCode(dayCode: String) = getDateTimeFromCode(dayCode).toString(YEAR_PATTERN) fun getShiftedTS(dateTime: DateTime, toZone: DateTimeZone) = dateTime.withTimeAtStartOfDay().withZoneRetainFields(toZone).seconds() fun getShiftedLocalTS(ts: Long) = getShiftedTS(dateTime = getUTCDateTimeFromTS(ts), toZone = DateTimeZone.getDefault()) fun getShiftedUtcTS(ts: Long) = getShiftedTS(dateTime = getDateTimeFromTS(ts), toZone = DateTimeZone.UTC) }
gpl-3.0
b288bb9380ee874483bbd23230982d6c
39.958621
154
0.706348
4.067808
false
false
false
false
dahlstrom-g/intellij-community
platform/core-api/src/com/intellij/util/messages/impl/Message.kt
8
1191
// 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.util.messages.impl import com.intellij.codeWithMe.ClientId import com.intellij.util.messages.Topic import java.lang.invoke.MethodHandle internal class Message( @JvmField val topic: Topic<*>, // we don't bind args as part of MethodHandle creation, because object is not known yet - so, MethodHandle here is not ready to use @JvmField val method: MethodHandle, @JvmField val methodName: String, // it allows us to cache MethodHandle per method and partially reuse it @JvmField val args: Array<Any?>?, @JvmField val handlers: Array<Any?>, @JvmField val bus: MessageBusImpl, ) { @JvmField val clientId = ClientId.getCurrentValue() // to avoid creating Message for each handler // see note about pumpMessages in createPublisher (invoking job handlers can be stopped and continued as part of another pumpMessages call) @JvmField var currentHandlerIndex = 0 override fun toString(): String { return "Message(topic=$topic, method=$methodName, args=${args.contentToString()}, handlers=${handlers.contentToString()})" } }
apache-2.0
25863d3a63409359d2c6cd2c7c7778c5
41.571429
141
0.758186
4.362637
false
false
false
false
androidx/androidx
health/health-services-client/src/test/java/androidx/health/services/client/data/PassiveGoalTest.kt
3
3059
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.services.client.data import androidx.health.services.client.data.ComparisonType.Companion.GREATER_THAN import androidx.health.services.client.data.DataType.Companion.STEPS import androidx.health.services.client.data.DataType.Companion.STEPS_DAILY import androidx.health.services.client.proto.DataProto import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class PassiveGoalTest { @Test fun protoRoundTrip() { val proto = PassiveGoal(DataTypeCondition(STEPS_DAILY, 400, GREATER_THAN)).proto val goal = PassiveGoal(proto) assertThat(goal.dataTypeCondition.dataType).isEqualTo(STEPS_DAILY) assertThat(goal.dataTypeCondition.threshold).isEqualTo(400) assertThat(goal.dataTypeCondition.comparisonType).isEqualTo(GREATER_THAN) assertThat(goal.triggerFrequency).isEqualTo(PassiveGoal.TriggerFrequency.REPEATED) } @Test fun shouldEqual() { val goal1 = PassiveGoal(DataTypeCondition(STEPS_DAILY, 400, GREATER_THAN)) val goal2 = PassiveGoal(DataTypeCondition(STEPS_DAILY, 400, GREATER_THAN)) assertThat(goal1).isEqualTo(goal2) } @Test fun shouldNotEqual_differentTriggerFrequency() { // This case isn't expected to happen for clients, but it _could_ happen from the service // side for old clients. Using proto constructor because triggerFrequency constructor is // private. val goal1 = PassiveGoal(DataTypeCondition(STEPS_DAILY, 400, GREATER_THAN)) val goal2 = PassiveGoal( goal1.proto.toBuilder() .setTriggerFrequency(DataProto.PassiveGoal.TriggerFrequency.TRIGGER_FREQUENCY_ONCE) .build() ) assertThat(goal1).isNotEqualTo(goal2) } @Test fun shouldNotEqual_differentThreshold() { val goal1 = PassiveGoal(DataTypeCondition(STEPS_DAILY, 400, GREATER_THAN)) val goal2 = PassiveGoal(DataTypeCondition(STEPS_DAILY, 800, GREATER_THAN)) assertThat(goal1).isNotEqualTo(goal2) } @Test fun shouldNotEqual_differentDataType() { val goal1 = PassiveGoal(DataTypeCondition(STEPS_DAILY, 400, GREATER_THAN)) val goal2 = PassiveGoal(DataTypeCondition(STEPS, 400, GREATER_THAN)) assertThat(goal1).isNotEqualTo(goal2) } }
apache-2.0
98cc9cc73f599b119b694a52a8a5aca4
37.25
99
0.727689
4.332861
false
true
false
false
androidx/androidx
compose/ui/ui-text/src/test/java/androidx/compose/ui/text/input/EditingBufferTest.kt
3
15106
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.input import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.matchers.assertThat import com.google.common.truth.Truth.assertThat import kotlin.test.assertFailsWith import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class EditingBufferTest { @Test fun insert() { val eb = EditingBuffer("", TextRange.Zero) eb.replace(0, 0, "A") assertThat(eb).hasChars("A") assertThat(eb.cursor).isEqualTo(1) assertThat(eb.selectionStart).isEqualTo(1) assertThat(eb.selectionEnd).isEqualTo(1) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) // Keep inserting text to the end of string. Cursor should follow. eb.replace(1, 1, "BC") assertThat(eb).hasChars("ABC") assertThat(eb.cursor).isEqualTo(3) assertThat(eb.selectionStart).isEqualTo(3) assertThat(eb.selectionEnd).isEqualTo(3) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) // Insert into middle position. Cursor should be end of inserted text. eb.replace(1, 1, "D") assertThat(eb).hasChars("ADBC") assertThat(eb.cursor).isEqualTo(2) assertThat(eb.selectionStart).isEqualTo(2) assertThat(eb.selectionEnd).isEqualTo(2) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) } @Test fun delete() { val eb = EditingBuffer("ABCDE", TextRange.Zero) eb.replace(0, 1, "") // Delete the left character at the cursor. assertThat(eb).hasChars("BCDE") assertThat(eb.cursor).isEqualTo(0) assertThat(eb.selectionStart).isEqualTo(0) assertThat(eb.selectionEnd).isEqualTo(0) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) // Delete the text before the cursor eb.replace(0, 2, "") assertThat(eb).hasChars("DE") assertThat(eb.cursor).isEqualTo(0) assertThat(eb.selectionStart).isEqualTo(0) assertThat(eb.selectionEnd).isEqualTo(0) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) // Delete end of the text. eb.replace(1, 2, "") assertThat(eb).hasChars("D") assertThat(eb.cursor).isEqualTo(1) assertThat(eb.selectionStart).isEqualTo(1) assertThat(eb.selectionEnd).isEqualTo(1) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) } @Test fun setSelection() { val eb = EditingBuffer("ABCDE", TextRange(0, 3)) assertThat(eb).hasChars("ABCDE") assertThat(eb.cursor).isEqualTo(-1) assertThat(eb.selectionStart).isEqualTo(0) assertThat(eb.selectionEnd).isEqualTo(3) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) eb.setSelection(0, 5) // Change the selection assertThat(eb).hasChars("ABCDE") assertThat(eb.cursor).isEqualTo(-1) assertThat(eb.selectionStart).isEqualTo(0) assertThat(eb.selectionEnd).isEqualTo(5) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) eb.replace(0, 3, "X") // replace function cancel the selection and place cursor. assertThat(eb).hasChars("XDE") assertThat(eb.cursor).isEqualTo(1) assertThat(eb.selectionStart).isEqualTo(1) assertThat(eb.selectionEnd).isEqualTo(1) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) eb.setSelection(0, 2) // Set the selection again assertThat(eb).hasChars("XDE") assertThat(eb.cursor).isEqualTo(-1) assertThat(eb.selectionStart).isEqualTo(0) assertThat(eb.selectionEnd).isEqualTo(2) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) } @Test fun setSelection_throws_whenNegativeStart() { val eb = EditingBuffer("ABCDE", TextRange.Zero) assertFailsWith<IndexOutOfBoundsException> { eb.setSelection(-1, 0) } } @Test fun setSelection_throws_whenNegativeEnd() { val eb = EditingBuffer("ABCDE", TextRange.Zero) assertFailsWith<IndexOutOfBoundsException> { eb.setSelection(0, -1) } } @Test fun setCompostion_and_cancelComposition() { val eb = EditingBuffer("ABCDE", TextRange.Zero) eb.setComposition(0, 5) // Make all text as composition assertThat(eb).hasChars("ABCDE") assertThat(eb.cursor).isEqualTo(0) assertThat(eb.selectionStart).isEqualTo(0) assertThat(eb.selectionEnd).isEqualTo(0) assertThat(eb.hasComposition()).isTrue() assertThat(eb.compositionStart).isEqualTo(0) assertThat(eb.compositionEnd).isEqualTo(5) eb.replace(2, 3, "X") // replace function cancel the composition text. assertThat(eb).hasChars("ABXDE") assertThat(eb.cursor).isEqualTo(3) assertThat(eb.selectionStart).isEqualTo(3) assertThat(eb.selectionEnd).isEqualTo(3) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) eb.setComposition(2, 4) // set composition again assertThat(eb).hasChars("ABXDE") assertThat(eb.cursor).isEqualTo(3) assertThat(eb.selectionStart).isEqualTo(3) assertThat(eb.selectionEnd).isEqualTo(3) assertThat(eb.hasComposition()).isTrue() assertThat(eb.compositionStart).isEqualTo(2) assertThat(eb.compositionEnd).isEqualTo(4) eb.cancelComposition() // cancel the composition assertThat(eb).hasChars("ABE") assertThat(eb.cursor).isEqualTo(2) assertThat(eb.selectionStart).isEqualTo(2) assertThat(eb.selectionEnd).isEqualTo(2) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) } @Test fun setCompostion_and_commitComposition() { val eb = EditingBuffer("ABCDE", TextRange.Zero) eb.setComposition(0, 5) // Make all text as composition assertThat(eb).hasChars("ABCDE") assertThat(eb.cursor).isEqualTo(0) assertThat(eb.selectionStart).isEqualTo(0) assertThat(eb.selectionEnd).isEqualTo(0) assertThat(eb.hasComposition()).isTrue() assertThat(eb.compositionStart).isEqualTo(0) assertThat(eb.compositionEnd).isEqualTo(5) eb.replace(2, 3, "X") // replace function cancel the composition text. assertThat(eb).hasChars("ABXDE") assertThat(eb.cursor).isEqualTo(3) assertThat(eb.selectionStart).isEqualTo(3) assertThat(eb.selectionEnd).isEqualTo(3) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) eb.setComposition(2, 4) // set composition again assertThat(eb).hasChars("ABXDE") assertThat(eb.cursor).isEqualTo(3) assertThat(eb.selectionStart).isEqualTo(3) assertThat(eb.selectionEnd).isEqualTo(3) assertThat(eb.hasComposition()).isTrue() assertThat(eb.compositionStart).isEqualTo(2) assertThat(eb.compositionEnd).isEqualTo(4) eb.commitComposition() // commit the composition assertThat(eb).hasChars("ABXDE") assertThat(eb.cursor).isEqualTo(3) assertThat(eb.selectionStart).isEqualTo(3) assertThat(eb.selectionEnd).isEqualTo(3) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) } @Test fun setCursor_and_get_cursor() { val eb = EditingBuffer("ABCDE", TextRange.Zero) eb.cursor = 1 assertThat(eb).hasChars("ABCDE") assertThat(eb.cursor).isEqualTo(1) assertThat(eb.selectionStart).isEqualTo(1) assertThat(eb.selectionEnd).isEqualTo(1) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) eb.cursor = 2 assertThat(eb).hasChars("ABCDE") assertThat(eb.cursor).isEqualTo(2) assertThat(eb.selectionStart).isEqualTo(2) assertThat(eb.selectionEnd).isEqualTo(2) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) eb.cursor = 5 assertThat(eb).hasChars("ABCDE") assertThat(eb.cursor).isEqualTo(5) assertThat(eb.selectionStart).isEqualTo(5) assertThat(eb.selectionEnd).isEqualTo(5) assertThat(eb.hasComposition()).isFalse() assertThat(eb.compositionStart).isEqualTo(-1) assertThat(eb.compositionEnd).isEqualTo(-1) } @Test fun delete_preceding_cursor_no_composition() { val eb = EditingBuffer("ABCDE", TextRange.Zero) eb.delete(1, 2) assertThat(eb).hasChars("ACDE") assertThat(eb.cursor).isEqualTo(0) assertThat(eb.hasComposition()).isFalse() } @Test fun delete_trailing_cursor_no_composition() { val eb = EditingBuffer("ABCDE", TextRange(3)) eb.delete(1, 2) assertThat(eb).hasChars("ACDE") assertThat(eb.cursor).isEqualTo(2) assertThat(eb.hasComposition()).isFalse() } @Test fun delete_preceding_selection_no_composition() { val eb = EditingBuffer("ABCDE", TextRange(0, 1)) eb.delete(1, 2) assertThat(eb).hasChars("ACDE") assertThat(eb.selectionStart).isEqualTo(0) assertThat(eb.selectionEnd).isEqualTo(1) assertThat(eb.hasComposition()).isFalse() } @Test fun delete_trailing_selection_no_composition() { val eb = EditingBuffer("ABCDE", TextRange(4, 5)) eb.delete(1, 2) assertThat(eb).hasChars("ACDE") assertThat(eb.selectionStart).isEqualTo(3) assertThat(eb.selectionEnd).isEqualTo(4) assertThat(eb.hasComposition()).isFalse() } @Test fun delete_covered_cursor() { // AB[]CDE val eb = EditingBuffer("ABCDE", TextRange(2, 2)) eb.delete(1, 3) // A[]DE assertThat(eb).hasChars("ADE") assertThat(eb.selectionStart).isEqualTo(1) assertThat(eb.selectionEnd).isEqualTo(1) } @Test fun delete_covered_selection() { // A[BC]DE val eb = EditingBuffer("ABCDE", TextRange(1, 3)) eb.delete(0, 4) // []E assertThat(eb).hasChars("E") assertThat(eb.selectionStart).isEqualTo(0) assertThat(eb.selectionEnd).isEqualTo(0) } @Test fun delete_intersects_first_half_of_selection() { // AB[CD]E val eb = EditingBuffer("ABCDE", TextRange(2, 4)) eb.delete(1, 3) // A[D]E assertThat(eb).hasChars("ADE") assertThat(eb.selectionStart).isEqualTo(1) assertThat(eb.selectionEnd).isEqualTo(2) } @Test fun delete_intersects_second_half_of_selection() { // A[BCD]EFG val eb = EditingBuffer("ABCDEFG", TextRange(1, 4)) eb.delete(3, 5) // A[BC]FG assertThat(eb).hasChars("ABCFG") assertThat(eb.selectionStart).isEqualTo(1) assertThat(eb.selectionEnd).isEqualTo(3) } @Test fun delete_preceding_composition_no_intersection() { val eb = EditingBuffer("ABCDE", TextRange.Zero) eb.setComposition(1, 2) eb.delete(2, 3) assertThat(eb).hasChars("ABDE") assertThat(eb.cursor).isEqualTo(0) assertThat(eb.compositionStart).isEqualTo(1) assertThat(eb.compositionEnd).isEqualTo(2) } @Test fun delete_trailing_composition_no_intersection() { val eb = EditingBuffer("ABCDE", TextRange.Zero) eb.setComposition(3, 4) eb.delete(2, 3) assertThat(eb).hasChars("ABDE") assertThat(eb.cursor).isEqualTo(0) assertThat(eb.compositionStart).isEqualTo(2) assertThat(eb.compositionEnd).isEqualTo(3) } @Test fun delete_preceding_composition_intersection() { val eb = EditingBuffer("ABCDE", TextRange.Zero) eb.setComposition(1, 3) eb.delete(2, 4) assertThat(eb).hasChars("ABE") assertThat(eb.cursor).isEqualTo(0) assertThat(eb.compositionStart).isEqualTo(1) assertThat(eb.compositionEnd).isEqualTo(2) } @Test fun delete_trailing_composition_intersection() { val eb = EditingBuffer("ABCDE", TextRange.Zero) eb.setComposition(3, 5) eb.delete(2, 4) assertThat(eb).hasChars("ABE") assertThat(eb.cursor).isEqualTo(0) assertThat(eb.compositionStart).isEqualTo(2) assertThat(eb.compositionEnd).isEqualTo(3) } @Test fun delete_composition_contains_delrange() { val eb = EditingBuffer("ABCDE", TextRange.Zero) eb.setComposition(2, 5) eb.delete(3, 4) assertThat(eb).hasChars("ABCE") assertThat(eb.cursor).isEqualTo(0) assertThat(eb.compositionStart).isEqualTo(2) assertThat(eb.compositionEnd).isEqualTo(4) } @Test fun delete_delrange_contains_composition() { val eb = EditingBuffer("ABCDE", TextRange.Zero) eb.setComposition(3, 4) eb.delete(2, 5) assertThat(eb).hasChars("AB") assertThat(eb.cursor).isEqualTo(0) assertThat(eb.hasComposition()).isFalse() } }
apache-2.0
1225ecc176244fa30b71891a62d88607
33.649083
88
0.647954
4.25641
false
true
false
false
androidx/androidx
privacysandbox/tools/tools-core/src/main/java/androidx/privacysandbox/tools/core/generator/AidlCompiler.kt
3
2188
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.privacysandbox.tools.core.generator import java.io.IOException import java.nio.file.Path import java.util.concurrent.TimeUnit class AidlCompiler( private val aidlCompilerPath: Path, private val aidlCompileTimeoutMs: Long = 10_000, ) { fun compile(workingDir: Path, sources: List<Path>) { val command = listOf( aidlCompilerPath.toString(), "--structured", "--lang=java", "--include=$workingDir", "--out=$workingDir", *sources.map(Path::toString).toTypedArray() ) val process = ProcessBuilder(command).start() if (!process.waitFor(aidlCompileTimeoutMs, TimeUnit.MILLISECONDS)) { throw Exception("AIDL compiler timed out: $command") } if (process.exitValue() != 0) { throw Exception( "AIDL compiler didn't terminate successfully (exit code: " + "${process.exitValue()}).\n" + "Command: '$command'\n" + "Errors: ${getProcessErrors(process)}" ) } } private fun getProcessErrors(process: Process): String { try { process.errorStream.bufferedReader().use { outputReader -> return outputReader.lines().toArray() .joinToString(separator = "\n\t", prefix = "\n\t") } } catch (e: IOException) { return "Error when printing output of command: ${e.message}" } } }
apache-2.0
6b8eee5f98cb61bf94d073c880a509bd
34.306452
76
0.602834
4.606316
false
false
false
false
nimakro/tornadofx
src/main/java/tornadofx/ViewModel.kt
1
28052
@file:Suppress("unused") package tornadofx import javafx.beans.Observable import javafx.beans.binding.Bindings import javafx.beans.binding.BooleanBinding import javafx.beans.binding.BooleanExpression import javafx.beans.property.* import javafx.beans.value.ChangeListener import javafx.beans.value.ObservableValue import javafx.collections.* import javafx.scene.Node import javafx.scene.control.* import javafx.scene.paint.Paint import tornadofx.FX.Companion.runAndWait import java.time.LocalDate import java.util.* import java.util.concurrent.Callable import kotlin.collections.ArrayList import kotlin.reflect.KFunction import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KProperty1 val viewModelBundle: ResourceBundle = ResourceBundle.getBundle("tornadofx/i18n/ViewModel") open class ViewModel : Component(), ScopedInstance { val propertyMap: ObservableMap<Property<*>, () -> Property<*>?> = FXCollections.observableHashMap<Property<*>, () -> Property<*>?>() val propertyCache: ObservableMap<Property<*>, Property<*>> = FXCollections.observableHashMap<Property<*>, Property<*>>() val externalChangeListeners: ObservableMap<Property<*>, ChangeListener<Any>> = FXCollections.observableHashMap<Property<*>, ChangeListener<Any>>() val dirtyProperties: ObservableList<ObservableValue<*>> = FXCollections.observableArrayList<ObservableValue<*>>() open val dirty = booleanBinding(dirtyProperties, dirtyProperties) { isNotEmpty() } @Deprecated("Use dirty property instead", ReplaceWith("dirty")) fun dirtyStateProperty() = dirty val validationContext = ValidationContext() val ignoreDirtyStateProperties = FXCollections.observableArrayList<ObservableValue<out Any>>() val autocommitProperties = FXCollections.observableArrayList<ObservableValue<out Any>>() companion object { val propertyToViewModel = WeakHashMap<Observable, ViewModel>() val propertyToFacade = WeakHashMap<Observable, Property<*>>() fun getViewModelForProperty(property: Observable): ViewModel? = propertyToViewModel[property] fun getFacadeForProperty(property: Observable): Property<*>? = propertyToFacade[property] /** * Register the combination of a property that has been bound to a property * that might be a facade in a ViewModel. This is done to be able to locate * the validation context for this binding. */ fun register(property: ObservableValue<*>, possiblyFacade: ObservableValue<*>?) { val propertyOwner = (possiblyFacade as? Property<*>)?.bean as? ViewModel if (propertyOwner != null) { propertyToFacade[property] = possiblyFacade propertyToViewModel[property] = propertyOwner } } } init { autocommitProperties.onChange { while (it.next()) { if (it.wasAdded()) { it.addedSubList.forEach { facade -> facade.addListener { obs, _, nv -> if (validate(fields = *arrayOf(facade))) propertyMap[obs]!!.invoke()?.value = nv } } } } } } /** * Wrap a JavaFX property and return the ViewModel facade for this property * * The value is returned in a lambda so that you can swap source objects * and call rebind to change the underlying source object in the mappings. * * You can bind a facade towards any kind of property as long as it can * be converted to a JavaFX property. TornadoFX provides a way to support * most property types via a concise syntax, see below for examples. * ``` * class PersonViewModel(var person: Person) : ViewModel() { * // Bind JavaFX property * val name = bind { person.nameProperty() } * * // Bind Kotlin var based property * val name = bind { person.observable(Person::name) } * * // Bind Java POJO getter/setter * val name = bind { person.observable(Person::getName, Person::setName) } * * // Bind Java POJO by property name (not type safe) * val name = bind { person.observable("name") } * } * ``` */ @Suppress("UNCHECKED_CAST") inline fun <reified PropertyType : Property<T>, reified T : Any, ResultType : PropertyType> bind(autocommit: Boolean = false, forceObjectProperty: Boolean = false, defaultValue: T? = null, noinline propertyProducer: () -> PropertyType?): ResultType { val prop = propertyProducer() val facade : Property<*> = if (forceObjectProperty) { BindingAwareSimpleObjectProperty<T>(this, prop?.name) } else { val propertyType = PropertyType::class.java val typeParam = T::class.java // Match PropertyType against known Property types first when { IntegerProperty::class.java.isAssignableFrom(propertyType) -> BindingAwareSimpleIntegerProperty(this, prop?.name) LongProperty::class.java.isAssignableFrom(propertyType) -> BindingAwareSimpleLongProperty(this, prop?.name) DoubleProperty::class.java.isAssignableFrom(propertyType) -> BindingAwareSimpleDoubleProperty(this, prop?.name) FloatProperty::class.java.isAssignableFrom(propertyType) -> BindingAwareSimpleFloatProperty(this, prop?.name) BooleanProperty::class.java.isAssignableFrom(propertyType) -> BindingAwareSimpleBooleanProperty(this, prop?.name) StringProperty::class.java.isAssignableFrom(propertyType) -> BindingAwareSimpleStringProperty(this, prop?.name) ObservableList::class.java.isAssignableFrom(propertyType) -> BindingAwareSimpleListProperty<T>(this, prop?.name) SimpleListProperty::class.java.isAssignableFrom(propertyType) -> BindingAwareSimpleListProperty<T>(this, prop?.name) List::class.java.isAssignableFrom(propertyType) -> BindingAwareSimpleListProperty<T>(this, prop?.name) ObservableSet::class.java.isAssignableFrom(propertyType) -> BindingAwareSimpleSetProperty<T>(this, prop?.name) Set::class.java.isAssignableFrom(propertyType) -> BindingAwareSimpleSetProperty<T>(this, prop?.name) Map::class.java.isAssignableFrom(propertyType) -> BindingAwareSimpleMapProperty<Any, Any>(this, prop?.name) ObservableMap::class.java.isAssignableFrom(propertyType) -> BindingAwareSimpleMapProperty<Any, Any>(this, prop?.name) // Match against the type of the Property java.lang.Integer::class.java.isAssignableFrom(typeParam) -> BindingAwareSimpleIntegerProperty(this, prop?.name) java.lang.Long::class.java.isAssignableFrom(typeParam) -> BindingAwareSimpleLongProperty(this, prop?.name) java.lang.Double::class.java.isAssignableFrom(typeParam) -> BindingAwareSimpleDoubleProperty(this, prop?.name) java.lang.Float::class.java.isAssignableFrom(typeParam) -> BindingAwareSimpleFloatProperty(this, prop?.name) java.lang.Boolean::class.java.isAssignableFrom(typeParam) -> BindingAwareSimpleBooleanProperty(this, prop?.name) java.lang.String::class.java.isAssignableFrom(typeParam) -> BindingAwareSimpleStringProperty(this, prop?.name) ObservableList::class.java.isAssignableFrom(typeParam) -> BindingAwareSimpleListProperty<T>(this, prop?.name) List::class.java.isAssignableFrom(typeParam) -> BindingAwareSimpleListProperty<T>(this, prop?.name) ObservableSet::class.java.isAssignableFrom(typeParam) -> BindingAwareSimpleSetProperty<T>(this, prop?.name) Set::class.java.isAssignableFrom(typeParam) -> BindingAwareSimpleSetProperty<T>(this, prop?.name) Map::class.java.isAssignableFrom(typeParam) -> BindingAwareSimpleMapProperty<Any,Any>(this, prop?.name) // Default to Object wrapper else -> BindingAwareSimpleObjectProperty<T>(this, prop?.name) } } assignValue(facade, prop, defaultValue) facade.addListener(dirtyListener) if (facade is ObservableList<*>) facade.addListener(dirtyListListener) propertyMap[facade] = propertyProducer propertyCache[facade] = prop // Listener that can track external changes for this facade externalChangeListeners[facade] = ChangeListener { _, _, nv -> val facadeProperty = (facade as Property<Any>) if (!facadeProperty.isBound) facadeProperty.value = nv } // Update facade when the property returned to us is changed externally prop?.addListener(externalChangeListeners[facade]!!) // Autocommit makes sure changes are written back to the underlying property. Validation will run before the commit is performed. if (autocommit) autocommitProperties.add(facade) return facade as ResultType } inline fun <reified T : Any> property(autocommit: Boolean = false, forceObjectProperty: Boolean = false, defaultValue: T? = null, noinline op: () -> Property<T>) = PropertyDelegate(bind(autocommit, forceObjectProperty, defaultValue, op)) val dirtyListener: ChangeListener<Any> = ChangeListener { property, _, newValue -> if (property in ignoreDirtyStateProperties) return@ChangeListener val sourceValue = propertyMap[property]!!.invoke()?.value if (sourceValue == newValue) { dirtyProperties.remove(property) } else if (property !in autocommitProperties && property !in dirtyProperties) { dirtyProperties.add(property) } } val dirtyListListener: ListChangeListener<Any> = ListChangeListener { c -> while (c.next()) { val property = c.list as ObservableValue<out Any> if (property !in ignoreDirtyStateProperties && property !in autocommitProperties && property !in dirtyProperties) { dirtyProperties.add(property) } } } val isDirty: Boolean get() = dirty.value val isNotDirty: Boolean get() = !isDirty fun validate(focusFirstError: Boolean = true, decorateErrors: Boolean = true, failFast: Boolean = false, vararg fields: ObservableValue<*>): Boolean = validationContext.validate(focusFirstError, decorateErrors,failFast, *fields) fun clearDecorators() = validationContext.validate(focusFirstError = false, decorateErrors = false) /** * This function is called after a successful commit, right before the optional successFn call sent to the commit * call is invoked. */ open fun onCommit() { } /** * This function is called after a successful commit, right before the optional successFn call sent to the commit * call is invoked. * * @param commits A list of the committed properties, including the old and new value */ open fun onCommit(commits: List<Commit>) { } fun commit(vararg fields: ObservableValue<*>, successFn: () -> Unit = {}) = commit(false, true, fields = *fields, successFn = successFn) /** * Perform validation and flush the values into the source object if validation passes. * * Optionally commit only the passed in properties instead of all (default). * * @param force Force flush even if validation fails */ fun commit(force: Boolean = false, focusFirstError: Boolean = true, vararg fields: ObservableValue<*>, successFn: () -> Unit = {}): Boolean { var committed = true val commits = mutableListOf<Commit>() runAndWait { if (!validate(focusFirstError, fields = *fields) && !force) { committed = false } else { val commitThese = if (fields.isNotEmpty()) fields.toList() else propertyMap.keys for (facade in commitThese) { val prop: Property<*>? = propertyMap[facade]?.invoke() if (prop != null) { val event = Commit(facade, prop.value, facade.value) commits.add(event) prop.value = facade.value } } dirtyProperties.removeAll(commitThese) } } if (committed) { onCommit() onCommit(commits) successFn.invoke() } return committed } fun markDirty(property: ObservableValue<*>) { require(propertyMap.containsKey(property)){"The property $property is not a facade of this ViewModel ($this)"} dirtyProperties+=property } /** * Rollback all or the specified fields */ @Suppress("UNCHECKED_CAST") fun rollback(vararg fields: Property<*>) { runAndWait { val rollbackThese = if (fields.isNotEmpty()) fields.toList() else propertyMap.keys for (facade in rollbackThese) { val prop: Property<*>? = propertyMap[facade]?.invoke() // Rebind external change listener in case the source property changed val oldProp = propertyCache[facade] if (oldProp != prop) { val extListener = externalChangeListeners[facade] as ChangeListener<Any> oldProp?.removeListener(extListener) prop?.removeListener(extListener) prop?.addListener(extListener) propertyCache[facade] = prop } assignValue(facade, prop) } dirtyProperties.clear() } } fun assignValue(facade: Property<*>, prop: Property<*>?, defaultValue: Any? = null) { facade.value = prop?.value ?: defaultValue // Never allow null collection values if (facade.value == null) { when (facade) { is ListProperty<*> -> facade.value = FXCollections.observableArrayList() is SetProperty<*> -> facade.value = FXCollections.observableSet() is MapProperty<*, *> -> facade.value = FXCollections.observableHashMap() is MutableList<*> -> facade.value = ArrayList<Any>() is MutableMap<*, *> -> facade.value = HashMap<Any, Any>() } } } inline fun <reified T> addValidator( node: Node, property: ObservableValue<T>, trigger: ValidationTrigger = ValidationTrigger.OnChange(), noinline validator: ValidationContext.(T?) -> ValidationMessage?) { validationContext.addValidator(node, property, trigger, validator) // Force update of valid state validationContext.validate(false, false) } fun setDecorationProvider(decorationProvider: (ValidationMessage) -> Decorator?) { validationContext.decorationProvider = decorationProvider } val isValid: Boolean get() = validationContext.isValid val valid: ReadOnlyBooleanProperty get() = validationContext.valid /** * Create a boolean binding indicating if the given list of properties are currently valid * with regards to the ValidationContext of this ViewModel. */ fun valid(vararg fields: Property<*>): BooleanExpression { val matchingValidators = FXCollections.observableArrayList<ValidationContext.Validator<*>>() fun updateMatchingValidators() { matchingValidators.setAll(validationContext.validators.filter { val facade = it.property.viewModelFacade facade != null && facade in fields }) } validationContext.validators.onChange { updateMatchingValidators() } updateMatchingValidators() return booleanListBinding(matchingValidators) { valid } } /** * Extract the value of the corresponding source property */ fun <T> backingValue(property: Property<T>) = propertyMap[property]?.invoke()?.value fun <T> isDirty(property: Property<T>) = backingValue(property) != property.value fun <T> isNotDirty(property: Property<T>) = !isDirty(property) } /** * Check if a given property from the ViewModel is dirty. This is a shorthand form of: * * `model.isDirty(model.property)` * * With this you can write: * * `model.property.isDirty` * */ val <T> Property<T>.isDirty: Boolean get() = (bean as? ViewModel)?.isDirty(this) ?: false val <T> Property<T>.isNotDirty: Boolean get() = !isDirty /** * Listen to changes in the given observable and call the op with the new value on change. * After each change the viewmodel is rolled back to reflect the values in the new source object or objects. */ fun <V : ViewModel, T> V.rebindOnChange(observable: ObservableValue<T>, op: V.(T?) -> Unit = {}) { observable.addListener { _, _, newValue -> op(this, newValue) rollback() } } /** * Rebind the itemProperty of the ViewModel when the itemProperty in the ListCellFragment changes. */ fun <V : ItemViewModel<T>, T> V.bindTo(itemFragment: ItemFragment<T>) = apply { itemProperty.bind(itemFragment.itemProperty) } /** * Rebind the itemProperty of the ViewModel when the itemProperty in the TableCellFragment changes. * TODO: Do we need this, or can we just use the one above? */ fun <V : ItemViewModel<T>, S, T> V.bindToItem(cellFragment: TableCellFragment<S, T>) = apply { itemProperty.bind(cellFragment.itemProperty) } /** * Rebind the rowItemProperty of the ViewModel when the itemProperty in the TableCellFragment changes. */ fun <V : ItemViewModel<S>, S, T> V.bindToRowItem(cellFragment: TableCellFragment<S, T>) = apply { itemProperty.bind(cellFragment.rowItemProperty) } fun <V : ViewModel, T : ObservableValue<X>, X> V.dirtyStateFor(modelField: KProperty1<V, T>): BooleanBinding { val prop = modelField.get(this) return Bindings.createBooleanBinding(Callable { prop in dirtyProperties }, dirtyProperties) } fun <V : ViewModel, T> V.rebindOnTreeItemChange(observable: ObservableValue<TreeItem<T>>, op: V.(T?) -> Unit) { observable.addListener { _, _, newValue -> op(newValue?.value) rollback() } } fun <V : ViewModel, T> V.rebindOnChange(tableview: TableView<T>, op: V.(T?) -> Unit) = rebindOnChange(tableview.selectionModel.selectedItemProperty(), op) fun <V : ViewModel, T> V.rebindOnChange(listview: ListView<T>, op: V.(T?) -> Unit) = rebindOnChange(listview.selectionModel.selectedItemProperty(), op) fun <V : ViewModel, T> V.rebindOnChange(treeview: TreeView<T>, op: V.(T?) -> Unit) = rebindOnTreeItemChange(treeview.selectionModel.selectedItemProperty(), op) fun <V : ViewModel, T> V.rebindOnChange(treetableview: TreeTableView<T>, op: V.(T?) -> Unit) = rebindOnTreeItemChange(treetableview.selectionModel.selectedItemProperty(), op) fun <T : ViewModel> T.rebind(op: (T.() -> Unit)) { op() rollback() } /** * Add the given validator to a property that resides inside a ViewModel. The supplied node will be * decorated by the current decorationProvider for this context inside the ViewModel of the property * if validation fails. * * The validator function is executed in the scope of this ValidationContext to give * access to other fields and shortcuts like the error and warning functions. * * The validation trigger decides when the validation is applied. ValidationTrigger.OnBlur * tracks focus on the supplied node while OnChange tracks changes to the property itself. */ inline fun <reified T> Property<T>.addValidator(node: Node, trigger: ValidationTrigger = ValidationTrigger.OnChange(), noinline validator: ValidationContext.(T?) -> ValidationMessage?) = requireNotNull(bean as? ViewModel){"The addValidator extension on Property can only be used on properties inside a ViewModel. Use validator.addValidator() instead."} .addValidator(node, this, trigger, validator) fun TextInputControl.required(trigger: ValidationTrigger = ValidationTrigger.OnChange(), message: String? = viewModelBundle["required"]) = validator(trigger) { if (it.isNullOrBlank()) error(message) else null } inline fun <reified T> ComboBoxBase<T>.required(trigger: ValidationTrigger = ValidationTrigger.OnChange(), message: String? = viewModelBundle["required"]) = validator(trigger) { if (it == null) error(message) else null } /** * Add a validator to a ComboBox that is already bound to a model property. */ inline fun <reified T> ComboBoxBase<T>.validator(trigger: ValidationTrigger = ValidationTrigger.OnChange(), noinline validator: ValidationContext.(T?) -> ValidationMessage?) = validator(this, valueProperty(), trigger, validator) /** * Add a validator to a ChoiceBox that is already bound to a model property. */ inline fun <reified T> ChoiceBox<T>.validator(trigger: ValidationTrigger = ValidationTrigger.OnChange(), noinline validator: ValidationContext.(T?) -> ValidationMessage?) = validator(this, valueProperty(), trigger, validator) /** * Add a validator to a Spinner that is already bound to a model property. */ inline fun <reified T> Spinner<T>.validator(trigger: ValidationTrigger = ValidationTrigger.OnChange(), noinline validator: ValidationContext.(T?) -> ValidationMessage?) = validator(this, valueFactory.valueProperty(), trigger, validator) /** * Add a validator to a TextInputControl that is already bound to a model property. */ fun TextInputControl.validator(trigger: ValidationTrigger = ValidationTrigger.OnChange(), validator: ValidationContext.(String?) -> ValidationMessage?) = validator(this, textProperty(), trigger, validator) /** * Add a validator to a Labeled Control that is already bound to a model property. */ fun Labeled.validator(trigger: ValidationTrigger = ValidationTrigger.OnChange(), validator: ValidationContext.(String?) -> ValidationMessage?) = validator(this, textProperty(), trigger, validator) /** * Add a validator to a ColorPicker that is already bound to a model property. */ fun ColorPicker.validator(trigger: ValidationTrigger = ValidationTrigger.OnChange(), validator: ValidationContext.(Paint?) -> ValidationMessage?) = validator(this, valueProperty(), trigger, validator) /** * Add a validator to a DatePicker that is already bound to a model property. */ fun DatePicker.validator(trigger: ValidationTrigger = ValidationTrigger.OnChange(), validator: ValidationContext.(LocalDate?) -> ValidationMessage?) = validator(this, valueProperty(), trigger, validator) /** * Add a validator to a CheckBox that is already bound to a model property. */ fun CheckBox.validator(trigger: ValidationTrigger = ValidationTrigger.OnChange(), validator: ValidationContext.(Boolean?) -> ValidationMessage?) = validator(this, selectedProperty(), trigger, validator) /** * Add a validator to a RadioButton that is already bound to a model property. */ fun RadioButton.validator(trigger: ValidationTrigger = ValidationTrigger.OnChange(), validator: ValidationContext.(Boolean?) -> ValidationMessage?) = validator(this, selectedProperty(), trigger, validator) /** * Add a validator to the given Control for the given model property. */ inline fun <reified T> validator(control: Control, property: Property<T>, trigger: ValidationTrigger, model: ViewModel? = null, noinline validator: ValidationContext.(T?) -> ValidationMessage?) = requireNotNull(model ?: property.viewModel){ "The addValidator extension can only be used on inputs that are already bound bidirectionally to a property in a Viewmodel. " + "Use validator.addValidator() instead or make the property's bean field point to a ViewModel." }.addValidator(control, property, trigger, validator) inline fun <reified T> validator(control: Control, property: Property<T>, trigger: ValidationTrigger, noinline validator: ValidationContext.(T?) -> ValidationMessage?) = validator(control, property, trigger, null, validator) /** * Extract the ViewModel from a property that is bound towards a ViewModel Facade */ @Suppress("UNCHECKED_CAST") val Property<*>.viewModel: ViewModel? get() = (bean as? ViewModel) ?: ViewModel.getViewModelForProperty(this) /** * Extract the ViewModel Facade from a property that is bound towards it */ val ObservableValue<*>.viewModelFacade: Property<*>? get() = ViewModel.getFacadeForProperty(this) @Suppress("UNCHECKED_CAST") open class ItemViewModel<T> @JvmOverloads constructor(initialValue: T? = null, val itemProperty: ObjectProperty<T> = SimpleObjectProperty(initialValue)) : ViewModel() { var item by itemProperty val empty = itemProperty.isNull val isEmpty: Boolean get() = empty.value val isNotEmpty: Boolean get() = empty.value.not() init { rebindOnChange(itemProperty) } fun <N> select(nested: (T) -> ObservableValue<N>) = itemProperty.select(nested) fun asyncItem(func: () -> T?) = task { func() } success { if (itemProperty.isBound && item is JsonModel) (item as JsonModel).update(it as JsonModel) else item = it } @JvmName("bindField") inline fun <reified N : Any, ReturnType : Property<N>> bind(property: KProperty1<T, N?>, autocommit: Boolean = false, forceObjectProperty: Boolean = false, defaultValue: N? = null): ReturnType = bind(autocommit, forceObjectProperty, defaultValue) { item?.let { property.get(it).toProperty() } } @JvmName("bindMutableField") inline fun <reified N : Any, ReturnType : Property<N>> bind(property: KMutableProperty1<T, N>, autocommit: Boolean = false, forceObjectProperty: Boolean = false, defaultValue: N? = null): ReturnType = bind(autocommit, forceObjectProperty, defaultValue) { item?.observable(property) } @JvmName("bindMutableNullableField") inline fun <reified N : Any, ReturnType : Property<N>> bind(property: KMutableProperty1<T, N?>, autocommit: Boolean = false, forceObjectProperty: Boolean = false, defaultValue: N? = null): ReturnType = bind(autocommit, forceObjectProperty, defaultValue) { (item?.observable(property) ?: SimpleObjectProperty<N>()) as Property<N> } @JvmName("bindProperty") inline fun <reified N : Any, reified PropertyType : Property<N>, ReturnType : PropertyType> bind(property: KProperty1<T, PropertyType>, autocommit: Boolean = false, forceObjectProperty: Boolean = false, defaultValue: N? = null): ReturnType = bind(autocommit, forceObjectProperty, defaultValue) { item?.let { property.get(it) } } @JvmName("bindMutableProperty") inline fun <reified N : Any, reified PropertyType : Property<N>, ReturnType : PropertyType> bind(property: KMutableProperty1<T, PropertyType>, autocommit: Boolean = false, forceObjectProperty: Boolean = false): ReturnType = bind(autocommit, forceObjectProperty) { item?.observable(property) } as ReturnType @JvmName("bindGetter") inline fun <reified N : Any, ReturnType : Property<N>> bind(property: KFunction<N>, autocommit: Boolean = false, forceObjectProperty: Boolean = false, defaultValue: N? = null): ReturnType = bind(autocommit, forceObjectProperty, defaultValue) { item?.let { property.call(it).toProperty() } } @JvmName("bindPropertyFunction") inline fun <reified N : Any, reified PropertyType : Property<N>, ReturnType : PropertyType> bind(property: KFunction<PropertyType>, autocommit: Boolean = false, forceObjectProperty: Boolean = false, defaultValue: N? = null): ReturnType = bind(autocommit, forceObjectProperty, defaultValue) { item?.let { property.call(it) } } } class Commit(val property: ObservableValue<*>, val oldValue: Any?, val newValue: Any?) { val changed: Boolean get() = oldValue != newValue } /** * Mark this ViewModel facade property as dirty in it's owning ViewModel. */ fun Property<*>.markDirty() = viewModel?.markDirty(this)
apache-2.0
c0c38f6755e37992f54be4329dd81113
47.701389
254
0.68398
4.694895
false
false
false
false
GunoH/intellij-community
java/java-impl/src/com/intellij/javadoc/JavadocGenerationAdditionalUi.kt
2
4556
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.javadoc import com.intellij.java.JavaBundle import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.NlsSafe import com.intellij.psi.PsiKeyword import com.intellij.ui.dsl.builder.* import com.intellij.ui.layout.selected import javax.swing.* class JavadocGenerationAdditionalUi { lateinit var myIncludeLibraryCb: JCheckBox lateinit var myLinkToJdkDocs: JCheckBox lateinit var myTfOutputDir: TextFieldWithBrowseButton lateinit var myScopeCombo: ComboBox<@NlsSafe String> lateinit var myHierarchy: JCheckBox lateinit var myNavigator: JCheckBox lateinit var myIndex: JCheckBox lateinit var mySeparateIndex: JCheckBox lateinit var myTagUse: JCheckBox lateinit var myTagAuthor: JCheckBox lateinit var myTagVersion: JCheckBox lateinit var myTagDeprecated: JCheckBox lateinit var myDeprecatedList: JCheckBox lateinit var myLocaleTextField: JTextField lateinit var myOtherOptionsField: JTextField lateinit var myHeapSizeField: JTextField lateinit var myOpenInBrowserCheckBox: JCheckBox val panel: JPanel = panel { group(JavaBundle.message("javadoc.generate.options.separator")) { row { myIncludeLibraryCb = checkBox(JavaBundle.message("javadoc.generate.include.jdk.library.sources.in.sourcepath.option")).component } row { myLinkToJdkDocs = checkBox(JavaBundle.message("javadoc.generate.link.to.jdk.documentation.option")).component } row(JavaBundle.message("javadoc.generate.output.directory")) { myTfOutputDir = textFieldWithBrowseButton(JavaBundle.message("javadoc.generate.output.directory.browse"), null, FileChooserDescriptorFactory.createSingleFolderDescriptor()) .align(AlignX.FILL) .component bottomGap(BottomGap.MEDIUM) } .layout(RowLayout.INDEPENDENT) row(JavaBundle.message("javadoc.generate.scope.row")) { myScopeCombo = comboBox(listOf(PsiKeyword.PUBLIC, PsiKeyword.PROTECTED, PsiKeyword.PACKAGE, PsiKeyword.PRIVATE)) .component } .layout(RowLayout.INDEPENDENT) row { panel { row { myHierarchy = checkBox(JavaBundle.message("javadoc.generate.options.hierarchy")).component } row { myNavigator = checkBox(JavaBundle.message("javadoc.generate.options.navigator")).component } row { myIndex = checkBox(JavaBundle.message("javadoc.generate.options.index")).component } indent { row { mySeparateIndex = checkBox(JavaBundle.message("javadoc.generate.options.index.per.letter")) .enabledIf(myIndex.selected) .component } } } .gap(RightGap.COLUMNS) .align(AlignY.TOP) panel { row { myTagUse = checkBox("@use").component } row { myTagAuthor = checkBox("@author").component } row { myTagVersion = checkBox("@version").component } row { myTagDeprecated = checkBox("@deprecated").component } indent { row { myDeprecatedList = checkBox(JavaBundle.message("javadoc.generate.tag.list.deprecated")) .enabledIf(myTagDeprecated.selected) .component } } } .align(AlignY.TOP) bottomGap(BottomGap.MEDIUM) } row(JavaBundle.message("javadoc.generate.locale")) { myLocaleTextField = textField() .align(AlignX.FILL) .component } row(JavaBundle.message("javadoc.generate.arguments")) { myOtherOptionsField = textField() .align(AlignX.FILL) .component } row(JavaBundle.message("javadoc.generate.heap.size")) { myHeapSizeField = intTextField(IntRange(0, Int.MAX_VALUE), 128) .gap(RightGap.SMALL) .component @Suppress("DialogTitleCapitalization") label(JavaBundle.message("megabytes.unit")) } row { myOpenInBrowserCheckBox = checkBox(JavaBundle.message("javadoc.generate.open.in.browser")).component } } } }
apache-2.0
9fd1d9c10d0cde1dfe5fa1633282b980
34.601563
158
0.659789
4.826271
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/util/CoroutineUtils.kt
1
6797
// 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.util import com.intellij.debugger.engine.SuspendContextImpl import com.intellij.debugger.engine.evaluation.EvaluationContextImpl import com.intellij.debugger.impl.DebuggerUtilsEx import com.intellij.debugger.jdi.StackFrameProxyImpl import com.intellij.debugger.jdi.ThreadReferenceProxyImpl import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.search.GlobalSearchScope import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.XDebuggerUtil import com.intellij.xdebugger.XSourcePosition import com.sun.jdi.* import org.jetbrains.kotlin.idea.debugger.* import org.jetbrains.kotlin.idea.debugger.coroutine.data.SuspendExitMode import org.jetbrains.kotlin.idea.debugger.evaluate.DefaultExecutionContext import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runReadAction const val CREATION_STACK_TRACE_SEPARATOR = "\b\b\b" // the "\b\b\b" is used as creation stacktrace separator in kotlinx.coroutines const val CREATION_CLASS_NAME = "_COROUTINE._CREATION" fun Method.isInvokeSuspend(): Boolean = name() == "invokeSuspend" && signature() == "(Ljava/lang/Object;)Ljava/lang/Object;" fun Method.isInvoke(): Boolean = name() == "invoke" && signature().contains("Ljava/lang/Object;)Ljava/lang/Object;") fun Method.isSuspendLambda() = isInvokeSuspend() && declaringType().isSuspendLambda() fun Method.hasContinuationParameter() = signature().contains("Lkotlin/coroutines/Continuation;)") fun Location.getSuspendExitMode(): SuspendExitMode { val method = safeMethod() ?: return SuspendExitMode.NONE if (method.isSuspendLambda()) return SuspendExitMode.SUSPEND_LAMBDA else if (method.hasContinuationParameter()) return SuspendExitMode.SUSPEND_METHOD_PARAMETER else if ((method.isInvokeSuspend() || method.isInvoke()) && safeCoroutineExitPointLineNumber()) return SuspendExitMode.SUSPEND_METHOD return SuspendExitMode.NONE } fun Location.safeCoroutineExitPointLineNumber() = (wrapIllegalArgumentException { DebuggerUtilsEx.getLineNumber(this, false) } ?: -2) == -1 fun ReferenceType.isContinuation() = isBaseContinuationImpl() || isSubtype("kotlin.coroutines.Continuation") fun Type.isBaseContinuationImpl() = isSubtype("kotlin.coroutines.jvm.internal.BaseContinuationImpl") fun Type.isAbstractCoroutine() = isSubtype("kotlinx.coroutines.AbstractCoroutine") fun Type.isCoroutineScope() = isSubtype("kotlinx.coroutines.CoroutineScope") fun Type.isSubTypeOrSame(className: String) = name() == className || isSubtype(className) fun ReferenceType.isSuspendLambda() = SUSPEND_LAMBDA_CLASSES.any { isSubtype(it) } fun Location.isInvokeSuspend() = safeMethod()?.isInvokeSuspend() ?: false fun Location.isInvokeSuspendWithNegativeLineNumber() = isInvokeSuspend() && safeLineNumber() < 0 fun Location.isFilteredInvokeSuspend() = isInvokeSuspend() || isInvokeSuspendWithNegativeLineNumber() fun StackFrameProxyImpl.variableValue(variableName: String): ObjectReference? { val continuationVariable = safeVisibleVariableByName(variableName) ?: return null return getValue(continuationVariable) as? ObjectReference ?: return null } fun StackFrameProxyImpl.continuationVariableValue(): ObjectReference? = variableValue("\$continuation") fun StackFrameProxyImpl.thisVariableValue(): ObjectReference? = this.thisObject() private fun Method.isGetCoroutineSuspended() = signature() == "()Ljava/lang/Object;" && name() == "getCOROUTINE_SUSPENDED" && declaringType().name() == "kotlin.coroutines.intrinsics.IntrinsicsKt__IntrinsicsKt" fun DefaultExecutionContext.findCoroutineMetadataType() = debugProcess.invokeInManagerThread { findClassSafe("kotlin.coroutines.jvm.internal.DebugMetadataKt") } fun DefaultExecutionContext.findDispatchedContinuationReferenceType(): List<ReferenceType>? = vm.classesByName("kotlinx.coroutines.DispatchedContinuation") fun DefaultExecutionContext.findCancellableContinuationImplReferenceType(): List<ReferenceType>? = vm.classesByName("kotlinx.coroutines.CancellableContinuationImpl") fun hasGetCoroutineSuspended(frames: List<StackFrameProxyImpl>) = frames.indexOfFirst { it.safeLocation()?.safeMethod()?.isGetCoroutineSuspended() == true } fun StackTraceElement.isCreationSeparatorFrame() = className.startsWith(CREATION_STACK_TRACE_SEPARATOR) || className == CREATION_CLASS_NAME fun Location.findPosition(project: Project) = runReadAction { if (declaringType() != null) getPosition(project, declaringType().name(), lineNumber()) else null } private fun getPosition(project: Project, className: String, lineNumber: Int): XSourcePosition? { val psiFacade = JavaPsiFacade.getInstance(project) val psiClass = psiFacade.findClass( className.substringBefore("$"), // find outer class, for which psi exists TODO GlobalSearchScope.everythingScope(project) ) val classFile = psiClass?.containingFile?.virtualFile // to convert to 0-based line number or '-1' to do not move val localLineNumber = if (lineNumber > 0) lineNumber - 1 else return null return XDebuggerUtil.getInstance().createPosition(classFile, localLineNumber) } fun SuspendContextImpl.executionContext() = invokeInManagerThread { DefaultExecutionContext(EvaluationContextImpl(this, this.frameProxy)) } fun <T : Any> SuspendContextImpl.invokeInManagerThread(f: () -> T?): T? = debugProcess.invokeInManagerThread { f() } fun ThreadReferenceProxyImpl.supportsEvaluation(): Boolean = threadReference?.isSuspended ?: false fun SuspendContextImpl.supportsEvaluation() = this.debugProcess.canRunEvaluation || isUnitTestMode() fun XDebugSession.suspendContextImpl() = suspendContext as SuspendContextImpl fun threadAndContextSupportsEvaluation(suspendContext: SuspendContextImpl, frameProxy: StackFrameProxyImpl?) = suspendContext.invokeInManagerThread { suspendContext.supportsEvaluation() && frameProxy?.threadProxy()?.supportsEvaluation() ?: false } ?: false fun Location.sameLineAndMethod(location: Location?): Boolean = location != null && location.safeMethod() == safeMethod() && location.safeLineNumber() == safeLineNumber() fun Location.isFilterFromTop(location: Location?): Boolean = isFilteredInvokeSuspend() || sameLineAndMethod(location) || location?.safeMethod() == safeMethod() fun Location.isFilterFromBottom(location: Location?): Boolean = sameLineAndMethod(location)
apache-2.0
206862fc7c5d6bda16d06102696a0a44
42.299363
166
0.774901
4.726704
false
false
false
false
smmribeiro/intellij-community
platform/platform-tests/testSrc/com/intellij/formatting/engine/testModelTests/TestFormattingModelBuilderTest.kt
32
2798
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.formatting.engine.testModelTests import com.intellij.formatting.Block import com.intellij.formatting.CompositeTestBlock import com.intellij.formatting.engine.testModel.getRoot import com.intellij.formatting.toFormattingBlock import com.intellij.openapi.util.TextRange import com.intellij.util.containers.TreeTraversal import org.assertj.core.api.Assertions.assertThat import org.junit.Test class TestFormattingModelBuilderTest { @Test fun `test model with correct ranges is built`() { val root = getRoot( """[a0]foo [a1]goo []hoo [a1]([a2]qoo [a2]woo [a3]([]roo []too))""" ) val rootFormattingBlock = root.toFormattingBlock(0) val subBlocks = rootFormattingBlock.subBlocks assertThat(subBlocks).hasSize(4) assertThat(subBlocks.last().subBlocks).hasSize(3) assertThat(subBlocks.last().subBlocks.last().subBlocks).hasSize(2) assertLeafRanges(rootFormattingBlock, 0..3, 12..15, 30..33, 34..37, 50..53, 60..63, 64..67) } private fun assertLeafRanges(rootFormattingBlock: CompositeTestBlock, vararg ranges: IntRange) { val textRanges = ranges.map { TextRange(it.start, it.endInclusive) } val leafs = TreeTraversal.LEAVES_DFS.createIterator<Block>(rootFormattingBlock.subBlocks, { it.subBlocks }).toList() assertThat(textRanges).isEqualTo(leafs.map { it.textRange }) } @Test fun `test alignment parsing`() { val root = getRoot("[a0]foo [a1]goo [a0]hoo") val rootBlock = root.toFormattingBlock(0) assertLeafRanges(rootBlock, 0..3, 4..7, 8..11) val children = rootBlock.subBlocks assertThat(children[0].alignment).isNotNull() assertThat(children[1].alignment).isNotNull() assertThat(children[0].alignment).isEqualTo(children[2].alignment) } @Test fun `test empty block`() { val root = getRoot( """[a0]fooooo [a1] [a0]go [a1]boo """).toFormattingBlock(0) val children = root.subBlocks assertThat(children).hasSize(4) assertThat(children[0].alignment).isEqualTo(children[2].alignment) assertThat(children[1].alignment).isEqualTo(children[3].alignment) assertThat(children[1].textRange.isEmpty).isTrue() } }
apache-2.0
aaf08b8d8723488fd07685286c7420e6
32.722892
120
0.722659
3.770889
false
true
false
false
smmribeiro/intellij-community
java/execution/impl/src/com/intellij/execution/util/UnknownAlternativeSdkResolver.kt
9
5474
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.util import com.intellij.build.BuildContentManager import com.intellij.execution.CantRunException import com.intellij.execution.ExecutionBundle import com.intellij.execution.runners.ExecutionUtil import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.impl.UnknownSdkFixAction import com.intellij.openapi.projectRoots.impl.UnknownSdkTracker import com.intellij.openapi.roots.ui.configuration.SdkLookup import com.intellij.openapi.roots.ui.configuration.SdkLookup.Companion.newLookupBuilder import com.intellij.openapi.roots.ui.configuration.SdkLookupDecision import com.intellij.openapi.roots.ui.configuration.SdkLookupDownloadDecision import com.intellij.openapi.roots.ui.configuration.SdkLookupParameters import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk import java.util.concurrent.atomic.AtomicReference import javax.swing.event.HyperlinkEvent import javax.swing.event.HyperlinkListener @Service //project class UnknownAlternativeSdkResolver(private val project: Project) { companion object { @JvmStatic fun getInstance(project: Project) = project.service<UnknownAlternativeSdkResolver>() } @Throws(CantRunException::class) fun notifyUserToResolveJreAndFail(jreHome: String) : Nothing { val notification = Notification("JDK resolve problems", ProjectBundle.message("failed.to.resolve.sdk.notification.title"), "", NotificationType.INFORMATION) notification.addAction(object : AnAction(ProjectBundle.message("try.to.find.sdk.notification.action")) { override fun actionPerformed(e: AnActionEvent) { try { tryResolveJre(jreHome) } catch (e: CantRunException) { val buildToolWindowId = BuildContentManager.getInstance(project).orCreateToolWindow.id ExecutionUtil.handleExecutionError(project, buildToolWindowId, ProjectBundle.message("resolve.sdk.task.name"), e) } } }) notification.notify(project) throw CantRunException.CustomProcessedCantRunException() } @Throws(CantRunException::class) private fun tryResolveJre(jreHome: String) : Sdk? { if (!Registry.`is`("jdk.auto.run.configurations")) return null val javaSdk = JavaSdk.getInstance() //assume it is a JDK name reference if (jreHome.contains("/") || jreHome.contains("\\")) return null val theDownload = AtomicReference<Sdk?>(null) val theSdk = AtomicReference<Sdk?>(null) val theFix = AtomicReference<UnknownSdkFixAction>(null) object : Task.Modal(project, ProjectBundle.message("progress.title.resolving.sdks"), true) { override fun run(indicator: ProgressIndicator) { val lookup = newLookupBuilder() .withProgressIndicator(indicator) .withProject(project) .withSdkName(jreHome) .withSdkType(javaSdk) .onDownloadingSdkDetected { sdk: Sdk -> theDownload.set(sdk) SdkLookupDownloadDecision.STOP } .onSdkFixResolved { fix: UnknownSdkFixAction -> theFix.set(fix) SdkLookupDecision.STOP } .onSdkResolved { sdk: Sdk? -> theSdk.set(sdk) } SdkLookup.getInstance().lookupBlocking(lookup as SdkLookupParameters) val fix = theFix.get() if (theSdk.get() == null && fix != null && UnknownSdkTracker.getInstance(project).isAutoFixAction(fix)) { theFix.set(null) invokeAndWaitIfNeeded { if (project.isDisposed) return@invokeAndWaitIfNeeded val sdk = UnknownSdkTracker.getInstance(project).applyAutoFixAndNotify(fix, indicator) theSdk.set(sdk) } } } }.queue() val found = theSdk.get() if (found != null) return found val downloading = theDownload.get() if (downloading != null) { throw CantRunException( ExecutionBundle.message("jre.path.is.not.valid.jre.home.downloading.message", jreHome)) } val fix = theFix.get() if (fix != null) { val builder = HtmlBuilder() val linkTarget = "this-is-an-action-to-fix-jdk" builder.append(ExecutionBundle.message("jre.path.is.not.valid.jre.home.error.message", jreHome)) builder.append(HtmlChunk.br()) builder.append(HtmlChunk.link(linkTarget, fix.actionDetailedText)) throw object : CantRunException(builder.toString()), HyperlinkListener { override fun hyperlinkUpdate(e: HyperlinkEvent) { if (e.eventType != HyperlinkEvent.EventType.ACTIVATED) return fix.applySuggestionAsync(project) } } } return null } }
apache-2.0
435d69596839404d27f34cb5a46f0f1f
40.78626
160
0.734015
4.461288
false
false
false
false
80998062/Fank
presentation/src/main/java/com/sinyuk/fanfou/util/linkfy/LinkTouchMovementMethod.kt
1
3849
/* * * * Apache License * * * * Copyright [2017] Sinyuk * * * * 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.sinyuk.fanfou.util.linkfy import android.text.Selection import android.text.Spannable import android.text.method.LinkMovementMethod import android.text.method.MovementMethod import android.view.MotionEvent import android.widget.TextView /** * A movement method that only highlights any touched * [TouchableUrlSpan]s * * * Adapted from http://stackoverflow.com/a/20905824 */ class LinkTouchMovementMethod : LinkMovementMethod() { private var pressedSpan: TouchableUrlSpan? = null override fun onTouchEvent(textView: TextView, spannable: Spannable, event: MotionEvent): Boolean { // Reference to // @link:{http://angeldevil.me/2015/09/08/Two-problems-about-LinkMovementMethod-and-URLSPan/} // LinkMovementMethod导致TextView可滚动,可能使文本错位 val action = event.action if (action == MotionEvent.ACTION_MOVE) { // Prevent scroll event return true } var handled = false if (event.action == MotionEvent.ACTION_DOWN) { pressedSpan = getPressedSpan(textView, spannable, event) if (pressedSpan != null) { pressedSpan!!.setPressed(true) Selection.setSelection(spannable, spannable.getSpanStart(pressedSpan), spannable.getSpanEnd(pressedSpan)) handled = true } } else if (event.action == MotionEvent.ACTION_MOVE) { val touchedSpan = getPressedSpan(textView, spannable, event) if (pressedSpan != null && touchedSpan != pressedSpan) { pressedSpan!!.setPressed(false) pressedSpan = null Selection.removeSelection(spannable) } } else { if (pressedSpan != null) { pressedSpan!!.setPressed(false) super.onTouchEvent(textView, spannable, event) handled = true } pressedSpan = null Selection.removeSelection(spannable) } return handled } private fun getPressedSpan(textView: TextView, buffer: Spannable, event: MotionEvent): TouchableUrlSpan? { var x = event.x.toInt() var y = event.y.toInt() x -= textView.totalPaddingLeft y -= textView.totalPaddingTop x += textView.scrollX y += textView.scrollY val layout = textView.layout val line = layout.getLineForVertical(y) val off = layout.getOffsetForHorizontal(line, x.toFloat()) val link = buffer.getSpans(off, off, TouchableUrlSpan::class.java) var touchedSpan: TouchableUrlSpan? = null if (link.isNotEmpty()) touchedSpan = link[0] return touchedSpan } companion object { private var instance: LinkTouchMovementMethod? = null fun getInstance(): MovementMethod { if (instance == null) { synchronized(LinkTouchMovementMethod::class.java) { if (instance == null) instance = LinkTouchMovementMethod() } } return instance!! } } }
mit
d25ca5ca95056187f4cd0f136b3b6e86
31.134454
110
0.61967
4.589436
false
false
false
false
ThiagoGarciaAlves/intellij-community
plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightProfile.kt
2
2140
/* * Copyright 2000-2017 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.maddyhome.idea.copyright import com.intellij.configurationStore.SerializableScheme import com.intellij.configurationStore.serializeObjectInto import com.intellij.openapi.components.BaseState import com.intellij.openapi.options.ExternalizableScheme import com.intellij.util.xmlb.annotations.OptionTag import com.intellij.util.xmlb.annotations.Transient import com.maddyhome.idea.copyright.pattern.EntityUtil import org.jdom.Element @JvmField val DEFAULT_COPYRIGHT_NOTICE: String = EntityUtil.encode( "Copyright (c) \$today.year. Lorem ipsum dolor sit amet, consectetur adipiscing elit. \n" + "Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. \n" + "Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. \n" + "Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. \n" + "Vestibulum commodo. Ut rhoncus gravida arcu. ") class CopyrightProfile @JvmOverloads constructor(profileName: String? = null) : ExternalizableScheme, BaseState(), SerializableScheme { // ugly name to preserve compatibility // must be not private because otherwise binding is not created for private accessor @get:OptionTag("myName") var profileName by string() var notice by property(DEFAULT_COPYRIGHT_NOTICE) var keyword by property(EntityUtil.encode("Copyright")) var allowReplaceRegexp by string() @Deprecated("use allowReplaceRegexp instead", ReplaceWith("")) var allowReplaceKeyword by string() init { // otherwise will be as default value and name will be not serialized this.profileName = profileName } // ugly name to preserve compatibility @Transient override fun getName() = profileName ?: "" override fun setName(value: String) { profileName = value } override fun toString() = profileName ?: "" override fun writeScheme(): Element { val element = Element("copyright") serializeObjectInto(this, element) return element } }
apache-2.0
3fc63e18295ab971edd6f46cd6d985fb
37.909091
140
0.767757
4.139265
false
false
false
false
sky-map-team/stardroid
app/src/main/java/com/google/android/stardroid/math/TimeUtils.kt
1
4219
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.stardroid.math import java.util.* import kotlin.math.floor public const val MINUTES_PER_HOUR = 60.0 public const val SECONDS_PER_HOUR = 3600.0 // Convert from hours to degrees public const val HOURS_TO_DEGREES = 360.0f / 24.0f /** * Utilities for working with Dates and times. * * @author Kevin Serafini * @author Brent Bryan */ /** * Calculates the number of Julian Centuries from the epoch 2000.0 * (equivalent to Julian Day 2451545.0). */ fun julianCenturies(date: Date): Double { val jd = julianDay(date) val delta = jd - 2451545.0 return delta / 36525.0 } /** * Calculates the Julian Day for a given date using the following formula: * JD = 367 * Y - INT(7 * (Y + INT((M + 9)/12))/4) + INT(275 * M / 9) * + D + 1721013.5 + UT/24 * * Note that this is only valid for the year range 1900 - 2099. */ fun julianDay(date: Date): Double { val cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")) cal.time = date val hour = (cal[Calendar.HOUR_OF_DAY] + cal[Calendar.MINUTE] / MINUTES_PER_HOUR + cal[Calendar.SECOND] / SECONDS_PER_HOUR) val year = cal[Calendar.YEAR] val month = cal[Calendar.MONTH] + 1 val day = cal[Calendar.DAY_OF_MONTH] return (367.0 * year - floor( 7.0 * (year + floor((month + 9.0) / 12.0)) / 4.0 ) + floor(275.0 * month / 9.0) + day + 1721013.5 + hour / 24.0) } /** * Converts the given Julian Day to Gregorian Date (in UT time zone). * Based on the formula given in the Explanatory Supplement to the * Astronomical Almanac, pg 604. */ fun gregorianDate(julianDay: Double): Date { var l = julianDay.toInt() + 68569 val n = 4 * l / 146097 l -= (146097 * n + 3) / 4 val i = 4000 * (l + 1) / 1461001 l -= 1461 * i / 4 + 31 val j = 80 * l / 2447 val d = l - 2447 * j / 80 l = j / 11 val m = j + 2 - 12 * l val y = 100 * (n - 49) + i + l val fraction = julianDay - floor(julianDay) val dHours = fraction * 24.0 val hours = dHours.toInt() val dMinutes = (dHours - hours) * 60.0 val minutes = dMinutes.toInt() val seconds = ((dMinutes - minutes) * 60.0).toInt() val cal = Calendar.getInstance(TimeZone.getTimeZone("UT")) cal[y, m - 1, d, hours + 12, minutes] = seconds return cal.time } /** * Calculates local mean sidereal time in degrees. Note that longitude is * negative for western longitude values. */ fun meanSiderealTime(date: Date, longitude: Float): Float { // First, calculate number of Julian days since J2000.0. val jd = julianDay(date) val delta = jd - 2451545.0f // Calculate the global and local sidereal times val gst = 280.461f + 360.98564737f * delta val lst = normalizeAngle(gst + longitude) return lst.toFloat() } /** * Normalizes the angle to the range 0 <= value < 360. */ private fun normalizeAngle(angleDegrees: Double): Double { return positiveMod(angleDegrees, 360.0) } /** * Normalizes the time to the range 0 <= value < 24. */ fun normalizeHours(time: Double): Double { return positiveMod(time, 24.0) } /** * Take a universal time between 0 and 24 and return a triple * [hours, minutes, seconds]. * * @param universalTime Universal time - presumed to be between 0 and 24. * @return [hours, minutes, seconds] */ fun clockTimeFromHrs(universalTime: Double): IntArray { val hms = IntArray(3) hms[0] = floor(universalTime).toInt() val remainderMins = MINUTES_PER_HOUR * (universalTime - hms[0]) hms[1] = floor(remainderMins).toInt() hms[2] = floor(remainderMins - hms[1]).toInt() return hms }
apache-2.0
6c50de6e786313705fda08e85e8a1370
30.492537
96
0.653946
3.314218
false
false
false
false
Duke1/UnrealMedia
UnrealMedia/app/src/main/java/com/qfleng/um/util/BitmapHelper.kt
1
2211
package com.qfleng.um.util import android.content.Context import android.graphics.Bitmap import androidx.renderscript.Allocation import androidx.renderscript.Element import androidx.renderscript.RenderScript import androidx.renderscript.ScriptIntrinsicBlur object BitmapHelper { /** * 使用 RenderScript 对图片进行高斯模糊 *参考:https://mrfzh.github.io/2019/11/14/%E9%AB%98%E6%96%AF%E6%A8%A1%E7%B3%8A%E7%9A%84%E5%AE%9E%E7%8E%B0/ * @param context * @param originImage 原图 * @param blurRadius 模糊半径,取值区间为 (0, 25] * @param scaleRatio 缩小比例,假设传入 a,那么图片的宽高是原来的 1 / a 倍,取值 >= 1 * @return */ fun blurBitmap(context: Context, originImage: Bitmap, blurRadius: Float, scaleRatio: Int): Bitmap { require(!(blurRadius <= 0 || blurRadius > 25f || scaleRatio < 1)) { "ensure blurRadius in (0, 25] and scaleRatio >= 1" } // 计算图片缩小后的宽高 val width = originImage.width / scaleRatio val height = originImage.height / scaleRatio // 创建缩小的 Bitmap val bitmap = Bitmap.createScaledBitmap(originImage, width, height, false) // 创建 RenderScript 对象 val rs: RenderScript = RenderScript.create(context) // 创建一个带模糊效果的工具对象 val blur: ScriptIntrinsicBlur = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)) // 由于 RenderScript 没有使用 VM 来分配内存,所以需要使用 Allocation 类来创建和分配内存空间 val input: Allocation = Allocation.createFromBitmap(rs, bitmap) // 创建相同类型的 Allocation 对象用来输出 val output: Allocation = Allocation.createTyped(rs, input.getType()) // 设置渲染的模糊程度,最大为 25f blur.setRadius(blurRadius) // 设置输入和输出内存 blur.setInput(input) blur.forEach(output) // 将数据填充到 Bitmap output.copyTo(bitmap) // 销毁它们的内存 input.destroy() output.destroy() blur.destroy() rs.destroy() return bitmap } }
mit
4c0ee0e26e3f5a814996b696e1a34cea
31.586207
128
0.657491
3.478821
false
false
false
false
blademainer/intellij-community
platform/configuration-store-impl/src/SchemeManagerImpl.kt
4
28266
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.Disposable import com.intellij.openapi.application.AccessToken import com.intellij.openapi.application.WriteAction import com.intellij.openapi.application.ex.DecodeDefaultsUtil import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil.DEFAULT_EXT import com.intellij.openapi.components.service import com.intellij.openapi.extensions.AbstractExtensionPointBean import com.intellij.openapi.options.* import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.Condition import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtilRt import com.intellij.openapi.vfs.* import com.intellij.openapi.vfs.newvfs.NewVirtualFile import com.intellij.openapi.vfs.tracker.VirtualFileTracker import com.intellij.util.PathUtil import com.intellij.util.PathUtilRt import com.intellij.util.SmartList import com.intellij.util.ThrowableConvertor import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.URLUtil import com.intellij.util.text.UniqueNameGenerator import gnu.trove.THashMap import gnu.trove.THashSet import gnu.trove.TObjectObjectProcedure import gnu.trove.TObjectProcedure import org.jdom.Document import org.jdom.Element import java.io.File import java.io.IOException import java.io.InputStream import java.util.* public class SchemeManagerImpl<T : Scheme, E : ExternalizableScheme>(private val fileSpec: String, private val processor: SchemeProcessor<E>, private val provider: StreamProvider?, private val ioDirectory: File, private val roamingType: RoamingType = RoamingType.DEFAULT, virtualFileTrackerDisposable: Disposable? = null) : SchemesManager<T, E>(), SafeWriteRequestor { private val schemes = ArrayList<T>() private val readOnlyExternalizableSchemes = THashMap<String, E>() private var currentScheme: T? = null private var directory: VirtualFile? = null private val schemeExtension: String private val updateExtension: Boolean private val filesToDelete = THashSet<String>() // scheme could be changed - so, hashcode will be changed - we must use identity hashing strategy private val schemeToInfo = THashMap<E, ExternalInfo>(ContainerUtil.identityStrategy()) private val useVfs = virtualFileTrackerDisposable != null init { if (processor is SchemeExtensionProvider) { schemeExtension = processor.schemeExtension updateExtension = processor.isUpgradeNeeded } else { schemeExtension = FileStorageCoreUtil.DEFAULT_EXT updateExtension = false } if (useVfs && (provider == null || !provider.enabled)) { try { refreshVirtualDirectoryAndAddListener(virtualFileTrackerDisposable) } catch (e: Throwable) { LOG.error(e) } } } private fun refreshVirtualDirectoryAndAddListener(virtualFileTrackerDisposable: Disposable?) { // store refreshes root directory, so, we don't need to use refreshAndFindFile val directory = LocalFileSystem.getInstance().findFileByIoFile(ioDirectory) ?: return this.directory = directory directory.children if (directory is NewVirtualFile) { directory.markDirty() } directory.refresh(true, false, { addVfsListener(virtualFileTrackerDisposable) }) } private fun addVfsListener(virtualFileTrackerDisposable: Disposable?) { service<VirtualFileTracker>().addTracker("${LocalFileSystem.PROTOCOL_PREFIX}${ioDirectory.absolutePath.replace(File.separatorChar, '/')}", object : VirtualFileAdapter() { override fun contentsChanged(event: VirtualFileEvent) { if (event.requestor != null || !isMy(event)) { return } val oldScheme = findExternalizableSchemeByFileName(event.file.name) var oldCurrentScheme: T? = null if (oldScheme != null) { oldCurrentScheme = currentScheme @Suppress("UNCHECKED_CAST") removeScheme(oldScheme as T) processor.onSchemeDeleted(oldScheme) } val newScheme = readSchemeFromFile(event.file, false) if (newScheme != null) { processor.initScheme(newScheme) processor.onSchemeAdded(newScheme) updateCurrentScheme(oldCurrentScheme, newScheme) } } private fun updateCurrentScheme(oldCurrentScheme: T?, newCurrentScheme: E? = null) { if (oldCurrentScheme != currentScheme && currentScheme == null) { @Suppress("UNCHECKED_CAST") setCurrent(newCurrentScheme as T? ?: schemes.firstOrNull()) } } override fun fileCreated(event: VirtualFileEvent) { if (event.requestor != null) { return } if (event.file.isDirectory) { val dir = getDirectory() if (event.file == dir) { for (file in dir.children) { if (isMy(file)) { schemeCreatedExternally(file) } } } } else if (isMy(event)) { schemeCreatedExternally(event.file) } } private fun schemeCreatedExternally(file: VirtualFile) { val readScheme = readSchemeFromFile(file, false) if (readScheme != null) { processor.initScheme(readScheme) processor.onSchemeAdded(readScheme) } } override fun fileDeleted(event: VirtualFileEvent) { if (event.requestor != null) { return } var oldCurrentScheme = currentScheme if (event.file.isDirectory) { val dir = directory if (event.file == dir) { directory = null removeExternalizableSchemes() } } else if (isMy(event)) { val scheme = findExternalizableSchemeByFileName(event.file.name) ?: return @Suppress("UNCHECKED_CAST") removeScheme(scheme as T) processor.onSchemeDeleted(scheme) } updateCurrentScheme(oldCurrentScheme) } }, false, virtualFileTrackerDisposable!!) } override fun loadBundledScheme(resourceName: String, requestor: Any, convertor: ThrowableConvertor<Element, T, Throwable>) { try { val url = if (requestor is AbstractExtensionPointBean) requestor.loaderForClass.getResource(resourceName) else DecodeDefaultsUtil.getDefaults(requestor, resourceName) if (url == null) { LOG.error("Cannot read scheme from $resourceName") return } val element = JDOMUtil.load(URLUtil.openStream(url)) val scheme = convertor.convert(element) if (scheme is ExternalizableScheme) { val fileName = PathUtilRt.getFileName(url.path) val extension = getFileExtension(fileName, true) val info = ExternalInfo(fileName.substring(0, fileName.length() - extension.length()), extension) info.hash = JDOMUtil.getTreeHash(element, true) info.schemeName = scheme.name @Suppress("UNCHECKED_CAST") val oldInfo = schemeToInfo.put(scheme as E, info) LOG.assertTrue(oldInfo == null) val oldScheme = readOnlyExternalizableSchemes.put(scheme.name, scheme) if (oldScheme != null) { LOG.warn("Duplicated scheme ${scheme.name} - old: $oldScheme, new $scheme") } } schemes.add(scheme) } catch (e: Throwable) { LOG.error("Cannot read scheme from $resourceName", e) } } private fun getFileExtension(fileName: CharSequence, allowAny: Boolean): String { return if (StringUtilRt.endsWithIgnoreCase(fileName, schemeExtension)) { schemeExtension } else if (StringUtilRt.endsWithIgnoreCase(fileName, DEFAULT_EXT)) { DEFAULT_EXT } else if (allowAny) { PathUtil.getFileExtension(fileName.toString())!! } else { throw IllegalStateException("Scheme file extension $fileName is unknown, must be filtered out") } } private fun isMy(event: VirtualFileEvent) = isMy(event.file) private fun isMy(file: VirtualFile) = StringUtilRt.endsWithIgnoreCase(file.nameSequence, schemeExtension) override fun loadSchemes(): Collection<E> { val newSchemesOffset = schemes.size() if (provider != null && provider.enabled) { provider.processChildren(fileSpec, roamingType, { canRead(it) }) { name, input, readOnly -> val scheme = loadScheme(name, input, true) if (readOnly && scheme != null) { readOnlyExternalizableSchemes.put(scheme.name, scheme) } true } } else { ioDirectory.listFiles({ parent, name -> canRead(name) })?.let { for (file in it) { if (file.isDirectory) { continue } try { loadScheme(file.name, file.inputStream(), true) } catch (e: Throwable) { LOG.error("Cannot read scheme ${file.path}", e) } } } } val list = SmartList<E>() for (i in newSchemesOffset..schemes.size() - 1) { @Suppress("UNCHECKED_CAST") val scheme = schemes[i] as E processor.initScheme(scheme) list.add(scheme) } return list } public fun reload() { // we must not remove non-persistent (e.g. predefined) schemes, because we cannot load it (obviously) removeExternalizableSchemes() loadSchemes() } private fun removeExternalizableSchemes() { // todo check is bundled/read-only schemes correctly handled for (i in schemes.indices.reversed()) { val scheme = schemes.get(i) @Suppress("UNCHECKED_CAST") if (scheme is ExternalizableScheme && getState(scheme as E) != SchemeProcessor.State.NON_PERSISTENT) { if (scheme == currentScheme) { currentScheme = null } processor.onSchemeDeleted(scheme as E) } } retainExternalInfo(schemes) } private fun findExternalizableSchemeByFileName(fileName: String): E? { for (scheme in schemes) { @Suppress("UNCHECKED_CAST") if (scheme is ExternalizableScheme && fileName == "${scheme.fileName}$schemeExtension") { return scheme as E } } return null } private fun isOverwriteOnLoad(existingScheme: E): Boolean { if (readOnlyExternalizableSchemes.get(existingScheme.name) === existingScheme) { // so, bundled scheme is shadowed return true } val info = schemeToInfo.get(existingScheme) // scheme from file with old extension, so, we must ignore it return info != null && schemeExtension != info.fileExtension } private fun loadScheme(fileName: CharSequence, input: InputStream, duringLoad: Boolean): E? { try { val element = JDOMUtil.load(input) @Suppress("DEPRECATED_SYMBOL_WITH_MESSAGE", "UNCHECKED_CAST") val scheme = processor.readScheme(element, duringLoad) ?: return null val extension = getFileExtension(fileName, false) val fileNameWithoutExtension = fileName.subSequence(0, fileName.length() - extension.length()).toString() if (duringLoad) { if (filesToDelete.isNotEmpty() && filesToDelete.contains(fileName.toString())) { LOG.warn("Scheme file \"$fileName\" is not loaded because marked to delete") return null } val existingScheme = findSchemeByName(scheme.name) if (existingScheme != null) { @Suppress("UNCHECKED_CAST") if (existingScheme is ExternalizableScheme && isOverwriteOnLoad(existingScheme as E)) { removeScheme(existingScheme) } else { if (schemeExtension != extension && schemeToInfo.get(existingScheme)?.fileNameWithoutExtension == fileNameWithoutExtension) { // 1.oldExt is loading after 1.newExt - we should delete 1.oldExt filesToDelete.add(fileName.toString()) } else { // We don't load scheme with duplicated name - if we generate unique name for it, it will be saved then with new name. // It is not what all can expect. Such situation in most cases indicates error on previous level, so, we just warn about it. LOG.warn("Scheme file \"$fileName\" is not loaded because defines duplicated name \"${scheme.name}\"") } return null } } } var info: ExternalInfo? = schemeToInfo.get(scheme) if (info == null) { info = ExternalInfo(fileNameWithoutExtension, extension) schemeToInfo.put(scheme, info) } else { info.setFileNameWithoutExtension(fileNameWithoutExtension, extension) } info.hash = JDOMUtil.getTreeHash(element, true) info.schemeName = scheme.name @Suppress("UNCHECKED_CAST") if (duringLoad) { schemes.add(scheme as T) } else { addScheme(scheme as T) } return scheme } catch (e: Throwable) { LOG.error("Cannot read scheme $fileName", e) return null } } private val ExternalizableScheme.fileName: String? get() = schemeToInfo.get(this)?.fileNameWithoutExtension private fun canRead(name: CharSequence) = updateExtension && StringUtilRt.endsWithIgnoreCase(name, DEFAULT_EXT) || StringUtilRt.endsWithIgnoreCase(name, schemeExtension) private fun readSchemeFromFile(file: VirtualFile, duringLoad: Boolean): E? { val fileName = file.nameSequence if (file.isDirectory || !canRead(fileName)) { return null } try { return loadScheme(fileName, file.inputStream, duringLoad) } catch (e: Throwable) { LOG.error("Cannot read scheme $fileName", e) return null } } fun save(errors: MutableList<Throwable>) { var hasSchemes = false val nameGenerator = UniqueNameGenerator() val schemesToSave = SmartList<E>() for (scheme in schemes) { @Suppress("UNCHECKED_CAST") if (scheme is ExternalizableScheme) { val state = getState(scheme as E) if (state == SchemeProcessor.State.NON_PERSISTENT) { continue } hasSchemes = true if (state != SchemeProcessor.State.UNCHANGED) { schemesToSave.add(scheme) } val fileName = scheme.fileName if (fileName != null && !isRenamed(scheme)) { nameGenerator.addExistingName(fileName) } } } for (scheme in schemesToSave) { try { saveScheme(scheme, nameGenerator) } catch (e: Throwable) { errors.add(RuntimeException("Cannot save scheme $fileSpec/$scheme", e)) } } if (!filesToDelete.isEmpty) { deleteFiles(errors) // remove empty directory only if some file was deleted - avoid check on each save if (!hasSchemes && (provider == null || !provider.enabled)) { removeDirectoryIfEmpty(errors) } } } private fun removeDirectoryIfEmpty(errors: MutableList<Throwable>) { ioDirectory.listFiles()?.let { for (file in it) { if (!file.isHidden) { LOG.info("Directory ${ioDirectory.name} is not deleted: at least one file ${file.name} exists") return } } } LOG.info("Remove schemes directory ${ioDirectory.name}") directory = null var deleteUsingIo = !useVfs if (!deleteUsingIo) { val dir = getDirectory() if (dir != null) { val token = WriteAction.start() try { dir.delete(this) } catch (e: Throwable) { deleteUsingIo = true errors.add(e) } finally { token.finish() } } } if (deleteUsingIo) { errors.catch { FileUtil.delete(ioDirectory) } } } private fun getState(scheme: E) = processor.getState(scheme) private fun saveScheme(scheme: E, nameGenerator: UniqueNameGenerator) { var externalInfo: ExternalInfo? = schemeToInfo.get(scheme) val currentFileNameWithoutExtension = if (externalInfo == null) null else externalInfo.fileNameWithoutExtension val parent = processor.writeScheme(scheme) val element = if (parent == null || parent is Element) parent as Element? else (parent as Document).detachRootElement() if (JDOMUtil.isEmpty(element)) { externalInfo?.scheduleDelete() return } var fileNameWithoutExtension = currentFileNameWithoutExtension if (fileNameWithoutExtension == null || isRenamed(scheme)) { fileNameWithoutExtension = nameGenerator.generateUniqueName(FileUtil.sanitizeFileName(scheme.name, false)) } val newHash = JDOMUtil.getTreeHash(element!!, true) if (externalInfo != null && currentFileNameWithoutExtension === fileNameWithoutExtension && newHash == externalInfo.hash) { return } // save only if scheme differs from bundled val bundledScheme = readOnlyExternalizableSchemes.get(scheme.name) if (bundledScheme != null && schemeToInfo.get(bundledScheme)?.hash == newHash) { externalInfo?.scheduleDelete() return } val fileName = fileNameWithoutExtension!! + schemeExtension // file will be overwritten, so, we don't need to delete it filesToDelete.remove(fileName) // stream provider always use LF separator val byteOut = element.toBufferExposingByteArray() var providerPath: String? if (provider != null && provider.enabled) { providerPath = fileSpec + '/' + fileName if (!provider.isApplicable(providerPath, roamingType)) { providerPath = null } } else { providerPath = null } // if another new scheme uses old name of this scheme, so, we must not delete it (as part of rename operation) val renamed = externalInfo != null && fileNameWithoutExtension !== currentFileNameWithoutExtension && nameGenerator.value(currentFileNameWithoutExtension) if (providerPath == null) { if (useVfs) { var file: VirtualFile? = null var dir = getDirectory() if (dir == null || !dir.isValid) { dir = createDir(ioDirectory, this) directory = dir } if (renamed) { file = dir.findChild(externalInfo!!.fileName) if (file != null) { runWriteAction { file!!.rename(this, fileName) } } } if (file == null) { file = getFile(fileName, dir, this) } runWriteAction { file!!.getOutputStream(this).use { byteOut.writeTo(it) } } } else { if (renamed) { externalInfo!!.scheduleDelete() } FileUtil.writeToFile(File(ioDirectory, fileName), byteOut.internalBuffer, 0, byteOut.size()) } } else { if (renamed) { externalInfo!!.scheduleDelete() } provider!!.write(providerPath, byteOut.internalBuffer, byteOut.size(), roamingType) } if (externalInfo == null) { externalInfo = ExternalInfo(fileNameWithoutExtension, schemeExtension) schemeToInfo.put(scheme, externalInfo) } else { externalInfo.setFileNameWithoutExtension(fileNameWithoutExtension, schemeExtension) } externalInfo.hash = newHash externalInfo.schemeName = scheme.name } private fun ExternalInfo.scheduleDelete() { filesToDelete.add(fileName) } private fun isRenamed(scheme: ExternalizableScheme): Boolean { val info = schemeToInfo.get(scheme) return info != null && scheme.name != info.schemeName } private fun deleteFiles(errors: MutableList<Throwable>) { val deleteUsingIo: Boolean if (provider != null && provider.enabled) { deleteUsingIo = false for (name in filesToDelete) { errors.catch { val spec = "$fileSpec/$name" if (provider.isApplicable(spec, roamingType)) { provider.delete(spec, roamingType) } } } } else if (!useVfs) { deleteUsingIo = true } else { val dir = getDirectory() deleteUsingIo = dir == null if (!deleteUsingIo) { var token: AccessToken? = null try { for (file in dir!!.children) { if (filesToDelete.contains(file.name)) { if (token == null) { token = WriteAction.start() } errors.catch { file.delete(this) } } } } finally { if (token != null) { token.finish() } } } } if (deleteUsingIo) { for (name in filesToDelete) { errors.catch { FileUtil.delete(File(ioDirectory, name)) } } } filesToDelete.clear() } private fun getDirectory(): VirtualFile? { var result = directory if (result == null) { result = LocalFileSystem.getInstance().findFileByIoFile(ioDirectory) directory = result } return result } override fun getRootDirectory() = ioDirectory override fun setSchemes(newSchemes: List<T>, newCurrentScheme: T?, removeCondition: Condition<T>?) { val oldCurrentScheme = currentScheme if (removeCondition == null) { schemes.clear() } else { for (i in schemes.indices.reversed()) { if (removeCondition.value(schemes.get(i))) { schemes.remove(i) } } } retainExternalInfo(newSchemes) schemes.addAll(newSchemes) if (oldCurrentScheme != newCurrentScheme) { if (newCurrentScheme != null) { currentScheme = newCurrentScheme } else if (oldCurrentScheme != null && !schemes.contains(oldCurrentScheme)) { currentScheme = schemes.firstOrNull() } if (oldCurrentScheme != currentScheme) { processor.onCurrentSchemeChanged(oldCurrentScheme) } } } private fun retainExternalInfo(newSchemes: List<T>) { if (schemeToInfo.isEmpty) { return } schemeToInfo.retainEntries(object : TObjectObjectProcedure<E, ExternalInfo> { override fun execute(scheme: E, info: ExternalInfo): Boolean { if (readOnlyExternalizableSchemes.get(scheme.name) == scheme) { return true } for (t in newSchemes) { // by identity if (t === scheme) { if (filesToDelete.isNotEmpty()) { filesToDelete.remove("${info.fileName}") } return true } } info.scheduleDelete() return false } }) } override fun addNewScheme(scheme: T, replaceExisting: Boolean) { var toReplace = -1 for (i in schemes.indices) { val existing = schemes.get(i) if (existing.name == scheme.name) { if (!Comparing.equal<Class<out Scheme>>(existing.javaClass, scheme.javaClass)) { LOG.warn("'${scheme.name}' ${existing.javaClass.simpleName} replaced with ${scheme.javaClass.simpleName}") } toReplace = i if (replaceExisting && existing is ExternalizableScheme) { val oldInfo = schemeToInfo.remove(existing) if (oldInfo != null && scheme is ExternalizableScheme && !schemeToInfo.containsKey(scheme)) { @Suppress("UNCHECKED_CAST") schemeToInfo.put(scheme as E, oldInfo) } } break } } if (toReplace == -1) { schemes.add(scheme) } else if (replaceExisting || scheme !is ExternalizableScheme) { schemes.set(toReplace, scheme) } else { scheme.renameScheme(UniqueNameGenerator.generateUniqueName(scheme.name, collectExistingNames(schemes))) schemes.add(scheme) } if (scheme is ExternalizableScheme && filesToDelete.isNotEmpty()) { val info = schemeToInfo.get(scheme) if (info != null) { filesToDelete.remove("${info.fileName}") } } } private fun collectExistingNames(schemes: Collection<T>): Collection<String> { val result = THashSet<String>(schemes.size()) for (scheme in schemes) { result.add(scheme.name) } return result } override fun clearAllSchemes() { schemeToInfo.forEachValue(object : TObjectProcedure<ExternalInfo> { override fun execute(info: ExternalInfo): Boolean { info.scheduleDelete() return true } }) currentScheme = null schemes.clear() schemeToInfo.clear() } override fun getAllSchemes() = Collections.unmodifiableList(schemes) override fun findSchemeByName(schemeName: String): T? { for (scheme in schemes) { if (scheme.name == schemeName) { return scheme } } return null } override fun setCurrent(scheme: T?, notify: Boolean) { val oldCurrent = currentScheme currentScheme = scheme if (notify && oldCurrent != scheme) { processor.onCurrentSchemeChanged(oldCurrent) } } override fun getCurrentScheme() = currentScheme override fun removeScheme(scheme: T) { for (i in schemes.size() - 1 downTo 0) { val s = schemes.get(i) if (scheme.name == s.name) { if (currentScheme == s) { currentScheme = null } if (s is ExternalizableScheme) { schemeToInfo.remove(s)?.scheduleDelete() } schemes.remove(i) break } } } override fun getAllSchemeNames(): Collection<String> { if (schemes.isEmpty()) { return emptyList() } val names = ArrayList<String>(schemes.size()) for (scheme in schemes) { names.add(scheme.name) } return names } override fun isMetadataEditable(scheme: E) = !readOnlyExternalizableSchemes.containsKey(scheme.name) private class ExternalInfo(var fileNameWithoutExtension: String, var fileExtension: String?) { // we keep it to detect rename var schemeName: String? = null var hash = 0 val fileName: String get() = "$fileNameWithoutExtension$fileExtension" fun setFileNameWithoutExtension(nameWithoutExtension: String, extension: String) { fileNameWithoutExtension = nameWithoutExtension fileExtension = extension } override fun toString() = fileName } override fun toString() = fileSpec } private fun ExternalizableScheme.renameScheme(newName: String) { if (newName != name) { name = newName LOG.assertTrue(newName == name) } } private inline fun MutableList<Throwable>.catch(runnable: () -> Unit) { try { runnable() } catch (e: Throwable) { add(e) } } fun createDir(ioDir: File, requestor: Any): VirtualFile { ioDir.mkdirs() val parentFile = ioDir.getParent() val parentVirtualFile = (if (parentFile == null) null else VfsUtil.createDirectoryIfMissing(parentFile)) ?: throw IOException(ProjectBundle.message("project.configuration.save.file.not.found", parentFile)) return getFile(ioDir.name, parentVirtualFile, requestor) } fun getFile(fileName: String, parent: VirtualFile, requestor: Any): VirtualFile { val file = parent.findChild(fileName) if (file != null) { return file } return runWriteAction { parent.createChildData(requestor, fileName) } }
apache-2.0
3e107057ae584aad0a61302645914011
30.904063
207
0.640558
4.743413
false
false
false
false
Austin72/Charlatano
src/main/kotlin/com/charlatano/game/offsets/Offset.kt
1
2676
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.game.offsets import com.charlatano.utils.extensions.uint import com.sun.jna.Memory import com.sun.jna.Pointer import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap import org.jire.arrowhead.Addressed import org.jire.arrowhead.Module import kotlin.LazyThreadSafetyMode.NONE import kotlin.reflect.KProperty class Offset(val module: Module, val patternOffset: Long, val addressOffset: Long, val read: Boolean, val subtract: Boolean, val mask: ByteArray) : Addressed { companion object { val memoryByModule = Object2ObjectArrayMap<Module, Memory>() private fun Offset.cachedMemory(): Memory { var memory = memoryByModule[module] if (memory == null) { memory = module.read(0, module.size.toInt(), fromCache = false)!! memoryByModule.put(module, memory) } return memory } } val memory = cachedMemory() override val address by lazy(NONE) { val offset = module.size - mask.size var currentAddress = 0L while (currentAddress < offset) { if (memory.mask(currentAddress, mask)) { currentAddress += module.address + patternOffset if (read) currentAddress = module.process.uint(currentAddress) if (subtract) currentAddress -= module.address return@lazy currentAddress + addressOffset } currentAddress++ } throw IllegalStateException("Failed to resolve offset") } private var value = -1L operator fun getValue(thisRef: Any?, property: KProperty<*>): Long { if (value == -1L) value = address return value } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Long) { this.value = value } } fun Pointer.mask(offset: Long, mask: ByteArray, skipZero: Boolean = true): Boolean { for (i in 0..mask.lastIndex) { val value = mask[i] if (skipZero && 0 == value.toInt()) continue if (value != getByte(offset + i)) return false } return true }
agpl-3.0
e734decbcbf1114a2d196536cef18d27
29.770115
84
0.72571
3.721836
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/utils/LibraryUtils.kt
1
8045
package com.gmail.blueboxware.libgdxplugin.utils import com.gmail.blueboxware.libgdxplugin.versions.VersionService import com.gmail.blueboxware.libgdxplugin.message import com.gmail.blueboxware.libgdxplugin.versions.Libraries import com.gmail.blueboxware.libgdxplugin.versions.libs.LibGDXLibrary import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.components.service import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.Library import com.intellij.psi.PsiElement import org.jetbrains.kotlin.config.MavenComparableVersion import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.kotlin.psi.KtValueArgumentList import org.jetbrains.kotlin.psi.psiUtil.plainContent import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCommandArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral /* * Copyright 2018 Blue Box Ware * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ internal fun checkVersionAndReport( holder: ProblemsHolder, element: PsiElement, lib: Libraries, version: MavenComparableVersion? ) { val versionManager = holder.project.service<VersionService>() val latestVersion = versionManager.getLatestVersion(lib) ?: return val usedVersion = version ?: run { if (lib.library is LibGDXLibrary) { versionManager.getUsedVersion(Libraries.LIBGDX) } else { versionManager.getUsedVersion(lib) } } ?: return if (usedVersion < latestVersion) { holder.registerProblem( element, message("outdated.version.inspection.msg", lib.library.name, latestVersion) ) } } internal fun getLibraryInfoFromIdeaLibrary(library: Library): Pair<Libraries, MavenComparableVersion>? { if ((library as? LibraryEx)?.isDisposed == true) { return null } for (libGDXLib in Libraries.values()) { for (url in library.getUrls(OrderRootType.CLASSES)) { libGDXLib.getVersionFromIdeaLibrary(library)?.let { version -> return Pair(libGDXLib, version) } } } return null } internal fun getLibraryFromExtKey(extKey: String): Libraries? = Libraries.values().find { it.library.extKeys?.contains(extKey) == true } internal fun getLibraryFromGroovyLiteral(grLiteral: GrLiteral): Libraries? = grLiteral.asString()?.let(::getLibraryFromMavenCoordString) internal fun getLibraryInfoFromGroovyLiteral(grLiteral: GrLiteral): Pair<Libraries, MavenComparableVersion?>? = getLibraryFromGroovyLiteral(grLiteral)?.let { lib -> grLiteral.asString()?.let { string -> lib.getVersionFromMavenCoordString(string).let { version -> lib to version } } } internal fun getLibraryFromGroovyArgumentList(groovyCommandArgumentList: GrCommandArgumentList): Libraries? { val groupArgument = (groovyCommandArgumentList.getNamedArgument("group") as? GrLiteral)?.asString()?.let(::trimQuotes) ?: return null val nameArgument = (groovyCommandArgumentList.getNamedArgument("name") as? GrLiteral)?.asString()?.let(::trimQuotes) ?: return null return Libraries.values().find { it.library.groupId == groupArgument && it.library.artifactId == nameArgument } } internal fun getLibraryFromKotlinArgumentList(ktValueArgumentList: KtValueArgumentList): Libraries? { val groupArgument = ktValueArgumentList.getNamedArgumentPlainContent("group") ?: return null val nameArgument = ktValueArgumentList.getNamedArgumentPlainContent("name") ?: return null return Libraries.values().find { it.library.groupId == groupArgument && it.library.artifactId == nameArgument } } internal fun getLibraryInfoFromGroovyArgumentList(groovyCommandArgumentList: GrCommandArgumentList): Pair<Libraries, MavenComparableVersion?>? = getLibraryFromGroovyArgumentList(groovyCommandArgumentList)?.let { it to getVersionFromGroovyArgumentList(groovyCommandArgumentList) } internal fun getLibraryInfoFromKotlinArgumentList(ktValueArgumentList: KtValueArgumentList): Pair<Libraries, MavenComparableVersion?>? = getLibraryFromKotlinArgumentList(ktValueArgumentList)?.let { it to getVersionFromKotlinArgumentList(ktValueArgumentList) } internal fun getLibraryInfoFromGroovyAssignment(grAssignmentExpression: GrAssignmentExpression): Pair<Libraries, MavenComparableVersion?>? = grAssignmentExpression.lValue.text?.let { extKey -> getLibraryFromExtKey(extKey)?.let { lib -> getVersionFromGroovyAssignment(grAssignmentExpression).let { version -> lib to version } } } internal fun getLibraryFromKotlinString(ktStringTemplateExpression: KtStringTemplateExpression): Libraries? = getLibraryFromMavenCoordString(ktStringTemplateExpression.plainContent) internal fun getLibraryInfoFromKotlinString(ktStringTemplateExpression: KtStringTemplateExpression): Pair<Libraries, MavenComparableVersion?>? = ktStringTemplateExpression.plainContent.let { str -> getLibraryFromKotlinString(ktStringTemplateExpression)?.let { lib -> lib.getVersionFromMavenCoordString(str).let { version -> lib to version } } } internal fun Libraries.getVersionFromMavenCoordString(str: String): MavenComparableVersion? = Regex("""${library.groupId}:${library.artifactId}:([^$:@"']+\.[^$:@"']+).*""").let { regex -> regex.matchEntire(str)?.let { matchResult -> matchResult.groupValues.getOrNull(1)?.toVersion() } } internal fun Libraries.getVersionFromIdeaLibrary(ideaLibrary: Library): MavenComparableVersion? { val regex = Regex("""[/\\]${library.groupId}[/\\]${library.artifactId}[/\\]([^/]+\.[^/]+)/""") for (url in ideaLibrary.getUrls(OrderRootType.CLASSES)) { regex.find(url)?.let { matchResult -> matchResult.groupValues.getOrNull(1)?.let { versionString -> return versionString.toVersion() } } } return null } internal fun getVersionFromGroovyAssignment(grAssignmentExpression: GrAssignmentExpression): MavenComparableVersion? = (grAssignmentExpression.rValue as? GrLiteral)?.asString()?.let(::trimQuotes)?.let { MavenComparableVersion(it) } private fun getLibraryFromMavenCoordString(str: String): Libraries? = Libraries.values().find { lib -> Regex("""${lib.library.groupId}:${lib.library.artifactId}($|:.*)""").matches(str) } private fun getVersionFromGroovyArgumentList(groovyCommandArgumentList: GrCommandArgumentList): MavenComparableVersion? = (groovyCommandArgumentList.getNamedArgument("version") as? GrLiteral)?.asString()?.toVersion() private fun getVersionFromKotlinArgumentList(ktValueArgumentList: KtValueArgumentList): MavenComparableVersion? = ktValueArgumentList.getNamedArgumentPlainContent("version")?.let(::MavenComparableVersion) private fun KtValueArgumentList.getNamedArgumentPlainContent(name: String): String? = (getNamedArgument(name) as? KtStringTemplateExpression)?.plainContent private fun String.toVersion() = takeIf { contains('.') && !any { char -> char in listOf('$', '"', '\'') } }?.let(::MavenComparableVersion)
apache-2.0
361d56a02b2b383b45315dcfdf3acf98
39.631313
144
0.735488
4.800119
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/utils/SuppressionUtils.kt
1
5228
package com.gmail.blueboxware.libgdxplugin.filetypes.skin.utils import com.gmail.blueboxware.libgdxplugin.filetypes.skin.LibGDXSkinLanguage import com.gmail.blueboxware.libgdxplugin.filetypes.skin.SkinElementTypes import com.gmail.blueboxware.libgdxplugin.filetypes.skin.SkinParserDefinition import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.* import com.gmail.blueboxware.libgdxplugin.message import com.gmail.blueboxware.libgdxplugin.utils.firstParent import com.gmail.blueboxware.libgdxplugin.utils.isLeaf import com.gmail.blueboxware.libgdxplugin.utils.isPrecededByNewline import com.intellij.codeInspection.ContainerBasedSuppressQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.SuppressionUtil import com.intellij.codeInspection.SuppressionUtil.isSuppressionComment import com.intellij.openapi.project.Project import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace /* * Copyright 2019 Blue Box Ware * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ val INSPECTION_NAMES = listOf( "SkinDuplicateProperty", "SkinDuplicateResourceName", "SkinMalformedColorString", "SkinMissingProperty", "SkinNonExistingClass", "SkinNonExistingField", "SkinNonExistingFontFile", "SkinNonExistingResourceAlias", "SkinNonExistingInspection", "SkinType", "SkinAbbrClass", "SkinDeprecated", "SkinSpellCheckingInspection" ) fun SkinElement.isSuppressed(id: String): Boolean { if (this is SkinFile) { children.forEach { child -> if ((child as? PsiComment)?.isSuppressionComment(id) == true) { return true } else if (child.isLeaf(SkinElementTypes.L_CURLY)) { return false } } } if ((parent as? SkinElement)?.isSuppressed(id) == true) { return true } if (this is SkinResources) { return false } var prev: PsiElement? = prevSibling if (prev == null && this is SkinResource) { prev = parent?.prevSibling } while (prev is PsiWhiteSpace || prev?.node?.elementType in SkinParserDefinition.SKIN_COMMENTARIES) { (prev as? PsiComment)?.let { comment -> if (comment.isSuppressionComment(id)) { return true } } prev = prev?.prevSibling } return false } private fun PsiComment.isSuppressionComment(id: String) = isSuppressionComment(this) && SuppressionUtil.isInspectionToolIdMentioned(text, id) abstract class SuppressFix(val id: String) : ContainerBasedSuppressQuickFix { override fun getName(): String = familyName override fun isSuppressAll(): Boolean = false override fun isAvailable(project: Project, context: PsiElement): Boolean = context.isValid && getContainer(context) != null override fun applyFix(project: Project, descriptor: ProblemDescriptor) { getContainer(descriptor.psiElement)?.let { container -> if (!container.isPrecededByNewline()) { SkinElementFactory(project).createNewLine()?.let { newline -> container.parent.addBefore(newline, container) } } SuppressionUtil.createSuppression(project, container, id, LibGDXSkinLanguage.INSTANCE) SkinElementFactory(project).createNewLine()?.let { newline -> container.parent.addBefore(newline, container) } } } } class SuppressForObjectFix(id: String) : SuppressFix(id) { override fun getFamilyName(): String = message("suppress.object") override fun getContainer(context: PsiElement?): PsiElement? = context?.firstParent(true) { it is SkinClassSpecification || it is SkinObject } } class SuppressForPropertyFix(id: String) : SuppressFix(id) { override fun getFamilyName(): String = message("suppress.property") override fun getContainer(context: PsiElement?): PsiElement? = context?.firstParent<SkinProperty>() } class SuppressForFileFix(id: String) : SuppressFix(id) { override fun getContainer(context: PsiElement?) = context?.containingFile as? SkinFile override fun getFamilyName(): String = message("suppress.file") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { (descriptor.psiElement.containingFile as? SkinFile)?.firstChild?.let { firstChild -> SkinElementFactory(project).createNewLine()?.let { newline -> SuppressionUtil.createSuppression(project, firstChild, id, LibGDXSkinLanguage.INSTANCE) firstChild.parent.addBefore(newline, firstChild) } } } }
apache-2.0
1b29013f0557c12b4ebfb023d692771f
33.622517
104
0.708875
4.655387
false
false
false
false
Zubnix/westmalle
compositor/src/main/kotlin/org/westford/launch/indirect/NativeConstants.kt
3
361
package org.westford.launch.indirect object NativeConstants { val OPCODE_WESTMALLE_LAUNCHER_OPEN = 0 val EVENT_WESTMALLE_LAUNCHER_SUCCESS = 0 val EVENT_WESTMALLE_LAUNCHER_ACTIVATE = 1 val EVENT_WESTMALLE_LAUNCHER_DEACTIVATE = 2 val ENV_WESTFORD_TTY_FD = "WESTFORD_TTY_FD" val ENV_WESTFORD_LAUNCHER_SOCK = "WESTFORD_LAUNCHER_SOCK" }
apache-2.0
c3458e1af70dad0da2871c76e8d656b5
24.785714
61
0.734072
3.13913
false
false
false
false
Zubnix/westmalle
launch.x11/src/main/kotlin/org/westford/compositor/launch/x11/Launcher.kt
3
2893
/* * Westford Wayland Compositor. * Copyright (C) 2016 Erik De Rijcke * * 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 org.westford.compositor.launch.x11 import org.westford.compositor.x11.X11PlatformModule import java.io.IOException import java.util.logging.FileHandler import java.util.logging.Logger import java.util.logging.SimpleFormatter class Launcher { private fun launch(builder: DaggerX11EglCompositor.Builder) { /* * Inject X11 config. */ val x11EglCompositor = builder.x11PlatformModule(X11PlatformModule(X11PlatformConfigSimple())).build() /* * Keep this first as weston demo clients *really* like their globals * to be initialized in a certain order, else they segfault... */ val lifeCycle = x11EglCompositor.lifeCycle() /*Get the seat that listens for input on the X connection and passes it on to a wayland seat. */ val wlSeat = x11EglCompositor.wlSeat() /* * Setup keyboard focus tracking to follow mouse pointer. */ val wlKeyboard = wlSeat.wlKeyboard val pointerDevice = wlSeat.wlPointer.pointerDevice pointerDevice.pointerFocusSignal.connect { wlKeyboard.keyboardDevice.setFocus(wlKeyboard.resources, pointerDevice.focus?.wlSurfaceResource) } /* * Start the compositor. */ lifeCycle.start() } companion object { private val LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) @Throws(IOException::class) @JvmStatic fun main(args: Array<String>) { configureLogger() LOGGER.info("Starting Westford") Launcher().launch(DaggerX11EglCompositor.builder()) } @Throws(IOException::class) private fun configureLogger() { val fileHandler = FileHandler("westford.log") fileHandler.formatter = SimpleFormatter() LOGGER.addHandler(fileHandler) Thread.setDefaultUncaughtExceptionHandler { _, throwable -> LOGGER.severe("Got uncaught exception " + throwable.message) throwable.printStackTrace() } } } }
apache-2.0
4f62936ff03424a5ae918a7b4bc2d20b
34.292683
110
0.66056
4.727124
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/support/delegates/DependencyConstraintHandlerDelegate.kt
3
2201
/* * Copyright 2019 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.support.delegates import org.gradle.api.Action import org.gradle.api.artifacts.DependencyConstraint import org.gradle.api.artifacts.dsl.DependencyConstraintHandler /** * Facilitates the implementation of the [DependencyConstraintHandler] interface by delegation via subclassing. * * See [GradleDelegate] for why this is currently necessary. */ abstract class DependencyConstraintHandlerDelegate : DependencyConstraintHandler { internal abstract val delegate: DependencyConstraintHandler override fun add(configurationName: String, dependencyConstraintNotation: Any): DependencyConstraint = delegate.add(configurationName, dependencyConstraintNotation) override fun add(configurationName: String, dependencyNotation: Any, configureAction: Action<in DependencyConstraint>): DependencyConstraint = delegate.add(configurationName, dependencyNotation, configureAction) override fun create(dependencyConstraintNotation: Any): DependencyConstraint = delegate.create(dependencyConstraintNotation) override fun create(dependencyConstraintNotation: Any, configureAction: Action<in DependencyConstraint>): DependencyConstraint = delegate.create(dependencyConstraintNotation, configureAction) override fun enforcedPlatform(notation: Any): DependencyConstraint = delegate.enforcedPlatform(notation) override fun enforcedPlatform(notation: Any, configureAction: Action<in DependencyConstraint>): DependencyConstraint = delegate.enforcedPlatform(notation, configureAction) }
apache-2.0
bb3b4d463c207c4da14059900ee08927
42.156863
146
0.789187
5.394608
false
true
false
false
gradle/gradle
build-logic/basics/src/main/kotlin/gradlebuild/basics/BuildParams.kt
2
15720
/* * Copyright 2021 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 gradlebuild.basics import gradlebuild.basics.BuildParams.AUTO_DOWNLOAD_ANDROID_STUDIO import gradlebuild.basics.BuildParams.BUILD_BRANCH import gradlebuild.basics.BuildParams.BUILD_COMMIT_DISTRIBUTION import gradlebuild.basics.BuildParams.BUILD_COMMIT_ID import gradlebuild.basics.BuildParams.BUILD_CONFIGURATION_ID import gradlebuild.basics.BuildParams.BUILD_FINAL_RELEASE import gradlebuild.basics.BuildParams.BUILD_ID import gradlebuild.basics.BuildParams.BUILD_IGNORE_INCOMING_BUILD_RECEIPT import gradlebuild.basics.BuildParams.BUILD_MILESTONE_NUMBER import gradlebuild.basics.BuildParams.BUILD_PROMOTION_COMMIT_ID import gradlebuild.basics.BuildParams.BUILD_RC_NUMBER import gradlebuild.basics.BuildParams.BUILD_SERVER_URL import gradlebuild.basics.BuildParams.BUILD_TIMESTAMP import gradlebuild.basics.BuildParams.BUILD_VCS_NUMBER import gradlebuild.basics.BuildParams.BUILD_VERSION_QUALIFIER import gradlebuild.basics.BuildParams.CI_ENVIRONMENT_VARIABLE import gradlebuild.basics.BuildParams.DEFAULT_PERFORMANCE_BASELINES import gradlebuild.basics.BuildParams.ENABLE_CONFIGURATION_CACHE_FOR_DOCS_TESTS import gradlebuild.basics.BuildParams.FLAKY_TEST import gradlebuild.basics.BuildParams.GRADLE_INSTALL_PATH import gradlebuild.basics.BuildParams.INCLUDE_PERFORMANCE_TEST_SCENARIOS import gradlebuild.basics.BuildParams.MAX_PARALLEL_FORKS import gradlebuild.basics.BuildParams.PERFORMANCE_BASELINES import gradlebuild.basics.BuildParams.PERFORMANCE_DB_PASSWORD import gradlebuild.basics.BuildParams.PERFORMANCE_DB_PASSWORD_ENV import gradlebuild.basics.BuildParams.PERFORMANCE_DB_URL import gradlebuild.basics.BuildParams.PERFORMANCE_DB_USERNAME import gradlebuild.basics.BuildParams.PERFORMANCE_DEPENDENCY_BUILD_IDS import gradlebuild.basics.BuildParams.PERFORMANCE_MAX_PROJECTS import gradlebuild.basics.BuildParams.PERFORMANCE_TEST_VERBOSE import gradlebuild.basics.BuildParams.PREDICTIVE_TEST_SELECTION_ENABLED import gradlebuild.basics.BuildParams.RERUN_ALL_TESTS import gradlebuild.basics.BuildParams.RUN_ANDROID_STUDIO_IN_HEADLESS_MODE import gradlebuild.basics.BuildParams.RUN_BROKEN_CONFIGURATION_CACHE_DOCS_TESTS import gradlebuild.basics.BuildParams.STUDIO_HOME import gradlebuild.basics.BuildParams.TEST_DISTRIBUTION_ENABLED import gradlebuild.basics.BuildParams.TEST_DISTRIBUTION_PARTITION_SIZE import gradlebuild.basics.BuildParams.TEST_JAVA_VENDOR import gradlebuild.basics.BuildParams.TEST_JAVA_VERSION import gradlebuild.basics.BuildParams.TEST_SPLIT_EXCLUDE_TEST_CLASSES import gradlebuild.basics.BuildParams.TEST_SPLIT_INCLUDE_TEST_CLASSES import gradlebuild.basics.BuildParams.TEST_SPLIT_ONLY_TEST_GRADLE_VERSION import gradlebuild.basics.BuildParams.VENDOR_MAPPING import org.gradle.api.JavaVersion import org.gradle.api.Project import org.gradle.api.provider.Provider import org.gradle.jvm.toolchain.JvmVendorSpec import org.jetbrains.kotlin.util.capitalizeDecapitalize.toUpperCaseAsciiOnly enum class FlakyTestStrategy { INCLUDE, EXCLUDE, ONLY } object BuildParams { const val BUILD_BRANCH = "BUILD_BRANCH" const val BUILD_COMMIT_ID = "BUILD_COMMIT_ID" const val BUILD_COMMIT_DISTRIBUTION = "buildCommitDistribution" const val BUILD_CONFIGURATION_ID = "BUILD_TYPE_ID" const val BUILD_FINAL_RELEASE = "finalRelease" const val BUILD_ID = "BUILD_ID" const val BUILD_IGNORE_INCOMING_BUILD_RECEIPT = "ignoreIncomingBuildReceipt" const val BUILD_MILESTONE_NUMBER = "milestoneNumber" const val BUILD_PROMOTION_COMMIT_ID = "promotionCommitId" const val BUILD_RC_NUMBER = "rcNumber" const val BUILD_SERVER_URL = "BUILD_SERVER_URL" const val BUILD_TIMESTAMP = "buildTimestamp" const val BUILD_VCS_NUMBER = "BUILD_VCS_NUMBER" const val BUILD_VERSION_QUALIFIER = "versionQualifier" const val CI_ENVIRONMENT_VARIABLE = "CI" const val DEFAULT_PERFORMANCE_BASELINES = "defaultPerformanceBaselines" const val GRADLE_INSTALL_PATH = "gradle_installPath" /** * Specify the flaky test quarantine strategy: * * -PflakyTests=include: run all tests, including flaky tests. * -PflakyTests=exclude: run all tests, excluding flaky tests. * -PflakyTests=only: run flaky tests only. * * Default value (if absent) is "include". */ const val FLAKY_TEST = "flakyTests" const val INCLUDE_PERFORMANCE_TEST_SCENARIOS = "includePerformanceTestScenarios" const val MAX_PARALLEL_FORKS = "maxParallelForks" const val PERFORMANCE_BASELINES = "performanceBaselines" const val PERFORMANCE_TEST_VERBOSE = "performanceTest.verbose" const val PERFORMANCE_DB_PASSWORD = "org.gradle.performance.db.password" const val PERFORMANCE_DB_PASSWORD_ENV = "PERFORMANCE_DB_PASSWORD_TCAGENT" const val PERFORMANCE_DB_URL = "org.gradle.performance.db.url" const val PERFORMANCE_DB_USERNAME = "org.gradle.performance.db.username" const val PERFORMANCE_DEPENDENCY_BUILD_IDS = "org.gradle.performance.dependencyBuildIds" const val PERFORMANCE_MAX_PROJECTS = "maxProjects" const val RERUN_ALL_TESTS = "rerunAllTests" const val PREDICTIVE_TEST_SELECTION_ENABLED = "enablePredictiveTestSelection" const val TEST_DISTRIBUTION_ENABLED = "enableTestDistribution" const val TEST_DISTRIBUTION_PARTITION_SIZE = "testDistributionPartitionSizeInSeconds" const val TEST_SPLIT_INCLUDE_TEST_CLASSES = "includeTestClasses" const val TEST_SPLIT_EXCLUDE_TEST_CLASSES = "excludeTestClasses" const val TEST_SPLIT_ONLY_TEST_GRADLE_VERSION = "onlyTestGradleVersion" const val TEST_JAVA_VENDOR = "testJavaVendor" const val TEST_JAVA_VERSION = "testJavaVersion" const val AUTO_DOWNLOAD_ANDROID_STUDIO = "autoDownloadAndroidStudio" const val RUN_ANDROID_STUDIO_IN_HEADLESS_MODE = "runAndroidStudioInHeadlessMode" const val STUDIO_HOME = "studioHome" /** * Run docs tests with the configuration cache enabled. */ const val ENABLE_CONFIGURATION_CACHE_FOR_DOCS_TESTS = "enableConfigurationCacheForDocsTests" /** * Run docs tests that are knowingly broken when running with the configuration cache enabled. Only applied when #ENABLE_CONFIGURATION_CACHE_FOR_DOCS_TESTS is also set. */ const val RUN_BROKEN_CONFIGURATION_CACHE_DOCS_TESTS = "runBrokenConfigurationCacheDocsTests" internal val VENDOR_MAPPING = mapOf( "oracle" to JvmVendorSpec.ORACLE, "openjdk" to JvmVendorSpec.ADOPTIUM, "zulu" to JvmVendorSpec.AZUL ) } fun Project.stringPropertyOrEmpty(projectPropertyName: String): String = stringPropertyOrNull(projectPropertyName) ?: "" fun Project.stringPropertyOrNull(projectPropertyName: String): String? = gradleProperty(projectPropertyName).orNull fun Project.selectStringProperties(vararg propertyNames: String): Map<String, String> = propertyNames.mapNotNull { propertyName -> stringPropertyOrNull(propertyName)?.let { propertyValue -> propertyName to propertyValue } }.toMap() /** * Creates a [Provider] that returns `true` when this [Provider] has a value * and `false` otherwise. The returned [Provider] always has a value. * @see Provider.isPresent */ private fun <T> Provider<T>.presence(): Provider<Boolean> = map { true }.orElse(false) fun Project.gradleProperty(propertyName: String) = providers.gradleProperty(propertyName) fun Project.systemProperty(propertyName: String) = providers.systemProperty(propertyName) fun Project.environmentVariable(propertyName: String) = providers.environmentVariable(propertyName) fun Project.propertyFromAnySource(propertyName: String) = gradleProperty(propertyName) .orElse(systemProperty(propertyName)) .orElse(environmentVariable(propertyName)) val Project.buildBranch: Provider<String> get() = environmentVariable(BUILD_BRANCH).orElse(currentGitBranchViaFileSystemQuery()) /** * The logical branch. * For non-pre-tested commit branches this is the same as {@link #buildBranch}. * For pre-tested commit branches, this is the branch which will be forwarded to the state on this branch when * pre-tested commit passes. * * For example, for the pre-tested commit branch "pre-test/master/queue/alice/personal-branch" the logical branch is "master". */ val Project.logicalBranch: Provider<String> get() = buildBranch.map(::toPreTestedCommitBaseBranch) val Project.buildCommitId: Provider<String> get() = environmentVariable(BUILD_COMMIT_ID) .orElse(gradleProperty(BUILD_PROMOTION_COMMIT_ID)) .orElse(environmentVariable(BUILD_VCS_NUMBER)) .orElse(currentGitCommitViaFileSystemQuery()) val Project.isBuildCommitDistribution: Boolean get() = gradleProperty(BUILD_COMMIT_DISTRIBUTION).map { it.toBoolean() }.orElse(false).get() val Project.buildConfigurationId: Provider<String> get() = environmentVariable(BUILD_CONFIGURATION_ID) val Project.buildFinalRelease: Provider<String> get() = gradleProperty(BUILD_FINAL_RELEASE) val Project.buildId: Provider<String> get() = environmentVariable(BUILD_ID) val Project.buildRcNumber: Provider<String> get() = gradleProperty(BUILD_RC_NUMBER) val Project.buildRunningOnCi: Provider<Boolean> get() = environmentVariable(CI_ENVIRONMENT_VARIABLE).presence() val Project.buildServerUrl: Provider<String> get() = environmentVariable(BUILD_SERVER_URL) val Project.buildMilestoneNumber: Provider<String> get() = gradleProperty(BUILD_MILESTONE_NUMBER) val Project.buildTimestamp: Provider<String> get() = gradleProperty(BUILD_TIMESTAMP) val Project.buildVersionQualifier: Provider<String> get() = gradleProperty(BUILD_VERSION_QUALIFIER) val Project.defaultPerformanceBaselines: Provider<String> get() = gradleProperty(DEFAULT_PERFORMANCE_BASELINES) val Project.flakyTestStrategy: FlakyTestStrategy get() = gradleProperty(FLAKY_TEST).let { if (it.getOrElse("").isEmpty()) { return FlakyTestStrategy.INCLUDE } else { return FlakyTestStrategy.valueOf(it.get().toUpperCaseAsciiOnly()) } } val Project.ignoreIncomingBuildReceipt: Provider<Boolean> get() = gradleProperty(BUILD_IGNORE_INCOMING_BUILD_RECEIPT).presence() val Project.performanceDependencyBuildIds: Provider<String> get() = gradleProperty(PERFORMANCE_DEPENDENCY_BUILD_IDS).orElse("") val Project.performanceBaselines: String? get() = stringPropertyOrNull(PERFORMANCE_BASELINES) val Project.performanceDbPassword: Provider<String> get() = environmentVariable(PERFORMANCE_DB_PASSWORD_ENV) val Project.performanceTestVerbose: Provider<String> get() = gradleProperty(PERFORMANCE_TEST_VERBOSE) val Project.propertiesForPerformanceDb: Map<String, String> get() { return if (performanceDbPassword.isPresent) { selectStringProperties( PERFORMANCE_DB_URL, PERFORMANCE_DB_USERNAME ) + (PERFORMANCE_DB_PASSWORD to performanceDbPassword.get()) } else { selectStringProperties( PERFORMANCE_DB_URL, PERFORMANCE_DB_USERNAME, PERFORMANCE_DB_PASSWORD ) } } val Project.performanceGeneratorMaxProjects: Int? get() = gradleProperty(PERFORMANCE_MAX_PROJECTS).map { it.toInt() }.orNull val Project.includePerformanceTestScenarios: Boolean get() = gradleProperty(INCLUDE_PERFORMANCE_TEST_SCENARIOS).getOrElse("false") == "true" val Project.gradleInstallPath: Provider<String> get() = gradleProperty(GRADLE_INSTALL_PATH).orElse( provider<String> { throw RuntimeException("You can't install without setting the $GRADLE_INSTALL_PATH property.") } ) val Project.rerunAllTests: Provider<Boolean> get() = gradleProperty(RERUN_ALL_TESTS).map { true }.orElse(false) val Project.testJavaVendor: Provider<JvmVendorSpec> get() = propertyFromAnySource(TEST_JAVA_VENDOR).map { vendorName -> VENDOR_MAPPING.getOrElse(vendorName) { -> JvmVendorSpec.matching(vendorName) } } val Project.testJavaVersion: String get() = propertyFromAnySource(TEST_JAVA_VERSION).getOrElse(JavaVersion.current().majorVersion) val Project.testSplitIncludeTestClasses: String get() = project.stringPropertyOrEmpty(TEST_SPLIT_INCLUDE_TEST_CLASSES) val Project.testSplitExcludeTestClasses: String get() = project.stringPropertyOrEmpty(TEST_SPLIT_EXCLUDE_TEST_CLASSES) val Project.testSplitOnlyTestGradleVersion: String get() = project.stringPropertyOrEmpty(TEST_SPLIT_ONLY_TEST_GRADLE_VERSION) val Project.predictiveTestSelectionEnabled: Provider<Boolean> get() = systemProperty(PREDICTIVE_TEST_SELECTION_ENABLED) .map { it.toBoolean() } .orElse( buildBranch.zip(buildRunningOnCi) { branch, ci -> val protectedBranches = listOf("master", "release") ci && !protectedBranches.contains(branch) && !branch.startsWith("pre-test/") } ).zip(project.rerunAllTests) { enabled, rerunAllTests -> enabled && !rerunAllTests } val Project.testDistributionEnabled: Boolean get() = systemProperty(TEST_DISTRIBUTION_ENABLED).orNull?.toBoolean() == true // Controls the test distribution partition size. The test classes smaller than this value will be merged into a "partition" val Project.maxTestDistributionPartitionSecond: Long? get() = systemProperty(TEST_DISTRIBUTION_PARTITION_SIZE).orNull?.toLong() val Project.maxParallelForks: Int get() = gradleProperty(MAX_PARALLEL_FORKS).getOrElse("4").toInt() * environmentVariable("BUILD_AGENT_VARIANT").getOrElse("").let { if (it == "AX41") 2 else 1 } val Project.autoDownloadAndroidStudio: Boolean get() = propertyFromAnySource(AUTO_DOWNLOAD_ANDROID_STUDIO).getOrElse("false").toBoolean() val Project.runAndroidStudioInHeadlessMode: Boolean get() = propertyFromAnySource(RUN_ANDROID_STUDIO_IN_HEADLESS_MODE).getOrElse("false").toBoolean() val Project.androidStudioHome: Provider<String> get() = propertyFromAnySource(STUDIO_HOME) /** * If set to `true`, run docs tests with the configuration cache enabled. */ val Project.configurationCacheEnabledForDocsTests: Boolean @JvmName("isConfigurationCacheEnabledForDocsTests") get() = gradleProperty(ENABLE_CONFIGURATION_CACHE_FOR_DOCS_TESTS).orNull.toBoolean() /** * If set to `true`, run docs tests that are knowingly broken when running with the configuration cache enabled. Only applied when #configurationCacheEnabledForDocsTests is also set. */ val Project.runBrokenForConfigurationCacheDocsTests: Boolean @JvmName("shouldRunBrokenForConfigurationCacheDocsTests") get() = gradleProperty(RUN_BROKEN_CONFIGURATION_CACHE_DOCS_TESTS).orNull.toBoolean() /** * Is a promotion build task called? */ val Project.isPromotionBuild: Boolean get() { val taskNames = gradle.startParameter.taskNames return taskNames.contains("promotionBuild") || // :updateReleasedVersionsToLatestNightly and :updateReleasedVersions taskNames.any { it.contains("updateReleasedVersions") } }
apache-2.0
a0f669a98d235800f09d4cb07629ff49
38.201995
182
0.762913
4.121657
false
true
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/codegen/backend/TypeToDataTypeDescriptor.kt
1
8345
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.codegen.backend import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptor import com.google.android.libraries.pcc.chronicle.api.FieldType import com.google.android.libraries.pcc.chronicle.codegen.FieldCategory import com.google.android.libraries.pcc.chronicle.codegen.Type import com.google.android.libraries.pcc.chronicle.codegen.TypeLocation import com.google.android.libraries.pcc.chronicle.codegen.TypeSet import com.google.android.libraries.pcc.chronicle.codegen.typeconversion.asClassName import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.asClassName /** * Generate a Chronicle [DataTypeDescriptor] using the provided set of types. * * If the `forSubType` parameter is provided, the types for the [Type] matching the specified * location will be generated. Otherwise, the first type encountered with `isTopLevelType` set to * true will be selected. * * The set of [Types][Type] should include all types needed to represent structured type fields. * This method will call itself recursively to generate inner types. */ fun TypeSet.dataTypeDescriptor( forSubType: TypeLocation? = null, outerTypes: MutableSet<TypeLocation> = mutableSetOf() ): CodeBlock { val typeToGenerate = forSubType?.let { subtype -> this.firstOrNull { it.location == subtype } } ?: primary val typeToGenerateLocation = typeToGenerate.location val typeToGenerateJvmLocation = typeToGenerate.jvmLocation // If we encounter a type already processed in the outer layers, just refer to its location in a // Reference type. if (typeToGenerateLocation in outerTypes) { return CodeBlock.builder() .add("%S", typeToGenerateLocation.toString()) .build() .wrapIn(FieldType.Reference::class.asClassName()) } val codeBuilder = CodeBlock.builder() .add( """ %T(name = %S, cls = %T::class) { ⇥ """.trimIndent(), dataTypeConstructorName, typeToGenerateLocation.toString(), typeToGenerateJvmLocation.asClassName() ) outerTypes.add(typeToGenerateLocation) typeToGenerate.fields.forEach { codeBuilder.add("%S to %L\n", it.name, generateCodeForField(it.category, outerTypes)) } outerTypes.remove(typeToGenerateLocation) return codeBuilder.add("⇤}").build() } private fun TypeSet.mapEntryDtd( keyType: FieldCategory, valueType: FieldCategory, outerTypes: MutableSet<TypeLocation> = mutableSetOf() ): CodeBlock { // Though simpleName loses some information (e.g. Set<String> has simpleName SetValue), the // scoping of the DTD definition prevents collision between between map DTDs with matching // simpleName parameters. val mapDTDName = "Map${keyType::class.java.simpleName}To${valueType::class.java.simpleName}" val codeBuilder = CodeBlock.builder() .add( """ dataTypeDescriptor(name = %S, cls = %T::class) { ⇥ """.trimIndent(), mapDTDName, Map.Entry::class.asClassName() ) codeBuilder.add("\"key\" to %L\n", generateCodeForField(keyType, outerTypes)) codeBuilder.add("\"value\" to %L\n", generateCodeForField(valueType, outerTypes)) codeBuilder.add("⇤}") return codeBuilder.build() } private fun TypeSet.tuple( types: List<FieldCategory>, outerTypes: MutableSet<TypeLocation> = mutableSetOf() ): CodeBlock { val codeBuilder = CodeBlock.builder().add("listOf(") types.forEach { codeBuilder.add("%L,", generateCodeForField(it, outerTypes)) } codeBuilder.add(")") return codeBuilder.build().wrapIn(FieldType.Tuple::class.asClassName()) } // Generate the proper DTD FieldType for a [FieldCategory]. This may involve recursive calls to // dataTypeDescriptor or this method. private fun TypeSet.generateCodeForField( fieldCategory: FieldCategory, outerTypes: MutableSet<TypeLocation> = mutableSetOf() ): CodeBlock { return when (fieldCategory) { // For a list or set or optional, the type of interest is the type parameter and List as the // container. is FieldCategory.ListValue -> generateCodeForField(fieldCategory.listType, outerTypes) .wrapIn(FieldType.List::class.asClassName()) is FieldCategory.SetValue -> generateCodeForField(fieldCategory.setType, outerTypes) .wrapIn(FieldType.List::class.asClassName()) is FieldCategory.NullableValue -> generateCodeForField(fieldCategory.innerType, outerTypes) .wrapIn(FieldType.Nullable::class.asClassName()) // For a map, define a list of an inner DTD that captures the key and value parameters. is FieldCategory.MapValue -> mapEntryDtd(fieldCategory.keyType, fieldCategory.valueType, outerTypes) .wrapIn(FieldType.List::class.asClassName()) // For an enum, wrap a list of possible values, in [FieldType.Enum]. is FieldCategory.EnumValue -> { val codeBuilder = CodeBlock.builder().add("%S, ", fieldCategory.location.toString()).add("listOf(") fieldCategory.possibleValues.forEachIndexed { idx, enumValue -> codeBuilder.add("%S", enumValue) if (idx < fieldCategory.possibleValues.size - 1) codeBuilder.add(", ") } codeBuilder.add(")") codeBuilder.build().wrapIn(FieldType.Enum::class.asClassName()) } // For a nested type, recursively generate the inner DTD. is FieldCategory.NestedTypeValue -> dataTypeDescriptor(fieldCategory.location, outerTypes) // For an opaque type, wrap the fully qualified typename in a [FieldType.Opaque]. is FieldCategory.OpaqueTypeValue -> CodeBlock.of("%S", fieldCategory.location.toString()) .wrapIn(FieldType.Opaque::class.asClassName()) // For pairs, wrap the list of types in a FieldType.Tuple. is FieldCategory.TupleValue -> tuple(fieldCategory.types, outerTypes) // For FieldType supported primitives, use the corresponding field type. FieldCategory.BooleanValue -> CodeBlock.of("%T", FieldType.Boolean::class.asClassName()) FieldCategory.ByteValue -> CodeBlock.of("%T", FieldType.Byte::class.asClassName()) FieldCategory.ByteArrayValue -> CodeBlock.of("%T", FieldType.ByteArray::class.asClassName()) FieldCategory.CharValue -> CodeBlock.of("%T", FieldType.Char::class.asClassName()) FieldCategory.DoubleValue -> CodeBlock.of("%T", FieldType.Double::class.asClassName()) FieldCategory.FloatValue -> CodeBlock.of("%T", FieldType.Float::class.asClassName()) FieldCategory.IntValue -> CodeBlock.of("%T", FieldType.Integer::class.asClassName()) FieldCategory.LongValue -> CodeBlock.of("%T", FieldType.Long::class.asClassName()) FieldCategory.ShortValue -> CodeBlock.of("%T", FieldType.Short::class.asClassName()) FieldCategory.StringValue -> CodeBlock.of("%T", FieldType.String::class.asClassName()) FieldCategory.InstantValue -> CodeBlock.of("%T", FieldType.Instant::class.asClassName()) FieldCategory.DurationValue -> CodeBlock.of("%T", FieldType.Duration::class.asClassName()) // Everything else will be considered a ByteArray. else -> CodeBlock.of("%T", FieldType.ByteArray::class.asClassName()) } } // Get the fully qualified name of the `dataType` constructor method. // I couldn't find a dynamic approach to getting the fully qualified name of the method reference, // but this does the trick for now. private val dataTypeConstructorName = ClassName("com.google.android.libraries.pcc.chronicle.api", "dataTypeDescriptor") /** Wraps the receiving [CodeBlock] in a constructor for the given [wrappingClassName]. */ private fun CodeBlock.wrapIn(wrappingClassName: ClassName): CodeBlock { return CodeBlock.builder().add("%T(", wrappingClassName).add(this).add(")").build() }
apache-2.0
fc0307bb7a57b9f8dc125e3f5b20a6a6
42.421875
98
0.732398
4.335413
false
false
false
false
terracotta-ko/Android_Treasure_House
Room/app/src/main/java/com/ko/room/data/UserDatabaseProvider.kt
1
733
package com.ko.room.data import androidx.room.Room import android.content.Context class UserDatabaseProvider { companion object { private const val USER_DATABASE = "user_database.db" @Volatile private var INSTANCE: UserDatabase? = null fun getInstance(context: Context): UserDatabase = INSTANCE ?: synchronized(this) { INSTANCE ?: buildDatabase(context).also { INSTANCE = it } } private fun buildDatabase(context: Context) = Room.databaseBuilder( context.applicationContext, UserDatabase::class.java, USER_DATABASE ) .build() } }
mit
6806c5ba4f10d96ef334b49830c20c1a
24.275862
68
0.568895
5.389706
false
false
false
false
meddlepal/openbaseball
src/main/kotlin/openbaseball/vertx/json/JacksonMessageCodec.kt
1
1043
package openbaseball.vertx.json import io.vertx.core.buffer.Buffer import io.vertx.core.eventbus.MessageCodec class JacksonMessageCodec<T>(private val clazz: Class<T>) : MessageCodec<T, T> { init { clazz.canonicalName ?: throw IllegalStateException("Class name is null") } override fun systemCodecID(): Byte = -1 override fun name(): String = clazz.canonicalName override fun transform(message: T?) = message override fun encodeToWire(buffer: Buffer?, message: T?) { val json = ObjectMappers.mapper.writeValueAsString(message) buffer?.appendInt(json.toByteArray(Charsets.UTF_8).size) buffer?.appendString(json) } override fun decodeFromWire(bufferPos: Int, buffer: Buffer?): T { val messageLength = buffer!!.getInt(bufferPos) val messageStartPos = bufferPos + 4 // Jump 4 because getInt() == 4 bytes val rawJson = buffer.getString(messageStartPos, messageStartPos + messageLength) return ObjectMappers.mapper.readValue(rawJson, clazz) } }
agpl-3.0
d9800a94cb60f02614b05bacd716d4f4
35
88
0.704698
4.27459
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/movies/MoviesDiscoverFragment.kt
1
6734
package com.battlelancer.seriesguide.movies import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.core.view.MenuProvider import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.ViewModelProvider import androidx.loader.app.LoaderManager import androidx.loader.content.Loader import androidx.recyclerview.widget.GridLayoutManager import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener import com.battlelancer.seriesguide.R import com.battlelancer.seriesguide.databinding.FragmentMoviesDiscoverBinding import com.battlelancer.seriesguide.movies.MovieLocalizationDialogFragment.LocalizationChangedEvent import com.battlelancer.seriesguide.movies.MoviesActivityViewModel.ScrollTabToTopEvent import com.battlelancer.seriesguide.movies.search.MoviesSearchActivity import com.battlelancer.seriesguide.ui.AutoGridLayoutManager import com.battlelancer.seriesguide.util.Utils import com.battlelancer.seriesguide.util.ViewTools import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode /** * Displays links to movie lists (see [MoviesDiscoverAdapter]) and movies currently in theaters. */ class MoviesDiscoverFragment : Fragment() { private var binding: FragmentMoviesDiscoverBinding? = null private lateinit var adapter: MoviesDiscoverAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return FragmentMoviesDiscoverBinding.inflate(inflater, container, false) .also { binding = it } .root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val binding = binding!! binding.swipeRefreshLayoutMoviesDiscover.setOnRefreshListener(onRefreshListener) binding.swipeRefreshLayoutMoviesDiscover.isRefreshing = false ViewTools.setSwipeRefreshLayoutColors( requireActivity().theme, binding.swipeRefreshLayoutMoviesDiscover ) adapter = MoviesDiscoverAdapter( requireContext(), DiscoverItemClickListener(requireContext()) ) val layoutManager = AutoGridLayoutManager( context, R.dimen.movie_grid_columnWidth, 2, 6 ) layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { val viewType = adapter.getItemViewType(position) if (viewType == MoviesDiscoverAdapter.VIEW_TYPE_LINK) { return 3 } if (viewType == MoviesDiscoverAdapter.VIEW_TYPE_HEADER) { return layoutManager.spanCount } return if (viewType == MoviesDiscoverAdapter.VIEW_TYPE_MOVIE) { 2 } else 0 } } binding.recyclerViewMoviesDiscover.setHasFixedSize(true) binding.recyclerViewMoviesDiscover.layoutManager = layoutManager binding.recyclerViewMoviesDiscover.adapter = adapter ViewModelProvider(requireActivity())[MoviesActivityViewModel::class.java] .scrollTabToTopLiveData .observe(viewLifecycleOwner) { event: ScrollTabToTopEvent? -> if (event != null && event.tabPosition == MoviesActivityImpl.TAB_POSITION_DISCOVER) { binding.recyclerViewMoviesDiscover.smoothScrollToPosition(0) } } LoaderManager.getInstance(this).initLoader(0, null, nowPlayingLoaderCallbacks) requireActivity().addMenuProvider( optionsMenuProvider, viewLifecycleOwner, Lifecycle.State.RESUMED ) } override fun onStart() { super.onStart() EventBus.getDefault().register(this) } override fun onStop() { super.onStop() EventBus.getDefault().unregister(this) } override fun onDestroyView() { super.onDestroyView() binding = null } private val optionsMenuProvider: MenuProvider = object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.movies_discover_menu, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { val itemId = menuItem.itemId if (itemId == R.id.menu_action_movies_search_change_language) { MovieLocalizationDialogFragment.show(parentFragmentManager) return true } return false } } @Subscribe(threadMode = ThreadMode.MAIN) fun onEventLanguageChanged(event: LocalizationChangedEvent?) { LoaderManager.getInstance(this).restartLoader(0, null, nowPlayingLoaderCallbacks) } private class DiscoverItemClickListener(context: Context) : MovieClickListenerImpl(context), MoviesDiscoverAdapter.ItemClickListener { override fun onClickLink(link: MoviesDiscoverLink, anchor: View) { val intent = Intent(context, MoviesSearchActivity::class.java) intent.putExtra(MoviesSearchActivity.EXTRA_ID_LINK, link.id) Utils.startActivityWithAnimation(context, intent, anchor) } } private val nowPlayingLoaderCallbacks: LoaderManager.LoaderCallbacks<MoviesDiscoverLoader.Result> = object : LoaderManager.LoaderCallbacks<MoviesDiscoverLoader.Result> { override fun onCreateLoader( id: Int, args: Bundle? ): Loader<MoviesDiscoverLoader.Result> { return MoviesDiscoverLoader(requireContext()) } override fun onLoadFinished( loader: Loader<MoviesDiscoverLoader.Result>, data: MoviesDiscoverLoader.Result ) { binding?.swipeRefreshLayoutMoviesDiscover?.isRefreshing = false adapter.updateMovies(data.results) } override fun onLoaderReset(loader: Loader<MoviesDiscoverLoader.Result>) { adapter.updateMovies(null) } } private val onRefreshListener = OnRefreshListener { LoaderManager.getInstance(this@MoviesDiscoverFragment) .restartLoader(0, null, nowPlayingLoaderCallbacks) } }
apache-2.0
fd0305ef25909e0460dd29c42187f0da
37.485714
103
0.686813
5.551525
false
false
false
false
rharter/windy-city-devcon-android
app/src/main/kotlin/com/gdgchicagowest/windycitydevcon/features/speakerlist/SpeakerListView.kt
1
1981
package com.gdgchicagowest.windycitydevcon.features.speakerlist import android.content.Context import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.AttributeSet import android.view.ViewGroup import com.gdgchicagowest.windycitydevcon.ext.getComponent import com.gdgchicagowest.windycitydevcon.features.main.MainComponent import com.gdgchicagowest.windycitydevcon.features.sessiondetail.SpeakerAdapter import com.gdgchicagowest.windycitydevcon.features.sessions.DividerItemDecoration import com.gdgchicagowest.windycitydevcon.features.speakerdetail.SpeakerNavigator import com.gdgchicagowest.windycitydevcon.model.Speaker import javax.inject.Inject class SpeakerListView(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : RecyclerView(context, attrs, defStyle), SpeakerListMvp.View { private val adapter: SpeakerAdapter @Inject lateinit var presenter: SpeakerListMvp.Presenter @Inject lateinit var speakerNavigator: SpeakerNavigator init { context.getComponent<MainComponent>().speakerListComponent().inject(this) layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) layoutManager = LinearLayoutManager(context, VERTICAL, false) addItemDecoration(DividerItemDecoration(context)) adapter = SpeakerAdapter(false, { speaker, view -> speakerNavigator.nagivateToSpeaker(speaker.id!!, view) }) super.setAdapter(adapter) } override fun onAttachedToWindow() { super.onAttachedToWindow() presenter.onAttach(this) } override fun onDetachedFromWindow() { presenter.onDetach() super.onDetachedFromWindow() } override fun showSpeakers(speakers: Collection<Speaker>) { adapter.speakers.clear() adapter.speakers.addAll(speakers) adapter.notifyDataSetChanged() } }
apache-2.0
03c3db169848ecd66c1307949765a90d
37.115385
119
0.767289
5.132124
false
false
false
false
Edward608/RxBinding
buildSrc/src/main/kotlin/com/jakewharton/rxbinding/project/KotlinGenTask.kt
2
13968
package com.jakewharton.rxbinding.project import com.github.javaparser.JavaParser import com.github.javaparser.ast.ImportDeclaration import com.github.javaparser.ast.PackageDeclaration import com.github.javaparser.ast.TypeParameter import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration import com.github.javaparser.ast.body.MethodDeclaration import com.github.javaparser.ast.expr.AnnotationExpr import com.github.javaparser.ast.expr.MarkerAnnotationExpr import com.github.javaparser.ast.expr.NameExpr import com.github.javaparser.ast.type.ClassOrInterfaceType import com.github.javaparser.ast.type.PrimitiveType import com.github.javaparser.ast.type.ReferenceType import com.github.javaparser.ast.type.Type import com.github.javaparser.ast.type.VoidType import com.github.javaparser.ast.type.WildcardType import com.github.javaparser.ast.visitor.VoidVisitorAdapter import com.squareup.kotlinpoet.ANY import com.squareup.kotlinpoet.AnnotationSpec import com.squareup.kotlinpoet.AnnotationSpec.UseSiteTarget.FILE import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.INT import com.squareup.kotlinpoet.KModifier.INLINE import com.squareup.kotlinpoet.KotlinFile import com.squareup.kotlinpoet.ParameterSpec import com.squareup.kotlinpoet.ParameterizedTypeName import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeVariableName import com.squareup.kotlinpoet.UNIT import com.squareup.kotlinpoet.WildcardTypeName import com.squareup.kotlinpoet.asClassName import org.gradle.api.tasks.SourceTask import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.incremental.IncrementalTaskInputs import sun.reflect.generics.reflectiveObjects.NotImplementedException import java.io.File import kotlin.properties.Delegates private val UNIT_OBSERVABLE = ParameterizedTypeName.get( ClassName("io.reactivex", "Observable"), UNIT) open class KotlinGenTask : SourceTask() { companion object { /** Regex used for finding references in javadoc links */ private val DOC_LINK_REGEX = "[0-9A-Za-z._]*" private val SLASH = File.separator private val GenericTypeNullableAnnotation = MarkerAnnotationExpr( NameExpr("GenericTypeNullable")) /** Recursive function for resolving a Type into a Kotlin-friendly String representation */ fun resolveKotlinType(inputType: Type, methodAnnotations: List<AnnotationExpr>? = null, associatedImports: Map<String, ClassName>? = null): TypeName { return when (inputType) { is ReferenceType -> resolveKotlinType(inputType.type, methodAnnotations, associatedImports) is PrimitiveType -> resolveKotlinTypeByName(inputType.toString(), associatedImports) is VoidType -> resolveKotlinTypeByName(inputType.toString(), associatedImports) is ClassOrInterfaceType -> resolveKotlinClassOrInterfaceType(inputType, methodAnnotations, associatedImports) is WildcardType -> resolveKotlinWildcardType(inputType, methodAnnotations, associatedImports) else -> throw NotImplementedException() } } private fun resolveKotlinTypeByName(input: String, associatedImports: Map<String, ClassName>? = null): ClassName { return when (input) { "Object" -> ANY "Integer" -> INT "int", "char", "boolean", "long", "float", "short", "byte" -> { ClassName("kotlin", input.capitalize()) } "List" -> MutableList::class.asClassName() else -> associatedImports?.let { it[input] } ?: ClassName.bestGuess(input) } } private fun resolveKotlinClassOrInterfaceType( inputType: ClassOrInterfaceType, methodAnnotations: List<AnnotationExpr>?, associatedImports: Map<String, ClassName>? = null): TypeName { return if (isObservableObject(inputType)) { UNIT_OBSERVABLE } else { val typeArgs = resolveTypeArguments(inputType, methodAnnotations, associatedImports) val rawType = resolveKotlinTypeByName(inputType.name, associatedImports) if (typeArgs.isEmpty()) { rawType } else { ParameterizedTypeName.get(rawType, *typeArgs.toTypedArray()) } } } private fun isObservableObject(inputType: ClassOrInterfaceType): Boolean { return inputType.name == "Observable" && inputType.typeArgs?.first() == ReferenceType(ClassOrInterfaceType("Object")) } private fun resolveTypeArguments(inputType: ClassOrInterfaceType, methodAnnotations: List<AnnotationExpr>?, associatedImports: Map<String, ClassName>? = null): List<TypeName> { return inputType.typeArgs?.map { type: Type -> resolveKotlinType(type, methodAnnotations, associatedImports) } ?: emptyList() } private fun resolveKotlinWildcardType(inputType: WildcardType, methodAnnotations: List<AnnotationExpr>?, associatedImports: Map<String, ClassName>? = null): WildcardTypeName { val isNullable = isWildcardNullable(methodAnnotations) inputType.`super`?.let { name -> val type = WildcardTypeName.supertypeOf( resolveKotlinType(name, associatedImports = associatedImports)) return if (isNullable) type.asNullable() else type } inputType.extends?.let { name -> val type = WildcardTypeName.subtypeOf( resolveKotlinType(name, associatedImports = associatedImports)) return if (isNullable) type.asNullable() else type } throw IllegalStateException("Wildcard with no super or extends") } private fun isWildcardNullable(annotations: List<AnnotationExpr>?): Boolean { return annotations?.any { it == GenericTypeNullableAnnotation } ?: false } } @TaskAction @Suppress("unused") fun generate(@Suppress("UNUSED_PARAMETER") inputs: IncrementalTaskInputs) { // Clear things out first to make sure no stragglers are left val outputDir = File("${project.projectDir}-kotlin${SLASH}src${SLASH}main${SLASH}kotlin") outputDir.walkTopDown() .filter { it.isFile } .filterNot { it.absolutePath.contains("internal") } .forEach { it.delete() } // Let's get going getSource().forEach { generateKotlin(it) } } private fun generateKotlin(file: File) { val outputPath = file.parent.replace("java", "kotlin") .replace("${SLASH}src", "-kotlin${SLASH}src") .substringBefore("com${SLASH}jakewharton") val outputDir = File(outputPath) // Start parsing the java files val cu = JavaParser.parse(file) val kClass = KFile() kClass.fileName = file.name.removeSuffix(".java") val imports = mutableListOf<String>() // Visit the imports first so we can create an associate of them for lookups later. cu.accept(object : VoidVisitorAdapter<MutableList<String>>() { override fun visit(n: ImportDeclaration, importsList: MutableList<String>) { if (!n.isStatic) { importsList.add(n.name.toString()) } super.visit(n, importsList) } }, imports) // Create an association of imports simple name -> ClassName // This is necessary because JavaParser doesn't yield the fully qualified classname of types, so // this is a bit of a trick to just reuse the imports from the target class as a reference for // what they're referring to. val associatedImports = imports.associateBy({ it.substringAfterLast(".") }) { ClassName.bestGuess(it) } // Visit the appropriate nodes and extract information cu.accept(object : VoidVisitorAdapter<KFile>() { override fun visit(n: PackageDeclaration, arg: KFile) { arg.packageName = n.name.toString() super.visit(n, arg) } override fun visit(n: ClassOrInterfaceDeclaration, arg: KFile) { arg.bindingClass = n.name arg.extendedClass = n.name.replace("Rx", "") super.visit(n, arg) } override fun visit(n: MethodDeclaration, arg: KFile) { arg.methods.add(KMethod(n, associatedImports)) // Explicitly avoid going deeper, we only care about top level methods. Otherwise // we'd hit anonymous inner classes and whatnot } }, kClass) kClass.generate(outputDir) } /** * Represents a kotlin file that corresponds to a Java file/class in an RxBinding module */ class KFile { var fileName: String by Delegates.notNull() var packageName: String by Delegates.notNull() var bindingClass: String by Delegates.notNull() var extendedClass: String by Delegates.notNull() val methods = mutableListOf<KMethod>() /** Generates the code and writes it to the desired directory */ fun generate(directory: File) { KotlinFile.builder(packageName, fileName) .apply { if (methods.any { it.emitsUnit() }) { addStaticImport("com.jakewharton.rxbinding2.internal", "VoidToUnit") } methods.map { it.generate(ClassName.bestGuess(bindingClass)) } .forEach { addFun(it) } } // @file:Suppress("NOTHING_TO_INLINE") .addFileAnnotation(AnnotationSpec.builder(Suppress::class) .useSiteTarget(FILE) .addMember("names", "%S", "NOTHING_TO_INLINE") .build()) .build() .writeTo(directory) } } /** * Represents a method implementation that needs to be wired up in Kotlin * * @param associatedImports a mapping of associated imports by simple name -> [ClassName]. This is * necessary because JavaParser doesn't yield the fully qualified class name to look up, but we * can snag the imports from the target class ourselves and refer to them as needed. */ class KMethod(n: MethodDeclaration, private val associatedImports: Map<String, ClassName>) { private val name = n.name private val annotations: List<AnnotationExpr> = n.annotations private val comment = n.comment?.content?.let { cleanUpDoc(it) } private val extendedClass = resolveKotlinType(n.parameters[0].type, associatedImports = associatedImports) private val parameters = n.parameters.subList(1, n.parameters.size) private val returnType = n.type private val typeParameters = typeParams(n.typeParameters) private val kotlinType = resolveKotlinType(returnType, annotations, associatedImports) /** Cleans up the generated doc and translates some html to equivalent markdown for Kotlin docs */ private fun cleanUpDoc(doc: String): String { return doc .replace(" * ", "") .replace(" *", "") .replace("<em>", "*") .replace("</em>", "*") .replace("<p>", "") // {@code view} -> `view` .replace("\\{@code ($DOC_LINK_REGEX)}".toRegex()) { result: MatchResult -> val codeName = result.destructured "`${codeName.component1()}`" } // {@link Foo} -> [Foo] .replace("\\{@link ($DOC_LINK_REGEX)}".toRegex()) { result: MatchResult -> val foo = result.destructured "[${foo.component1()}]" } // {@link Foo#bar} -> [Foo.bar] .replace( "\\{@link ($DOC_LINK_REGEX)#($DOC_LINK_REGEX)}".toRegex()) { result: MatchResult -> val (foo, bar) = result.destructured "[$foo.$bar]" } // {@linkplain Foo baz} -> [baz][Foo] .replace( "\\{@linkplain ($DOC_LINK_REGEX) ($DOC_LINK_REGEX)}".toRegex()) { result: MatchResult -> val (foo, baz) = result.destructured "[$baz][$foo]" } //{@linkplain Foo#bar baz} -> [baz][Foo.bar] .replace( "\\{@linkplain ($DOC_LINK_REGEX)#($DOC_LINK_REGEX) ($DOC_LINK_REGEX)}".toRegex()) { result: MatchResult -> val (foo, bar, baz) = result.destructured "[$baz][$foo.$bar]" } .trim() .plus("\n") } /** Generates method level type parameters */ private fun typeParams(params: List<TypeParameter>?): List<TypeVariableName>? { return params?.map { p -> TypeVariableName(p.name, resolveKotlinType(p.typeBound[0], associatedImports = associatedImports)) } } /** * Generates parameters in a kotlin-style format */ private fun kParams(): List<ParameterSpec> { return parameters.map { p -> ParameterSpec.builder(p.id.name, resolveKotlinType(p.type, associatedImports = associatedImports)) .build() } } /** * Generates the kotlin code for this method * * @param bindingClass name of the RxBinding class this is tied to */ fun generate(bindingClass: TypeName): FunSpec { /////////////// // STRUCTURE // /////////////// // Javadoc // public inline fun DrawerLayout.drawerOpen(): Observable<Boolean> = RxDrawerLayout.drawerOpen(this) // <access specifier> inline fun <extendedClass>.<name>(params): <type> = <bindingClass>.name(this, params) val parameterSpecs = kParams() return FunSpec.builder(name) .receiver(extendedClass) .addKdoc(comment ?: "") .addModifiers(INLINE) .apply { typeParameters?.let { addTypeVariables(it) } } .returns(kotlinType) .addParameters(parameterSpecs) .addCode("return %T.$name(${if (parameterSpecs.isNotEmpty()) { "this, ${parameterSpecs.joinToString { it.name }}" } else { "this" }})", bindingClass) .apply { // Object --> Unit mapping if (emitsUnit()) { addCode(".map(VoidToUnit)") } } .addCode("\n") .build() } fun emitsUnit() = kotlinType == UNIT_OBSERVABLE } }
apache-2.0
6ba33dc26460c89ee15d6f78a66e0ea2
38.01676
120
0.657861
4.603823
false
false
false
false
dropbox/dropbox-sdk-java
examples/examples/src/test/java/com/dropbox/core/examples/upload_file/UploadFileExampleTest.kt
1
1700
package com.dropbox.core.examples.upload_file import com.dropbox.core.examples.CredentialsUtil import com.dropbox.core.examples.FileCreationUtils.createTempFileOfSize import com.dropbox.core.examples.FileCreationUtils.kbToBytes import com.dropbox.core.examples.FileCreationUtils.mbToBytes import com.dropbox.core.examples.TestUtil import org.junit.Assume.assumeTrue import org.junit.Before import org.junit.Test import java.io.File import java.time.Instant class UploadFileExampleTest { private val dateStr = Instant.now().toString() @Before fun setup() { assumeTrue(TestUtil.isRunningInCI()) } @Test fun upload1KBFile() { File.createTempFile(dateStr, ".dat").also { tempFile -> try { createTempFileOfSize(tempFile, kbToBytes(1).toInt()) val localFile = tempFile.absolutePath val dropboxFile = "/test/dropbox-sdk-java/${dateStr}/examples/upload-file/small-1KiB.dat" UploadFileExample.runExample(CredentialsUtil.getAuthInfo(), localFile, dropboxFile) } finally { tempFile.delete() } } } @Test fun upload32MBFile() { File.createTempFile(dateStr, ".dat").also { tempFile -> try { createTempFileOfSize(tempFile, mbToBytes(32).toInt()) val localFile = tempFile.absolutePath val dropboxFile = "/test/dropbox-sdk-java/${dateStr}/examples/upload-file/large-32MiB.dat" UploadFileExample.runExample(CredentialsUtil.getAuthInfo(), localFile, dropboxFile) } finally { tempFile.delete() } } } }
mit
7159a5b28e4febe7f537ea2d6c364232
32.352941
106
0.651176
4.347826
false
true
false
false
nickthecoder/tickle
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/util/Vector2dParameter.kt
1
2435
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.editor.util import javafx.util.StringConverter import org.joml.Vector2d import uk.co.nickthecoder.paratask.parameters.CompoundParameter import uk.co.nickthecoder.paratask.parameters.DoubleParameter import uk.co.nickthecoder.paratask.parameters.addParameters import uk.co.nickthecoder.paratask.util.uncamel import uk.co.nickthecoder.tickle.vector2dFromString import uk.co.nickthecoder.tickle.vector2dToString class Vector2dParameter( name: String, label: String = name.uncamel(), value: Vector2d = Vector2d(), description: String = "", showXY: Boolean = true) : CompoundParameter<Vector2d>( name, label, description) { val xP = DoubleParameter("${name}_x", label = if (showXY) "X" else "", minValue = -Double.MAX_VALUE) var x by xP val yP = DoubleParameter("${name}_y", label = if (showXY) "Y" else ",", minValue = -Double.MAX_VALUE) var y by yP override val converter = object : StringConverter<Vector2d>() { override fun fromString(string: String): Vector2d { return vector2dFromString(string) } override fun toString(obj: Vector2d): String { return vector2dToString(obj) } } override var value: Vector2d get() { return Vector2d(xP.value ?: 0.0, yP.value ?: 0.0) } set(value) { xP.value = value.x yP.value = value.y } init { this.value = value addParameters(xP, yP) } override fun toString(): String { return "Vector2dParameter : $value" } override fun copy(): Vector2dParameter { val copy = Vector2dParameter(name, label, value, description) return copy } }
gpl-3.0
2f7c153357ef401c76796cbc63a471de
29.4375
105
0.680903
4.024793
false
false
false
false