content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
fun<T> foo(): Set<T> { ret<caret> } // INVOCATION_COUNT: 1 // WITH_ORDER // EXIST: { lookupString: "return", itemText: "return", tailText: null, attributes: "bold" } // EXIST: { lookupString: "return emptySet()", itemText: "return", tailText: " emptySet()", attributes: "bold" } // NOTHING_ELSE
plugins/kotlin/completion/tests/testData/keywords/ReturnSet.kt
2899345907
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.remote import com.google.common.net.HostAndPort import com.intellij.openapi.diagnostic.logger import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.isPending import java.io.InputStream import java.io.OutputStream import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import kotlin.math.max import kotlin.system.measureNanoTime /** * Asynchronous adapter for synchronous process callers. Intended for usage in cases when blocking calls like [ProcessBuilder.start] * are called in EDT and it's uneasy to refactor. **Anyway, better to not call blocking methods in EDT rather than use this class.** * * **Beware!** Note that [DeferredRemoteProcess] is created even if underlying one fails to. Take care to make sure that such cases really * look to users like underlying process not started, not like it started and died silently (see IDEA-265188). It would help a lot with * future troubleshooting, reporting and investigation. */ class DeferredRemoteProcess(private val promise: Promise<RemoteProcess>) : RemoteProcess() { override fun getOutputStream(): OutputStream = DeferredOutputStream() override fun getInputStream(): InputStream = DeferredInputStream { it.inputStream } override fun getErrorStream(): InputStream = DeferredInputStream { it.errorStream } override fun waitFor(): Int = get().waitFor() override fun waitFor(timeout: Long, unit: TimeUnit): Boolean { val process: RemoteProcess? val nanosSpent = measureNanoTime { process = promise.blockingGet(timeout.toInt(), unit) } val restTimeoutNanos = max(0, TimeUnit.NANOSECONDS.convert(timeout, unit) - nanosSpent) return process?.waitFor(restTimeoutNanos, TimeUnit.NANOSECONDS) ?: false } override fun exitValue(): Int = tryGet()?.exitValue() ?: throw IllegalStateException("Process is not terminated") override fun destroy() { runNowOrSchedule { it.destroy() } } override fun killProcessTree(): Boolean = runNowOrSchedule { it.killProcessTree() } ?: false override fun isDisconnected(): Boolean = tryGet()?.isDisconnected ?: false override fun getLocalTunnel(remotePort: Int): HostAndPort? = get().getLocalTunnel(remotePort) override fun destroyForcibly(): Process = runNowOrSchedule { it.destroyForcibly() } ?: this override fun supportsNormalTermination(): Boolean = true override fun isAlive(): Boolean = tryGet()?.isAlive ?: true override fun onExit(): CompletableFuture<Process> = CompletableFuture<Process>().also { promise.then(it::complete) } private fun get(): RemoteProcess = promise.blockingGet(Int.MAX_VALUE)!! private fun tryGet(): RemoteProcess? = promise.takeUnless { it.isPending }?.blockingGet(0) private fun <T> runNowOrSchedule(handler: (RemoteProcess) -> T): T? { val process = tryGet() return if (process != null) { handler(process) } else { val cause = Throwable("Initially called from this context.") promise.then { try { it?.let(handler) } catch (err: Throwable) { err.addSuppressed(cause) LOG.info("$this: Got an error that nothing could catch: ${err.message}", err) } } null } } private inner class DeferredOutputStream : OutputStream() { override fun close() { runNowOrSchedule { it.outputStream.close() } } override fun flush() { tryGet()?.outputStream?.flush() } override fun write(b: Int) { get().outputStream.write(b) } override fun write(b: ByteArray) { get().outputStream.write(b) } override fun write(b: ByteArray, off: Int, len: Int) { get().outputStream.write(b, off, len) } } private inner class DeferredInputStream(private val streamGetter: (RemoteProcess) -> InputStream) : InputStream() { override fun close() { runNowOrSchedule { streamGetter(it).close() } } override fun read(): Int = streamGetter(get()).read() override fun read(b: ByteArray): Int = streamGetter(get()).read(b) override fun read(b: ByteArray, off: Int, len: Int): Int = streamGetter(get()).read(b, off, len) override fun readAllBytes(): ByteArray = streamGetter(get()).readAllBytes() override fun readNBytes(len: Int): ByteArray = streamGetter(get()).readNBytes(len) override fun readNBytes(b: ByteArray, off: Int, len: Int): Int = streamGetter(get()).readNBytes(b, off, len) override fun skip(n: Long): Long = streamGetter(get()).skip(n) override fun available(): Int = tryGet()?.let(streamGetter)?.available() ?: 0 override fun markSupported(): Boolean = false } private companion object { private val LOG = logger<DeferredRemoteProcess>() } }
platform/platform-impl/src/com/intellij/remote/DeferredRemoteProcess.kt
3723803732
//FILE: a/a.kt class A( val firstName: String, val lastName: String, val age: Int ) { val c = 1 val d = "A" } //FILE: b/a.kt class B( val firstName: String, val lastName: String, val age: Int ) { init { val a = 5 val b = 6 } }
plugins/kotlin/jvm-debugger/test/testData/fileRanking/multilinePrimaryConstructorWithBody.kt
311495232
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetnews.data import android.content.Context import com.example.jetnews.data.interests.InterestsRepository import com.example.jetnews.data.interests.impl.FakeInterestsRepository import com.example.jetnews.data.posts.PostsRepository import com.example.jetnews.data.posts.impl.FakePostsRepository /** * Dependency Injection container at the application level. */ interface AppContainer { val postsRepository: PostsRepository val interestsRepository: InterestsRepository } /** * Implementation for the Dependency Injection container at the application level. * * Variables are initialized lazily and the same instance is shared across the whole app. */ class AppContainerImpl(private val applicationContext: Context) : AppContainer { override val postsRepository: PostsRepository by lazy { FakePostsRepository() } override val interestsRepository: InterestsRepository by lazy { FakeInterestsRepository() } }
JetNews/app/src/main/java/com/example/jetnews/data/AppContainerImpl.kt
346328607
package com.kickstarter.viewmodels import androidx.annotation.NonNull import com.kickstarter.libs.ActivityViewModel import com.kickstarter.libs.Environment import com.kickstarter.libs.utils.DateTimeUtils import com.kickstarter.models.ProjectFaq import com.kickstarter.ui.viewholders.FrequentlyAskedQuestionsViewHolder import rx.Observable import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject interface FrequentlyAskedQuestionsViewHolderViewModel { interface Inputs { /** Configure the view model with the [ProjectFaq]. */ fun configureWith(projectFaq: ProjectFaq) } interface Outputs { /** Emits the String for the question */ fun question(): Observable<String> /** Emits the String for the answer */ fun answer(): Observable<String> /** Emits the String for the updatedDate */ fun updatedDate(): Observable<String> } class ViewModel(@NonNull val environment: Environment) : ActivityViewModel<FrequentlyAskedQuestionsViewHolder>(environment), Inputs, Outputs { val inputs: Inputs = this val outputs: Outputs = this private val projectFaqInput = PublishSubject.create<ProjectFaq>() private val question = BehaviorSubject.create<String>() private val answer = BehaviorSubject.create<String>() private val updatedDate = BehaviorSubject.create<String>() init { val projectFaqInput = this.projectFaqInput projectFaqInput .map { it.question } .subscribe(this.question) projectFaqInput .map { it.answer } .subscribe(this.answer) projectFaqInput .map { requireNotNull(it.createdAt) } .map { DateTimeUtils.longDate(it) } .subscribe(this.updatedDate) } override fun configureWith(projectFaq: ProjectFaq) = this.projectFaqInput.onNext(projectFaq) override fun question(): Observable<String> = this.question override fun answer(): Observable<String> = this.answer override fun updatedDate(): Observable<String> = this.updatedDate } }
app/src/main/java/com/kickstarter/viewmodels/FrequentlyAskedQuestionsViewHolderViewModel.kt
1957561179
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.firebase.functions.ktx import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import com.google.firebase.FirebaseApp import com.google.firebase.FirebaseOptions import com.google.firebase.functions.FirebaseFunctions import com.google.firebase.ktx.Firebase import com.google.firebase.ktx.app import com.google.firebase.ktx.initialize import com.google.firebase.platforminfo.UserAgentPublisher import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner const val APP_ID = "APP_ID" const val API_KEY = "API_KEY" const val EXISTING_APP = "existing" abstract class BaseTestCase { @Before fun setUp() { Firebase.initialize( ApplicationProvider.getApplicationContext(), FirebaseOptions.Builder() .setApplicationId(APP_ID) .setApiKey(API_KEY) .setProjectId("123") .build() ) Firebase.initialize( ApplicationProvider.getApplicationContext(), FirebaseOptions.Builder() .setApplicationId(APP_ID) .setApiKey(API_KEY) .setProjectId("123") .build(), EXISTING_APP ) } @After fun cleanUp() { FirebaseApp.clearInstancesForTest() } } @RunWith(RobolectricTestRunner::class) class FunctionsTests : BaseTestCase() { @Test fun `functions should delegate to FirebaseFunctions#getInstance()`() { assertThat(Firebase.functions).isSameInstanceAs(FirebaseFunctions.getInstance()) } @Test fun `FirebaseApp#functions should delegate to FirebaseFunctions#getInstance(FirebaseApp)`() { val app = Firebase.app(EXISTING_APP) assertThat(Firebase.functions(app)).isSameInstanceAs(FirebaseFunctions.getInstance(app)) } @Test fun `Firebase#functions should delegate to FirebaseFunctions#getInstance(region)`() { val region = "valid_region" assertThat(Firebase.functions(region)).isSameInstanceAs(FirebaseFunctions.getInstance(region)) } @Test fun `Firebase#functions should delegate to FirebaseFunctions#getInstance(FirebaseApp, region)`() { val app = Firebase.app(EXISTING_APP) val region = "valid_region" assertThat(Firebase.functions(app, region)) .isSameInstanceAs(FirebaseFunctions.getInstance(app, region)) } } @RunWith(RobolectricTestRunner::class) class LibraryVersionTest : BaseTestCase() { @Test fun `library version should be registered with runtime`() { val publisher = Firebase.app.get(UserAgentPublisher::class.java) assertThat(publisher.userAgent).contains(LIBRARY_NAME) } }
firebase-functions/ktx/src/test/kotlin/com/google/firebase/functions/ktx/FunctionsTests.kt
3870963886
@file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final. package com.vanniktech.lintrules.android import com.android.tools.lint.checks.infrastructure.TestFiles.xml import com.android.tools.lint.checks.infrastructure.TestLintTask.lint import org.junit.Test class WrongMenuIdFormatDetectorTest { @Test fun idLowerCamelCase() { lint() .files( xml( "res/menu/ids.xml", """ <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/lowerCamelCase"/> </menu> """, ).indented(), ) .issues(ISSUE_WRONG_MENU_ID_FORMAT) .run() .expectClean() } @Test fun idDefinedLowerCamelCase() { lint() .files( xml( "res/menu/ids.xml", """ <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@id/lowerCamelCase"/> </menu> """, ).indented(), ) .issues(ISSUE_WRONG_MENU_ID_FORMAT) .run() .expectClean() } @Test fun idCamelCase() { lint() .files( xml( "res/menu/ids.xml", """ <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/CamelCase"/> </menu> """, ).indented(), ) .issues(ISSUE_WRONG_MENU_ID_FORMAT) .run() .expect( """ |res/menu/ids.xml:2: Warning: Id is not in lowerCamelCaseFormat [WrongMenuIdFormat] | <item android:id="@+id/CamelCase"/> | ~~~~~~~~~~~~~~ |0 errors, 1 warnings """.trimMargin(), ) .expectFixDiffs( """ |Fix for res/menu/ids.xml line 1: Convert to lowerCamelCase: |@@ -2 +2 |- <item android:id="@+id/CamelCase"/> |+ <item android:id="@+id/camelCase"/> """.trimMargin(), ) } @Test fun idSnakeCase() { lint() .files( xml( "res/menu/ids.xml", """ <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/snake_case"/> </menu> """, ).indented(), ) .issues(ISSUE_WRONG_MENU_ID_FORMAT) .run() .expect( """ |res/menu/ids.xml:2: Warning: Id is not in lowerCamelCaseFormat [WrongMenuIdFormat] | <item android:id="@+id/snake_case"/> | ~~~~~~~~~~~~~~~ |0 errors, 1 warnings """.trimMargin(), ) .expectFixDiffs( """ |Fix for res/menu/ids.xml line 1: Convert to lowerCamelCase: |@@ -2 +2 |- <item android:id="@+id/snake_case"/> |+ <item android:id="@+id/snakeCase"/> """.trimMargin(), ) } }
lint-rules-android-lint/src/test/java/com/vanniktech/lintrules/android/WrongMenuIdFormatDetectorTest.kt
1194408244
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.groovy.config.wizard import com.intellij.ide.wizard.BuildSystemNewProjectWizardData import com.intellij.ide.wizard.NewProjectWizardStep import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.roots.ui.distribution.DistributionInfo import com.intellij.openapi.util.Key interface BuildSystemGroovyNewProjectWizardData: BuildSystemNewProjectWizardData { val groovySdkProperty : GraphProperty<DistributionInfo?> var groovySdk : DistributionInfo? companion object { @JvmStatic val KEY = Key.create<BuildSystemGroovyNewProjectWizardData>(BuildSystemGroovyNewProjectWizardData::class.java.name) @JvmStatic val NewProjectWizardStep.buildSystemData get() = data.getUserData(KEY)!! @JvmStatic val NewProjectWizardStep.buildSystemProperty get() = buildSystemData.buildSystemProperty @JvmStatic var NewProjectWizardStep.buildSystem get() = buildSystemData.buildSystem; set(it) { buildSystemData.buildSystem = it } } }
plugins/groovy/src/org/jetbrains/plugins/groovy/config/wizard/BuildSystemGroovyNewProjectWizardData.kt
3887300414
// 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.evaluate import com.intellij.debugger.SourcePosition import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.evaluation.EvaluateException import com.intellij.debugger.engine.evaluation.EvaluateExceptionUtil import com.intellij.debugger.engine.evaluation.EvaluationContextImpl import com.intellij.debugger.engine.evaluation.expression.* import com.intellij.debugger.engine.jdi.StackFrameProxy import com.intellij.openapi.application.ReadAction import com.intellij.openapi.diagnostic.Attachment import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.DumbService import com.intellij.psi.PsiElement import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.sun.jdi.* import com.sun.jdi.Value import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import org.jetbrains.eval4j.* import org.jetbrains.eval4j.jdi.JDIEval import org.jetbrains.eval4j.jdi.asJdiValue import org.jetbrains.eval4j.jdi.asValue import org.jetbrains.eval4j.jdi.makeInitialFrame import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.base.util.caching.ConcurrentFactoryCache import org.jetbrains.kotlin.idea.core.util.analyzeInlinedFunctions import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.CoroutineStackFrameProxyImpl import org.jetbrains.kotlin.idea.debugger.evaluate.EvaluationStatus.EvaluationContextLanguage import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.GENERATED_CLASS_NAME import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.isEvaluationEntryPoint import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.* import org.jetbrains.kotlin.idea.debugger.evaluate.compilingEvaluator.ClassLoadingResult import org.jetbrains.kotlin.idea.debugger.evaluate.compilingEvaluator.loadClassesSafely import org.jetbrains.kotlin.idea.debugger.evaluate.variables.EvaluatorValueConverter import org.jetbrains.kotlin.idea.debugger.evaluate.variables.VariableFinder import org.jetbrains.kotlin.idea.debugger.base.util.safeLocation import org.jetbrains.kotlin.idea.debugger.base.util.safeMethod import org.jetbrains.kotlin.idea.debugger.base.util.safeVisibleVariableByName import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.application.attachmentByPsiFile import org.jetbrains.kotlin.idea.util.application.merge import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.psi.KtCodeFragment import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.AnalyzingUtils import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.jvm.AsmTypes import org.jetbrains.org.objectweb.asm.ClassReader import org.jetbrains.org.objectweb.asm.tree.ClassNode import java.util.* import java.util.concurrent.ConcurrentHashMap import org.jetbrains.eval4j.Value as Eval4JValue internal val LOG = Logger.getInstance(KotlinEvaluator::class.java) object KotlinEvaluatorBuilder : EvaluatorBuilder { override fun build(codeFragment: PsiElement, position: SourcePosition?): ExpressionEvaluator { if (codeFragment !is KtCodeFragment) { return EvaluatorBuilderImpl.getInstance().build(codeFragment, position) } val context = codeFragment.context val file = context?.containingFile if (file != null && file !is KtFile) { reportError(codeFragment, position, "Unknown context${codeFragment.context?.javaClass}") evaluationException(KotlinDebuggerEvaluationBundle.message("error.bad.context")) } return ExpressionEvaluatorImpl(KotlinEvaluator(codeFragment, position)) } } class KotlinEvaluator(val codeFragment: KtCodeFragment, private val sourcePosition: SourcePosition?) : Evaluator { override fun evaluate(context: EvaluationContextImpl): Any? { if (codeFragment.text.isEmpty()) { return context.debugProcess.virtualMachineProxy.mirrorOfVoid() } val status = EvaluationStatus() val evaluationType = codeFragment.getUserData(KotlinCodeFragmentFactory.EVALUATION_TYPE) if (evaluationType != null) { status.evaluationType(evaluationType) } val language = runReadAction { when { codeFragment.getCopyableUserData(KtCodeFragment.FAKE_CONTEXT_FOR_JAVA_FILE) != null -> EvaluationContextLanguage.Java codeFragment.context?.language == KotlinLanguage.INSTANCE -> EvaluationContextLanguage.Kotlin else -> EvaluationContextLanguage.Other } } status.contextLanguage(language) try { return evaluateWithStatus(context, status) } finally { status.send() } } private fun evaluateWithStatus(context: EvaluationContextImpl, status: EvaluationStatus): Any? { runReadAction { if (DumbService.getInstance(codeFragment.project).isDumb) { status.error(EvaluationError.DumbMode) evaluationException(KotlinDebuggerEvaluationBundle.message("error.dumb.mode")) } } if (!context.debugProcess.isAttached) { status.error(EvaluationError.DebuggerNotAttached) throw EvaluateExceptionUtil.PROCESS_EXITED } val frameProxy = context.frameProxy ?: run { status.error(EvaluationError.NoFrameProxy) throw EvaluateExceptionUtil.NULL_STACK_FRAME } val operatingThread = context.suspendContext.thread ?: run { status.error(EvaluationError.ThreadNotAvailable) evaluationException(KotlinDebuggerEvaluationBundle.message("error.thread.unavailable")) } if (!operatingThread.isSuspended) { status.error(EvaluationError.ThreadNotSuspended) evaluationException(KotlinDebuggerEvaluationBundle.message("error.thread.not.suspended")) } try { val executionContext = ExecutionContext(context, frameProxy) return evaluateSafe(executionContext, status) } catch (e: CodeFragmentCodegenException) { status.error(EvaluationError.BackendException) evaluationException(e.reason) } catch (e: EvaluateException) { val error = if (e.exceptionFromTargetVM != null) { EvaluationError.ExceptionFromEvaluatedCode } else { EvaluationError.EvaluateException } status.error(error) throw e } catch (e: ProcessCanceledException) { status.error(EvaluationError.ProcessCancelledException) evaluationException(e) } catch (e: Eval4JInterpretingException) { status.error(EvaluationError.InterpretingException) evaluationException(e.cause) } catch (e: Exception) { val isSpecialException = isSpecialException(e) if (isSpecialException) { status.error(EvaluationError.SpecialException) evaluationException(e) } status.error(EvaluationError.GenericException) reportError(codeFragment, sourcePosition, e.message ?: KotlinDebuggerEvaluationBundle.message("error.exception.occurred"), e) val cause = if (e.message != null) ": ${e.message}" else "" evaluationException(KotlinDebuggerEvaluationBundle.message("error.cant.evaluate") + cause) } } private fun evaluateSafe(context: ExecutionContext, status: EvaluationStatus): Any? { val compiledData = getCompiledCodeFragment(context, status) val classLoadingResult = loadClassesSafely(context, compiledData.classes) val classLoaderRef = (classLoadingResult as? ClassLoadingResult.Success)?.classLoader if (classLoadingResult is ClassLoadingResult.Failure) { status.classLoadingFailed() } val result = if (classLoaderRef != null) { try { status.usedEvaluator(EvaluationStatus.EvaluatorType.Bytecode) return evaluateWithCompilation(context, compiledData, classLoaderRef, status) } catch (e: Throwable) { status.compilingEvaluatorFailed() LOG.warn("Compiling evaluator failed: " + e.message, e) status.usedEvaluator(EvaluationStatus.EvaluatorType.Eval4j) evaluateWithEval4J(context, compiledData, classLoaderRef, status) } } else { status.usedEvaluator(EvaluationStatus.EvaluatorType.Eval4j) evaluateWithEval4J(context, compiledData, null, status) } return result.toJdiValue(context, status) } private fun getCompiledCodeFragment(context: ExecutionContext, status: EvaluationStatus): CompiledCodeFragmentData { val contextElement = codeFragment.context ?: return compileCodeFragment(context, status) val cache = runReadAction { CachedValuesManager.getCachedValue(contextElement) { val storage = ConcurrentHashMap<String, CompiledCodeFragmentData>() CachedValueProvider.Result(ConcurrentFactoryCache(storage), PsiModificationTracker.MODIFICATION_COUNT) } } val key = buildString { appendLine(codeFragment.importsToString()) append(codeFragment.text) } return cache.get(key) { compileCodeFragment(context, status) } } private fun compileCodeFragment(context: ExecutionContext, status: EvaluationStatus): CompiledCodeFragmentData { val debugProcess = context.debugProcess var analysisResult = analyze(codeFragment, status, debugProcess) val codeFragmentWasEdited = KotlinCodeFragmentEditor(codeFragment) .withToStringWrapper(analysisResult.bindingContext) .withSuspendFunctionWrapper( analysisResult.bindingContext, context, isCoroutineScopeAvailable(context.frameProxy) ) .editCodeFragment() if (codeFragmentWasEdited) { // Repeat analysis for edited code fragment analysisResult = analyze(codeFragment, status, debugProcess) } analysisResult.illegalSuspendFunCallDiagnostic?.let { reportErrorDiagnostic(it, status) } val (bindingContext, filesToCompile) = runReadAction { val resolutionFacade = getResolutionFacadeForCodeFragment(codeFragment) try { val filesToCompile = if (!CodeFragmentCompiler.useIRFragmentCompiler()) { analyzeInlinedFunctions( resolutionFacade, codeFragment, analyzeOnlyReifiedInlineFunctions = false, analysisResult.bindingContext ).second } else { // The IR Evaluator is sensitive to the analysis order of files in fragment compilation: // The codeFragment must be passed _last_ to analysis such that the result is stacked at // the _bottom_ of the composite analysis result. // // The situation as seen from here is as follows: // 1) `analyzeWithAllCompilerChecks` analyze each individual file passed to it separately. // 2) The individual results are "stacked" on top of each other. // 3) With distinct files, "stacking on top" is equivalent to "side by side" - there is // no overlap in what is analyzed, so the order doesn't matter: the composite analysis // result is just a look-up mechanism for convenience. // 4) Code Fragments perform partial analysis of the context of the fragment, e.g. a // breakpoint in a function causes partial analysis of the surrounding function. // 5) If the surrounding function is _also_ included in the `filesToCompile`, that // function will be analyzed more than once: in particular, fresh symbols will be // allocated anew upon repeated analysis. // 6) Now the order of composition is significant: layering the fragment at the bottom // ensures code that needs a consistent view of the entire function (i.e. psi2ir) // does not mix the fresh, partial view of the function in the fragment analysis with // the complete analysis from the separate analysis of the entire file included in the // compilation. // fun <T> MutableList<T>.moveToLast(element: T) { removeAll(listOf(element)) add(element) } gatherProjectFilesDependedOnByFragment( codeFragment, analysisResult.bindingContext ).toMutableList().apply { moveToLast(codeFragment) } } val analysis = resolutionFacade.analyzeWithAllCompilerChecks(filesToCompile) Pair(analysis.bindingContext, filesToCompile) } catch (e: IllegalArgumentException) { status.error(EvaluationError.ErrorElementOccurred) evaluationException(e.message ?: e.toString()) } } val moduleDescriptor = analysisResult.moduleDescriptor val result = CodeFragmentCompiler(context, status).compile(codeFragment, filesToCompile, bindingContext, moduleDescriptor) if (@Suppress("TestOnlyProblems") LOG_COMPILATIONS) { LOG.debug("Compile bytecode for ${codeFragment.text}") } return createCompiledDataDescriptor(result) } private fun isCoroutineScopeAvailable(frameProxy: StackFrameProxy) = if (frameProxy is CoroutineStackFrameProxyImpl) frameProxy.isCoroutineScopeAvailable() else false private data class ErrorCheckingResult( val bindingContext: BindingContext, val moduleDescriptor: ModuleDescriptor, val files: List<KtFile>, val illegalSuspendFunCallDiagnostic: Diagnostic? ) private fun analyze(codeFragment: KtCodeFragment, status: EvaluationStatus, debugProcess: DebugProcessImpl): ErrorCheckingResult { val result = ReadAction.nonBlocking<Result<ErrorCheckingResult>> { try { Result.success(doAnalyze(codeFragment, status, debugProcess)) } catch (ex: ProcessCanceledException) { throw ex // Restart the action } catch (ex: Exception) { Result.failure(ex) } }.executeSynchronously() return result.getOrThrow() } private fun doAnalyze(codeFragment: KtCodeFragment, status: EvaluationStatus, debugProcess: DebugProcessImpl): ErrorCheckingResult { try { AnalyzingUtils.checkForSyntacticErrors(codeFragment) } catch (e: IllegalArgumentException) { status.error(EvaluationError.ErrorElementOccurred) evaluationException(e.message ?: e.toString()) } val resolutionFacade = getResolutionFacadeForCodeFragment(codeFragment) DebugLabelPropertyDescriptorProvider(codeFragment, debugProcess).supplyDebugLabels() val analysisResult = resolutionFacade.analyzeWithAllCompilerChecks(codeFragment) if (analysisResult.isError()) { status.error(EvaluationError.FrontendException) evaluationException(analysisResult.error) } val bindingContext = analysisResult.bindingContext reportErrorDiagnosticIfAny(status, bindingContext) return ErrorCheckingResult( bindingContext, analysisResult.moduleDescriptor, Collections.singletonList(codeFragment), bindingContext.diagnostics.firstOrNull { it.isIllegalSuspendFunCallInCodeFragment() } ) } private fun reportErrorDiagnosticIfAny(status: EvaluationStatus, bindingContext: BindingContext) = bindingContext.diagnostics .filter { it.factory !in IGNORED_DIAGNOSTICS } .firstOrNull { it.severity == Severity.ERROR && it.psiElement.containingFile == codeFragment } ?.let { reportErrorDiagnostic(it, status) } private fun reportErrorDiagnostic(diagnostic: Diagnostic, status: EvaluationStatus) { status.error(EvaluationError.ErrorsInCode) evaluationException(DefaultErrorMessages.render(diagnostic)) } private fun Diagnostic.isIllegalSuspendFunCallInCodeFragment() = severity == Severity.ERROR && psiElement.containingFile == codeFragment && factory == Errors.ILLEGAL_SUSPEND_FUNCTION_CALL private fun evaluateWithCompilation( context: ExecutionContext, compiledData: CompiledCodeFragmentData, classLoader: ClassLoaderReference, status: EvaluationStatus ): Value? { return runEvaluation(context, compiledData, classLoader, status) { args -> val mainClassType = context.findClass(GENERATED_CLASS_NAME, classLoader) as? ClassType ?: error("Can not find class \"$GENERATED_CLASS_NAME\"") val mainMethod = mainClassType.methods().single { isEvaluationEntryPoint(it.name()) } val returnValue = context.invokeMethod(mainClassType, mainMethod, args) EvaluatorValueConverter.unref(returnValue) } } private fun evaluateWithEval4J( context: ExecutionContext, compiledData: CompiledCodeFragmentData, classLoader: ClassLoaderReference?, status: EvaluationStatus ): InterpreterResult { val mainClassBytecode = compiledData.mainClass.bytes val mainClassAsmNode = ClassNode().apply { ClassReader(mainClassBytecode).accept(this, 0) } val mainMethod = mainClassAsmNode.methods.first { it.isEvaluationEntryPoint } return runEvaluation(context, compiledData, classLoader ?: context.evaluationContext.classLoader, status) { args -> val vm = context.vm.virtualMachine val thread = context.suspendContext.thread?.threadReference?.takeIf { it.isSuspended } ?: error("Can not find a thread to run evaluation on") val eval = object : JDIEval(vm, classLoader, thread, context.invokePolicy) { override fun jdiInvokeStaticMethod(type: ClassType, method: Method, args: List<Value?>, invokePolicy: Int): Value? { return context.invokeMethod(type, method, args) } override fun jdiInvokeStaticMethod(type: InterfaceType, method: Method, args: List<Value?>, invokePolicy: Int): Value? { return context.invokeMethod(type, method, args) } override fun jdiInvokeMethod(obj: ObjectReference, method: Method, args: List<Value?>, policy: Int): Value? { return context.invokeMethod(obj, method, args, ObjectReference.INVOKE_NONVIRTUAL) } } interpreterLoop(mainMethod, makeInitialFrame(mainMethod, args.map { it.asValue() }), eval) } } private fun <T> runEvaluation( context: ExecutionContext, compiledData: CompiledCodeFragmentData, classLoader: ClassLoaderReference?, status: EvaluationStatus, block: (List<Value?>) -> T ): T { // Preload additional classes compiledData.classes .filter { !it.isMainClass } .forEach { context.findClass(it.className, classLoader) } for (parameterType in compiledData.mainMethodSignature.parameterTypes) { context.findClass(parameterType, classLoader) } val variableFinder = VariableFinder(context) val args = calculateMainMethodCallArguments(variableFinder, compiledData, status) val result = block(args) for (wrapper in variableFinder.refWrappers) { updateLocalVariableValue(variableFinder.evaluatorValueConverter, wrapper) } return result } private fun updateLocalVariableValue(converter: EvaluatorValueConverter, ref: VariableFinder.RefWrapper) { val frameProxy = converter.context.frameProxy val newValue = EvaluatorValueConverter.unref(ref.wrapper) val variable = frameProxy.safeVisibleVariableByName(ref.localVariableName) if (variable != null) { try { frameProxy.setValue(variable, newValue) } catch (e: InvalidTypeException) { LOG.error("Cannot update local variable value: expected type ${variable.type}, actual type ${newValue?.type()}", e) } } else if (frameProxy is CoroutineStackFrameProxyImpl) { frameProxy.updateSpilledVariableValue(ref.localVariableName, newValue) } } private fun calculateMainMethodCallArguments( variableFinder: VariableFinder, compiledData: CompiledCodeFragmentData, status: EvaluationStatus ): List<Value?> { val asmValueParameters = compiledData.mainMethodSignature.parameterTypes val valueParameters = compiledData.parameters require(asmValueParameters.size == valueParameters.size) val args = valueParameters.zip(asmValueParameters) return args.map { (parameter, asmType) -> val result = variableFinder.find(parameter, asmType) if (result == null) { val name = parameter.debugString val frameProxy = variableFinder.context.frameProxy fun isInsideDefaultInterfaceMethod(): Boolean { val method = frameProxy.safeLocation()?.safeMethod() ?: return false val desc = method.signature() return method.name().endsWith("\$default") && DEFAULT_METHOD_MARKERS.any { desc.contains("I${it.descriptor})") } } if (parameter.kind == CodeFragmentParameter.Kind.COROUTINE_CONTEXT) { status.error(EvaluationError.CoroutineContextUnavailable) evaluationException(KotlinDebuggerEvaluationBundle.message("error.coroutine.context.unavailable")) } else if (parameter in compiledData.crossingBounds) { status.error(EvaluationError.ParameterNotCaptured) evaluationException(KotlinDebuggerEvaluationBundle.message("error.not.captured", name)) } else if (parameter.kind == CodeFragmentParameter.Kind.FIELD_VAR) { status.error(EvaluationError.BackingFieldNotFound) evaluationException(KotlinDebuggerEvaluationBundle.message("error.cant.find.backing.field", parameter.name)) } else if (parameter.kind == CodeFragmentParameter.Kind.ORDINARY && isInsideDefaultInterfaceMethod()) { status.error(EvaluationError.InsideDefaultMethod) evaluationException(KotlinDebuggerEvaluationBundle.message("error.parameter.evaluation.default.methods")) } else if (parameter.kind == CodeFragmentParameter.Kind.ORDINARY && frameProxy is CoroutineStackFrameProxyImpl) { status.error(EvaluationError.OptimisedVariable) evaluationException(KotlinDebuggerEvaluationBundle.message("error.variable.was.optimised")) } else { status.error(EvaluationError.CannotFindVariable) evaluationException(KotlinDebuggerEvaluationBundle.message("error.cant.find.variable", name, asmType.className)) } } result.value } } override fun getModifier() = null companion object { @get:TestOnly @get:ApiStatus.Internal var LOG_COMPILATIONS: Boolean = false internal val IGNORED_DIAGNOSTICS: Set<DiagnosticFactory<*>> = Errors.INVISIBLE_REFERENCE_DIAGNOSTICS + setOf( Errors.OPT_IN_USAGE_ERROR, Errors.MISSING_DEPENDENCY_SUPERCLASS, Errors.IR_WITH_UNSTABLE_ABI_COMPILED_CLASS, Errors.FIR_COMPILED_CLASS, Errors.ILLEGAL_SUSPEND_FUNCTION_CALL ) private val DEFAULT_METHOD_MARKERS = listOf(AsmTypes.OBJECT_TYPE, AsmTypes.DEFAULT_CONSTRUCTOR_MARKER) private fun InterpreterResult.toJdiValue(context: ExecutionContext, status: EvaluationStatus): Value? { val jdiValue = when (this) { is ValueReturned -> result is ExceptionThrown -> { when (this.kind) { ExceptionThrown.ExceptionKind.FROM_EVALUATED_CODE -> { status.error(EvaluationError.ExceptionFromEvaluatedCode) evaluationException(InvocationException(this.exception.value as ObjectReference)) } ExceptionThrown.ExceptionKind.BROKEN_CODE -> throw exception.value as Throwable else -> { status.error(EvaluationError.Eval4JUnknownException) evaluationException(exception.toString()) } } } is AbnormalTermination -> { status.error(EvaluationError.Eval4JAbnormalTermination) evaluationException(message) } else -> throw IllegalStateException("Unknown result value produced by eval4j") } val sharedVar = if ((jdiValue is AbstractValue<*>)) getValueIfSharedVar(jdiValue) else null return sharedVar?.value ?: jdiValue.asJdiValue(context.vm.virtualMachine, jdiValue.asmType) } private fun getValueIfSharedVar(value: Eval4JValue): VariableFinder.Result? { val obj = value.obj(value.asmType) as? ObjectReference ?: return null return VariableFinder.Result(EvaluatorValueConverter.unref(obj)) } } } private fun isSpecialException(th: Throwable): Boolean { return when (th) { is ClassNotPreparedException, is InternalException, is AbsentInformationException, is ClassNotLoadedException, is IncompatibleThreadStateException, is InconsistentDebugInfoException, is ObjectCollectedException, is VMDisconnectedException -> true else -> false } } private fun reportError(codeFragment: KtCodeFragment, position: SourcePosition?, message: String, throwable: Throwable? = null) { runReadAction { val contextFile = codeFragment.context?.containingFile val attachments = listOfNotNull( attachmentByPsiFile(contextFile), attachmentByPsiFile(codeFragment), Attachment("breakpoint.info", "Position: " + position?.run { "${file.name}:$line" }), Attachment("context.info", runReadAction { codeFragment.context?.text ?: "null" }) ) val decapitalizedMessage = message.replaceFirstChar { it.lowercase(Locale.getDefault()) } LOG.error( "Cannot evaluate a code fragment of type ${codeFragment::class.java}: $decapitalizedMessage", throwable, attachments.merge() ) } } fun createCompiledDataDescriptor(result: CodeFragmentCompiler.CompilationResult): CompiledCodeFragmentData { val localFunctionSuffixes = result.localFunctionSuffixes val dumbParameters = ArrayList<CodeFragmentParameter.Dumb>(result.parameterInfo.parameters.size) for (parameter in result.parameterInfo.parameters) { val dumb = parameter.dumb if (dumb.kind == CodeFragmentParameter.Kind.LOCAL_FUNCTION) { val suffix = localFunctionSuffixes[dumb] if (suffix != null) { dumbParameters += dumb.copy(name = dumb.name + suffix) continue } } dumbParameters += dumb } return CompiledCodeFragmentData( result.classes, dumbParameters, result.parameterInfo.crossingBounds, result.mainMethodSignature ) } internal fun evaluationException(msg: String): Nothing = throw EvaluateExceptionUtil.createEvaluateException(msg) internal fun evaluationException(e: Throwable): Nothing = throw EvaluateExceptionUtil.createEvaluateException(e) internal fun getResolutionFacadeForCodeFragment(codeFragment: KtCodeFragment): ResolutionFacade { val filesToAnalyze = listOf(codeFragment) val kotlinCacheService = KotlinCacheService.getInstance(codeFragment.project) return kotlinCacheService.getResolutionFacadeWithForcedPlatform(filesToAnalyze, JvmPlatforms.unspecifiedJvmPlatform) }
plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinEvaluatorBuilder.kt
2452083558
@file:JvmName("SearchFragment") // ANALYTICS package org.mtransit.android.ui.search import android.content.Context import android.location.Location import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import androidx.core.os.bundleOf import androidx.core.view.isVisible import androidx.fragment.app.viewModels import dagger.hilt.android.AndroidEntryPoint import org.mtransit.android.R import org.mtransit.android.common.repository.LocalPreferenceRepository import org.mtransit.android.commons.KeyboardUtils.Companion.hideKeyboard import org.mtransit.android.commons.ToastUtils import org.mtransit.android.data.DataSourceType import org.mtransit.android.data.POIArrayAdapter import org.mtransit.android.data.POIArrayAdapter.TypeHeaderButtonsClickListener import org.mtransit.android.databinding.FragmentSearchBinding import org.mtransit.android.datasource.DataSourcesRepository import org.mtransit.android.datasource.POIRepository import org.mtransit.android.provider.FavoriteManager import org.mtransit.android.provider.sensor.MTSensorManager import org.mtransit.android.task.ServiceUpdateLoader import org.mtransit.android.task.StatusLoader import org.mtransit.android.ui.MTActivityWithLocation import org.mtransit.android.ui.MTActivityWithLocation.UserLocationListener import org.mtransit.android.ui.MainActivity import org.mtransit.android.ui.fragment.ABFragment import org.mtransit.android.ui.view.MTSearchView import org.mtransit.android.ui.view.common.isAttached import org.mtransit.android.ui.view.common.isVisible import javax.inject.Inject @AndroidEntryPoint class SearchFragment : ABFragment(R.layout.fragment_search), UserLocationListener, TypeHeaderButtonsClickListener, OnItemSelectedListener { companion object { private val LOG_TAG = SearchFragment::class.java.simpleName private const val TRACKING_SCREEN_NAME = "Search" @JvmOverloads @JvmStatic fun newInstance( optQuery: String? = null, optTypeIdFilter: Int? = null ): SearchFragment { return SearchFragment().apply { arguments = bundleOf( SearchViewModel.EXTRA_QUERY to (optQuery?.trim() ?: SearchViewModel.EXTRA_QUERY_DEFAULT), SearchViewModel.EXTRA_TYPE_FILTER to optTypeIdFilter, ) } } private const val DEV_QUERY = "MTDEV" } override fun getLogTag(): String = LOG_TAG override fun getScreenName(): String = TRACKING_SCREEN_NAME private val viewModel by viewModels<SearchViewModel>() private val attachedViewModel get() = if (isAttached()) viewModel else null @Inject lateinit var sensorManager: MTSensorManager @Inject lateinit var dataSourcesRepository: DataSourcesRepository @Inject lateinit var poiRepository: POIRepository @Inject lateinit var favoriteManager: FavoriteManager @Inject lateinit var statusLoader: StatusLoader @Inject lateinit var serviceUpdateLoader: ServiceUpdateLoader @Inject lateinit var lclPrefRepository: LocalPreferenceRepository private var binding: FragmentSearchBinding? = null private val adapter: POIArrayAdapter by lazy { POIArrayAdapter( this, this.sensorManager, this.dataSourcesRepository, this.poiRepository, this.favoriteManager, this.statusLoader, this.serviceUpdateLoader ).apply { logTag = logTag setOnTypeHeaderButtonsClickListener(this@SearchFragment) setPois(emptyList()) // empty search = no result } } private val typeFilterAdapter: SearchTypeFilterAdapter by lazy { SearchTypeFilterAdapter(requireContext()) } override fun onAttach(context: Context) { super.onAttach(context) this.adapter.setActivity(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding = FragmentSearchBinding.bind(view).apply { listLayout.list.let { listView -> listView.isVisible = adapter.isInitialized adapter.setListView(listView) } typeFilters.apply { onItemSelectedListener = this@SearchFragment adapter = typeFilterAdapter } } viewModel.query.observe(viewLifecycleOwner, { query -> binding?.apply { emptyLayout.isVisible = false // hide by default emptyLayout.emptyText.text = if (query.isNullOrEmpty()) { getString(R.string.search_hint) } else { getString(R.string.search_no_result_for_and_query, query) } if (query.isNullOrEmpty()) { adapter.setPois(emptyList()) // empty search = no result loadingLayout.isVisible = false // hide listLayout.isVisible = false // hide emptyLayout.isVisible = true // show } } }) viewModel.loading.observe(viewLifecycleOwner, { loading -> if (loading) { adapter.clear() // mark not initialized == loading binding?.apply { listLayout.isVisible = false // hide emptyLayout.isVisible = false // hide loadingLayout.isVisible = true // show } } }) viewModel.searchResults.observe(viewLifecycleOwner, { searchResults -> adapter.setPois(searchResults) adapter.updateDistanceNowAsync(viewModel.deviceLocation.value) binding?.apply { loadingLayout.isVisible = false if (searchResults.isNullOrEmpty()) { // SHOW EMPTY listLayout.isVisible = false emptyLayout.isVisible = true } else { // SHOW LIST emptyLayout.isVisible = false listLayout.isVisible = true } } }) viewModel.deviceLocation.observe(viewLifecycleOwner, { deviceLocation -> adapter.setLocation(deviceLocation) }) viewModel.searchableDataSourceTypes.observe(viewLifecycleOwner, { dstList -> typeFilterAdapter.setData(dstList) }) viewModel.typeFilter.observe(viewLifecycleOwner, { dst -> binding?.typeFilters?.apply { setSelection(typeFilterAdapter.getPosition(dst)) isVisible = dst != null } adapter.setShowTypeHeader(if (dst == null) POIArrayAdapter.TYPE_HEADER_MORE else POIArrayAdapter.TYPE_HEADER_NONE) }) } override fun onTypeHeaderButtonClick(buttonId: Int, type: DataSourceType): Boolean { if (buttonId == TypeHeaderButtonsClickListener.BUTTON_MORE) { hideKeyboard(activity, view) viewModel.setTypeFilter(type) return true // handled } return false // not handled } override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { val dst = typeFilterAdapter.getItem(position) viewModel.setTypeFilter(dst) } override fun onNothingSelected(parent: AdapterView<*>?) { // DO NOTHING } override fun onResume() { super.onResume() adapter.onResume(this, viewModel.deviceLocation.value) (activity as? MTActivityWithLocation)?.let { onUserLocationChanged(it.lastLocation) } viewModel.onScreenVisible() } override fun onPause() { super.onPause() adapter.onPause() } override fun onUserLocationChanged(newLocation: Location?) { attachedViewModel?.onDeviceLocationChanged(newLocation) } private var devEnabled: Boolean? = null fun setSearchQuery( query: String?, @Suppress("UNUSED_PARAMETER") alreadyInSearchView: Boolean ) { if (DEV_QUERY == query) { devEnabled = devEnabled != true // flip lclPrefRepository.saveAsync(LocalPreferenceRepository.PREFS_LCL_DEV_MODE_ENABLED, devEnabled) ToastUtils.makeTextAndShowCentered(context, "DEV MODE: $devEnabled") return } viewModel.onNewQuery(query) } override fun isABReady(): Boolean { return searchView != null } override fun isABShowSearchMenuItem(): Boolean { return false } override fun isABCustomViewFocusable(): Boolean { return true } override fun isABCustomViewRequestFocus(): Boolean { return searchHasFocus() } private fun searchHasFocus(): Boolean { return refreshSearchHasFocus() } private fun refreshSearchHasFocus(): Boolean { return searchView?.let { val focus = it.hasFocus() attachedViewModel?.setSearchHasFocus(focus) focus } ?: false } override fun getABCustomView(): View? { return getSearchView() } private var searchView: MTSearchView? = null private fun getSearchView(): MTSearchView? { if (searchView == null) { initSearchView() } return searchView } private fun initSearchView() { val activity = activity ?: return val mainActivity = activity as MainActivity val supportActionBar = mainActivity.supportActionBar val context = if (supportActionBar == null) mainActivity else supportActionBar.themedContext searchView = MTSearchView(mainActivity, context).apply { setQuery(attachedViewModel?.query?.value, false) if (attachedViewModel?.searchHasFocus?.value == false) { clearFocus() } } } override fun onDestroyView() { super.onDestroyView() binding = null } override fun onDestroy() { super.onDestroy() searchView = null // part of the activity } }
src/main/java/org/mtransit/android/ui/search/SearchFragment.kt
2527878012
package com.sqisland.android.espresso.hello import android.app.Activity import android.os.Bundle import android.view.View import android.widget.TextView class MainActivity : Activity() { private lateinit var greetingView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) greetingView = findViewById(R.id.greeting) } fun greet(v: View) { greetingView.setText(R.string.hello) } }
hello-world/app/src/main/java/com/sqisland/android/espresso/hello/MainActivity.kt
1907568346
// 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.collaboration.auth.ui import com.intellij.collaboration.auth.Account import com.intellij.collaboration.auth.AccountDetails import com.intellij.collaboration.ui.SingleValueModel import com.intellij.util.concurrency.annotations.RequiresEdt import org.jetbrains.annotations.Nls import java.awt.Image import javax.swing.Icon interface AccountsDetailsProvider<in A : Account, out D : AccountDetails> { @get:RequiresEdt val loadingStateModel: SingleValueModel<Boolean> @RequiresEdt fun getDetails(account: A): D? @RequiresEdt fun getAvatarImage(account: A): Image? @RequiresEdt @Nls fun getErrorText(account: A): String? @RequiresEdt fun checkErrorRequiresReLogin(account: A): Boolean @RequiresEdt fun reset(account: A) @RequiresEdt fun resetAll() }
platform/collaboration-tools/src/com/intellij/collaboration/auth/ui/AccountsDetailsProvider.kt
3866759820
package test fun b() = "b"
plugins/kotlin/jps/jps-plugin/tests/testData/incremental/withJava/other/accessingFunctionsViaRenamedFileClass/b.kt
3569053116
// WITH_RUNTIME fun test() { val array: IntArray = intArrayOf(0, 1, 2, 3) array.<caret>filter { it > 0 }.singleOrNull() }
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/primitiveArray/filterSingleOrNull.kt
750904804
// FIR_IDENTICAL // FIR_COMPARISON interface Interface { var field: Int } expect class SClass : Interface { override<caret> } // ELEMENT_TEXT: "override var field: Int"
plugins/kotlin/completion/tests/testData/handlers/basic/override/ExpectClassValOverride.kt
3180541781
// 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.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtReturnExpression import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression class AddLabeledReturnInLambdaIntention : SelfTargetingRangeIntention<KtBlockExpression>( KtBlockExpression::class.java, KotlinBundle.lazyMessage("add.labeled.return.to.last.expression.in.a.lambda") ), LowPriorityAction { override fun applicabilityRange(element: KtBlockExpression): TextRange? { if (!isApplicableTo(element)) return null val labelName = element.getParentLambdaLabelName() ?: return null if (labelName == KtTokens.SUSPEND_KEYWORD.value) return null setTextGetter(KotlinBundle.lazyMessage("add.return.at.0", labelName)) return element.statements.lastOrNull()?.textRange } override fun applyTo(element: KtBlockExpression, editor: Editor?) { val labelName = element.getParentLambdaLabelName() ?: return val lastStatement = element.statements.lastOrNull() ?: return val newExpression = KtPsiFactory(element.project).createExpressionByPattern("return@$labelName $0", lastStatement) lastStatement.replace(newExpression) } private fun isApplicableTo(block: KtBlockExpression): Boolean { val lastStatement = block.statements.lastOrNull().takeIf { it !is KtReturnExpression } ?: return false val bindingContext = lastStatement.safeAnalyzeNonSourceRootCode().takeIf { it != BindingContext.EMPTY } ?: return false return lastStatement.isUsedAsExpression(bindingContext) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddLabeledReturnInLambdaIntention.kt
2183382056
fun main() { println("Hello, versioned world!") }
backend.native/tests/link/versioning/hello.kt
482115890
package alraune import vgrechka.* import alraune.Ordering.* import alraune.entity.* import bolone.* import bolone.rp.* import pieces100.* import kotlin.math.max class OrderFilesTab_A2(val pedro: OrderPedro_A2) : EntityPageTemplate.Tab { companion object { val filesTabID = "Files" } var tampering by notNullOnce<OrderFilesTab_Tampering_A2>() var searchFucker by notNullOnce<SearchFucker>() val front_fileItems = mutableListOf<BoFrontFuns.InitOrderFilesPage.FileItem>() override fun id() = filesTabID override fun title() = t("Files", "Файлы") val juan get() = pedro.juan override fun willRender() { tampering = OrderFilesTab_Tampering_A2(this) } override fun addTopRightControls(trc: TopRightControls) { searchFucker = SearchFucker(juan.initialParams, trc) trc.addOrderingSelect() if (editable()) { if (false) { withNewSpaghettiDish( before = tampering.tamperPreparePlusButton, main = { trc.addButton(FA.plus, AlDebugTag.topRightButton).whenDomReady_addOnClick( jsBustOutModal(modalWithContext(composeFileModalContent_a2(juan.toLight(), null, FieldSource.Initial())))) } ) } } } override fun render(): Renderable { val tag = div().with { if (searchFucker.sanitizedSearchString.isNotEmpty()) { oo(div().style(""" margin-bottom: 1rem; padding-right: 0; padding-top: 0.5rem; padding-bottom: 1rem; border-bottom: 3px dashed #9E9E9E;""").with { oo(composeFlex_alignItemsCenter().with { oo(FA.search()) oo(span().add(t("TOTE", "Это результаты поиска")).style("font-weight: bold; margin-left: 0.5em;")) oo(ComposeChevronLink( title = t("TOTE", "Не хочу поиск"), href = makeUrlPart(SpitOrderPage.path, juan.initialParams.copy { it.search.set(null)})) .WithLeftMargin().replaceState()) }) }) } // oo(!object : ComposePaginatedOrderFiles( // req = juan.ept.requestSnapshot, // order = juan.entity, // spitPage = juan.ept.pedro.pageClass()) { // // init { // orderingFrom(juan.initialParams) // } // // override fun renderItem(item: Order_UA_V1.File) = // composeOrderFileItem_a2(item, false, juan.ept) // }) val pageSize = AlConst.pageSize val order = juan.order val orderData = order.data oo(dance(object : ComposePaginatedShit<Order.File>( object : PaginationPussy<Order.File> { override fun pageSize() = pageSize override fun selectItems(offset: Long): List<Order.File> { val ordering = juan.initialParams.ordering.get()!! val files = when (ordering) { NewerFirst -> order.viewBucket().files.reversed() OlderFirst -> order.viewBucket().files } val fromIndex = Math.toIntExact(offset) val toIndex = Math.toIntExact(offset + pageSize) val size = files.size return files.subList(clamp(fromIndex, 0, max(size - 1, 0)), clamp(toIndex, 0, size)) } override fun count() = order.viewBucket().files.size.toLong() }) { override fun initShitGivenItems(items: List<Order.File>) {} override fun renderItem(item: Order.File, index: Int) = composeOrderFileItem_a2(juan.order, item, false, juan.toLight(), tab = this@OrderFilesTab_A2) override fun makePageHref(pageFrom1: Int): String { return makeUrlPart(juan.ept.pedro.pagePath(), GetParams().also {it.page.set(pageFrom1)}, keepCurrentParamsFrom = rctx0.req) } })) } !BoFrontFuns.InitOrderFilesPage( userKind = rctx.maybeUser()?.kind, editable = editable(), orderHandle = juan.order.toHandle().toJsonizable(), bucket = juan.order.viewBucket().name, tabsTopRightContainerDomid = juan.tabsTopRightContainer.attrs.id, reloadURL = juan.ept.reloadUrl(), reloadToFirstPageURL = juan.ept.reloadToFirstPageUrl(), storikanURL = alConfig.storikanUrl, fileItems = front_fileItems) return tag } fun editable() = pedro.canEditParams() } fun doUpdateOrderFile__killme(orderHandle: OrderHandle, viewBucket: String?, fileId: Long, fs: OrderFileFields__killme) { !object : UpdateOrder(orderHandle, "Update order file") { var file by notNullOnce<Order.File>() override fun specificUpdates() { file = order.bucket(postBucket(viewBucket)).fileByID(fileId) populateEntityFromFields(file, fs) file.updatedAt = now } override fun makeOperationData(template: Order.Operation) = new_Order_Operation_File_Update(template, file) } } fun doCreateOrderFile__killme(orderHandle: OrderHandle, viewBucket: String?, fs: OrderFileFields__killme): Long { val fileFormValue = fs.file.value().meat!! val fileId = dbNextSequenceValue(AlConst.orderFileIdSequence) !object : UpdateOrder(orderHandle, shortDescription = "Create order file") { var file by notNullOnce<Order.File>() override fun specificUpdates() { val fileUuid = largeUUID() file = Order.File().fill( id = fileId, createdAt = now, updatedAt = now, uuid = fileUuid, state = Order.File.State.Unknown, title = fs.title.sanitized(), details = fs.details.sanitized(), adminNotes = null, toBeFixed = null, resource = Order.Resource().fill( name = fileFormValue.name, size = fileFormValue.size, downloadUrl = fileFormValue.downloadUrl, secretKeyBase64 = fileFormValue.secretKeyBase64)) val postBucket = postBucket(viewBucket) order.bucket(postBucket).files.add(file) if (postBucket == AlSite.BoloneCustomer.name) { fun addToWriterBucket() = order.bucket(AlSite.BoloneWriter.name).files.add(file) fun checkIsAdmin_addToWriterBucket() { check(isAdmin()) addToWriterBucket() } exhaustive=when (order.state) { Order.State.CustomerDraft -> addToWriterBucket() Order.State.LookingForWriters -> checkIsAdmin_addToWriterBucket() Order.State.WaitingPayment -> checkIsAdmin_addToWriterBucket() Order.State.WaitingAdminApproval -> checkIsAdmin_addToWriterBucket() Order.State.ReturnedToCustomerForFixing -> addToWriterBucket() Order.State.WorkInProgress -> {} } } } override fun makeOperationData(template: Order.Operation) = new_Order_Operation_File_Create(template, file) } return fileId } fun postBucket(viewBucket: String?) = when { rctx0.al.site() == AlSite.BoloneAdmin -> viewBucket!! else -> { check(viewBucket == null) rctx0.al.site().name } } private fun composeFileModalContent_a2(lej: LightEptJuan, fileId: Long?, source: FieldSource): MainAndTieKnots<Renderable, Context1> { return MainAndTieKnots( main = { dance(ComposeModalContent().also { it.title = when { fileId == null -> t("TOTE", "Файл") else -> t("TOTE", "Файл №" + fileId) } it.blueLeftMargin() it.body = composeFileModalBody_a2(source) it.footer = dance(ButtonBarWithTicker() .tickerLocation(Rightness.Left) .addSubmitFormButton(MinimalButtonShit( when { fileId == null -> AlText.create else -> AlText.save }, AlButtonStyle.Primary, freakingServant(postCreateOrUpdateFile(lej, fileId)))) .addCloseModalButton()) }) }, tieKnots = {c1 -> c1.filePicker.shitIntoJsAfterStatusChanged.add {buf, status -> buf.appendln(when (status) { FilePicker.Status.Uploading -> """ ${c1.buttonBars.joinToString(";") {it.jsCodeToSetMeEnabled(false)}} ${jsByIdSingle(c1.titleInput.controlDomid)}.focus()""" else -> """ ${c1.buttonBars.joinToString(";") {it.jsCodeToSetMeEnabled(true)}}""" }) } c1.filePicker.errorBannerDomid = c1.errorBannerDomid } ) } private fun composeFileModalBody_a2(source: FieldSource) = div().with { val fields = useFieldsSkippingAdminOnesIfNecessary(OrderFileFields__killme(), source) oo(fields.file.compose()) oo(fields.title.begin() .also {Context1.get().titleInput = it} .focused() .compose()) oo(fields.details.compose()) // fields.adminNotes.ifUsed {oo(it.compose())} } fun postCreateOrUpdateFile(lej: LightEptJuan, fileId: Long? = null) = fun() { val fs = useFieldsSkippingAdminOnesIfNecessary(OrderFileFields__killme(), FieldSource.Post()) if (anyFieldErrors(fs)) { val swc = withNewContext1(composeFileModalContent_a2(lej, fileId, FieldSource.Post())) btfEval {s -> jsReplaceElement( ComposeModalContent.defaultModalDialogDomid, swc.shit, swc.context.onDomReadyPlusOnShown() )} return } if (fileId == null) { doCreateOrderFile__killme(lej.handle, lej.viewBucket, fs) btfRemoveModalAndProgressyNavigate(lej.reloadToFirstPageUrl, replaceState = true) } else { doUpdateOrderFile__killme(lej.handle, lej.viewBucket, fileId, fs) btfEval(lej.jsReload()) } } private fun composeOrderFileItem_a2(order: Order, file: Order.File, fuckIn: Boolean, lej: LightEptJuan, tab: OrderFilesTab_A2): Renderable { var editTriggerDomid: String? = null var titleBar by once<ooItemTitle>() val tag = div().id(fileItemDomid_a2(file.id)).with { if (fuckIn) { currentTag().className(AlCSS.fuckIn.className) } titleBar = ooItemTitle( title = file.title, tinySubtitle = AlText.numString(file.id), addIcons = {icons-> addDownloadOrderFileIcon(icons, file) if (tab.editable()) { val iconDomid = nextDomid() editTriggerDomid = iconDomid // bustOutModalOnDomidClick(iconDomid, modalWithContext( // composeFileModalContent_a2(lej, file.id, FieldSource.DB(file)))) icons.item(FA.pencil, t("Edit", "Изменить")).id(iconDomid).appendStyle("margin-top: 1px;") } }, belowTitle = div().with { if (isAdmin()) { val iconStyle = "margin-left: 40px; margin-right: 0.5em; color: #616161;" val copies = findFileCopies(file, order) if (copies.isNotEmpty()) { oo(div().with { oo(FA.signIn().style(iconStyle)) oo(span(t("TOTE", "Скопирован в ")).style("font-weight: bold;")) oo(copies.joinToString(", ") {it.display()}) }) } file.copiedFrom?.let {src-> val srcDeleted = order.maybeBucketAndFileByID(src.fileID) == null oo(div().with { oo(FA.filesO().style(iconStyle)) oo(span(t("TOTE", "скопирован из ")).style("font-weight: bold;")) oo(span(src.display()).style(srcDeleted.thenElseEmpty {"text-decoration: line-through;"})) }) } } } ) ooOrderFileItemBody_part1(file) rctx0.somethingDrawn = false if (AlFeatures.markSpecificFilesAsNeedingFix) { file.toBeFixed?.let { oo(div().style("background-color: #fbe9e7; border-radius: 5px; padding: 5px; margin-bottom: 0.5rem; position: relative;").with { oo(DetailsRow().title(t("TOTE", "Что необходимо исправить")).content(it.what).noMarginBottom()) val detailsForAdmin = it.detailsForAdmin if (!detailsForAdmin.isNullOrBlank() && rctx0.al.pretending == AlUserKind.Admin) { oo(div().style("border-top: 2px dashed white; margin-top: 0.5rem; padding-top: 0.5rem;").with { oo(DetailsRow().title(t("TOTE", "Админские заметки на этот счет")).content(detailsForAdmin).noMarginBottom())}) } // run { // Bug menu // val clsPosition = nextJSIdentifier() // val clsIcon = nextJSIdentifier() // val clsIconAdmin = nextJSIdentifier() // oo(rawHtml("""<style> // .$clsPosition { // position: absolute; // right: 5px; // top: 5px; // } // .$clsIcon { // color: #bf360c; // font-size: 150%; // transform: rotate(25deg); // } // .$clsIcon.$clsIconAdmin:hover { // cursor: pointer; // color: #e64a19; // } // </style>""")) // val icon = FA.bug() // exhaustive=when { // isPretendingAdmin() -> ooDropdown(icon.appendClassName("$clsIcon $clsIconAdmin"), containerClass = clsPosition) { // it.item(t("TOTE", "Пофикшено"), FA.checkSquareO) {domid-> // bustOutModalOnDomidClick( // domid = domid, // title = t("TOTE", "Файл №${file.id} считать пофикшеным?"), // composeBody = {composeDescriptionOfEntityToBeOperatedOnInModal(file.title)}, // submitButtonServant = ept.servantHandle(ServeConsiderFileFixed_A2().fill(file)) // ).thunk() // } // it.item(t("TOTE", "Редактировать"), FA.pencil) {domid-> // attachWhatShouldBeFixedModal_a2(domid, file, ept) // } // } // else -> oo(icon.appendClassName("$clsIcon $clsPosition")) // } // } }) } } AlRender2.drawAdminNotes_ifAny_andPretendingAdmin(file.adminNotes) ooOrderFileItemBody_part2(file) } tab.front_fileItems += BoFrontFuns.InitOrderFilesPage.FileItem( id = file.id, file = file, editTriggerDomid = editTriggerDomid, rightIconsContainerDomid = titleBar.rightIconsContainer.attrs.id, fields = new_OrderFileFields( file = FileField.noError(new_FileField_Value( name = file.resource.name, size = file.resource.size, downloadURL = file.resource.downloadUrl, secretKeyBase64 = file.resource.secretKeyBase64)), title = TextField.noError(file.title), details = TextField.noError(file.details)), copiedTo = findFileCopies(file, order)) return tag } fun findFileCopies(file: Order.File, order: Order) = l<Order.File.Reference>{ist-> for (bucket in order.data.buckets) { for (otherFile in bucket.files) { if (otherFile.copiedFrom?.fileID == file.id) { ist += new_Order_File_Reference( bucketName = bucket.name, fileID = otherFile.id) } } } } private fun fileItemDomid_a2(id: Long) = "fileItem-$id" fun doDeleteFile__killme(lej: LightEptJuan, fileId: Long) = { !object : UpdateOrder(lej.handle, "Delete order file") { var file by notNullOnce<Order.File>() override fun specificUpdates() { val bucket = order.bucket(postBucket(lej.viewBucket)) file = bucket.fileByID(fileId) bucket.files.remove(file) } override fun makeOperationData(template: Order.Operation) = new_Order_Operation_File_Delete(template, file) } btfEval(lej.jsReload()) }
alraune/alraune/src/main/java/alraune/OrderFilesTab_A2.kt
1990160212
// 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.internal.statistic.devkit.actions import com.intellij.icons.AllIcons import com.intellij.idea.ActionsBundle import com.intellij.internal.statistic.StatisticsBundle import com.intellij.internal.statistic.devkit.StatisticsDevKitUtil import com.intellij.internal.statistic.eventLog.validator.IntellijSensitiveDataValidator import com.intellij.internal.statistic.eventLog.validator.storage.persistence.EventLogMetadataSettingsPersistence import com.intellij.internal.statistic.eventLog.validator.storage.persistence.EventsSchemePathSettings import com.intellij.internal.statistic.utils.StatisticsRecorderUtil import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.DumbAwareAction import com.intellij.ui.LayeredIcon import com.intellij.ui.components.dialog class ConfigureEventsSchemeFileAction(private var myRecorderId: String = StatisticsDevKitUtil.DEFAULT_RECORDER) : DumbAwareAction(ActionsBundle.message("action.ConfigureEventsSchemeFileAction.text"), ActionsBundle.message("action.ConfigureEventsSchemeFileAction.description"), null) { override fun actionPerformed(e: AnActionEvent) { val project = e.project val configurationModel = EventsSchemeConfigurationModel().reset(myRecorderId) val dialog = dialog( title = "Configure Custom Events Scheme", panel = configurationModel.panel, resizable = true, project = project, ok = { listOfNotNull(configurationModel.validate()) } ) if (!dialog.showAndGet()) return ProgressManager.getInstance().run(object : Task.Backgroundable(project, StatisticsBundle.message("stats.saving.events.scheme.configuration"), false) { override fun run(indicator: ProgressIndicator) { updateSchemeSettings(configurationModel.recorderToSettings) } }) } private fun updateSchemeSettings(recorderToSettings: MutableMap<String, EventsSchemeConfigurationModel.EventsSchemePathSettings>) { val settingsPersistence = EventLogMetadataSettingsPersistence.getInstance() for ((recorder, settings) in recorderToSettings) { val customPath = settings.customPath if (settings.useCustomPath && customPath != null) { settingsPersistence.setPathSettings(recorder, EventsSchemePathSettings(customPath, true)) } else { val oldSettings = settingsPersistence.getPathSettings(recorder) if (oldSettings != null && oldSettings.isUseCustomPath) { settingsPersistence.setPathSettings(recorder, EventsSchemePathSettings(oldSettings.customPath, false)) } } val validator = IntellijSensitiveDataValidator.getInstance(recorder) validator.update() validator.reload() } } override fun update(event: AnActionEvent) { super.update(event) val presentation = event.presentation presentation.isEnabled = StatisticsRecorderUtil.isTestModeEnabled(myRecorderId) val settings = EventLogMetadataSettingsPersistence.getInstance().getPathSettings(myRecorderId) presentation.icon = if (settings != null && settings.isUseCustomPath) customPathConfiguredIcon else AllIcons.General.Settings } companion object { private val customPathConfiguredIcon = LayeredIcon(AllIcons.General.Settings, AllIcons.Nodes.WarningMark) } }
platform/statistics/devkit/src/com/intellij/internal/statistic/devkit/actions/ConfigureEventsSchemeFileAction.kt
2190601009
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.integration.camera2.pipe import android.Manifest import android.hardware.camera2.CameraCharacteristics import android.os.Bundle import android.os.Trace import android.util.Log import android.view.View import androidx.camera.camera2.pipe.CameraId import androidx.camera.camera2.pipe.CameraPipe import kotlinx.coroutines.runBlocking /** * This is the main activity for the CameraPipe test application. */ class CameraPipeActivity : CameraPermissionActivity() { private lateinit var cameraPipe: CameraPipe private lateinit var dataVisualizations: DataVisualizations private lateinit var ui: CameraPipeUi private var lastCameraId: CameraId? = null private var currentCamera: SimpleCamera? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.i("CXCP-App", "Activity onCreate") cameraPipe = (applicationContext as CameraPipeApplication).cameraPipe // This adjusts the UI to make the activity run a a full screen application. configureFullScreenCameraWindow(this) // Inflate the main ui for the camera activity. Trace.beginSection("CXCP-App#inflate") ui = CameraPipeUi.inflate(this) // Configure and wire up basic UI behaviors. ui.disableButton(ui.captureButton) ui.disableButton(ui.infoButton) ui.viewfinderText.visibility = View.VISIBLE ui.switchButton.setOnClickListener { startNextCamera() } Trace.endSection() // TODO: Update this to work with newer versions of the visualizations and to accept // the CameraPipeUi object as a parameter. dataVisualizations = DataVisualizations(this) } override fun onStart() { super.onStart() Log.i("CXCP-App", "Activity onStart") checkPermissionsAndRun( setOf( Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO ) ) { val camera = currentCamera if (camera == null) { startNextCamera() } else { camera.start() } } } override fun onResume() { super.onResume() Log.i("CXCP-App", "Activity onResume") } override fun onPause() { super.onPause() Log.i("CXCP-App", "Activity onPause") } override fun onStop() { super.onStop() Log.i("CXCP-App", "Activity onStop") currentCamera?.stop() } override fun onDestroy() { super.onDestroy() Log.i("CXCP-App", "Activity onDestroy") currentCamera?.close() dataVisualizations.close() } private fun startNextCamera() { Trace.beginSection("CXCP-App#startNextCamera") Trace.beginSection("CXCP-App#stopCamera") var camera = currentCamera camera?.stop() Trace.endSection() Trace.beginSection("CXCP-App#findNextCamera") val cameraId = runBlocking { findNextCamera(lastCameraId) } Trace.endSection() Trace.beginSection("CXCP-App#startCameraGraph") camera = SimpleCamera.create(cameraPipe, cameraId, ui.viewfinder, listOf()) Trace.endSection() currentCamera = camera lastCameraId = cameraId ui.viewfinderText.text = camera.cameraInfoString() camera.start() Trace.endSection() Trace.endSection() } private suspend fun findNextCamera(lastCameraId: CameraId?): CameraId { val cameras: List<CameraId> = cameraPipe.cameras().ids() // By default, open the first back facing camera if no camera was previously configured. if (lastCameraId == null) { return cameras.firstOrNull { cameraPipe.cameras().getMetadata(it)[CameraCharacteristics.LENS_FACING] == CameraCharacteristics.LENS_FACING_BACK } ?: cameras.first() } // If a camera was previously open, select the next camera in the list of all cameras. It is // possible that the list of cameras contains only one camera, in which case this will return // the same camera as "currentCameraId" val lastCameraIndex = cameras.indexOf(lastCameraId) if (cameras.isEmpty() || lastCameraIndex == -1) { Log.e("CXCP-App", "Failed to find matching camera!") return cameras.first() } // When we reach the end of the list of cameras, loop. return cameras[(lastCameraIndex + 1) % cameras.size] } }
camera/integration-tests/camerapipetestapp/src/main/java/androidx/camera/integration/camera2/pipe/CameraPipeActivity.kt
3508748791
package org.thoughtcrime.securesms.color import android.content.Context import android.os.Parcelable import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.core.content.ContextCompat import kotlinx.parcelize.Parcelize import org.thoughtcrime.securesms.R /** * Represents a set of colors to be applied to the foreground and background of a view. * * Supports mixing color ints and color resource ids. */ @Parcelize data class ViewColorSet( val foreground: ViewColor, val background: ViewColor ) : Parcelable { companion object { val PRIMARY = ViewColorSet( foreground = ViewColor.ColorResource(R.color.signal_colorOnPrimary), background = ViewColor.ColorResource(R.color.signal_colorPrimary) ) fun forCustomColor(@ColorInt customColor: Int): ViewColorSet { return ViewColorSet( foreground = ViewColor.ColorResource(R.color.signal_colorOnCustom), background = ViewColor.ColorValue(customColor) ) } } @Parcelize sealed class ViewColor : Parcelable { @ColorInt abstract fun resolve(context: Context): Int @Parcelize data class ColorValue(@ColorInt val colorInt: Int) : ViewColor() { override fun resolve(context: Context): Int { return colorInt } } @Parcelize data class ColorResource(@ColorRes val colorRes: Int) : ViewColor() { override fun resolve(context: Context): Int { return ContextCompat.getColor(context, colorRes) } } } }
app/src/main/java/org/thoughtcrime/securesms/color/ViewColorSet.kt
1757093262
package de.droidcon.berlin2018.di import android.content.Context import com.tickaroo.tikxml.TikXml import com.tickaroo.tikxml.converter.htmlescape.HtmlEscapeStringConverter import com.tickaroo.tikxml.retrofit.TikXmlConverterFactory import dagger.Module import dagger.Provides import de.droidcon.berlin2018.BuildConfig import de.droidcon.berlin2018.schedule.backend.BackendScheduleAdapter import de.droidcon.berlin2018.schedule.backend.DroidconBerlinBackend2018 import de.droidcon.berlin2018.schedule.backend.DroidconBerlinBackendScheduleAdapter2018 import de.droidcon.berlin2018.schedule.backend.data2018.InstantTimeTypeConverter import de.droidcon.berlin2018.schedule.backend.data2018.MyHtmlEscapeConverter import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import okhttp3.logging.HttpLoggingInterceptor.Level import org.threeten.bp.Instant import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory /** * @author Hannes Dorfmann */ @Module open class NetworkModule(context: Context) { private val retrofit: Retrofit private val okHttp: OkHttpClient private val backendAdapter: BackendScheduleAdapter init { val builder = OkHttpClient.Builder() .cache(okhttp3.Cache(context.cacheDir, 48 * 1024 * 1024)) if (BuildConfig.DEBUG) { val logging = HttpLoggingInterceptor() logging.level = Level.HEADERS builder.addInterceptor(logging) } okHttp = builder.build() /* val moshi = Moshi.Builder() .add(HtmlStringTypeAdapter.newFactory()) .add(InstantIsoTypeConverter()) .build() */ retrofit = Retrofit.Builder() .client(okHttp) .baseUrl("https://cfp.droidcon.de") .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory( TikXmlConverterFactory.create( TikXml.Builder() .exceptionOnUnreadXml(false) .addTypeConverter(Instant::class.java, InstantTimeTypeConverter()) .addTypeConverter(String::class.java, MyHtmlEscapeConverter()) // HtmlEscapeStringConverter encode / decode html characters. This class ships as optional dependency .build() ) ) .build() val backend = retrofit.create(DroidconBerlinBackend2018::class.java) backendAdapter = DroidconBerlinBackendScheduleAdapter2018(backend) } @Provides fun provideOkHttp(): OkHttpClient = okHttp @Provides fun provideBackendAdapter(): BackendScheduleAdapter = backendAdapter }
app/src/main/java/de/droidcon/berlin2018/di/NetworkModule.kt
1105296716
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.animation.graphics.vector.compat import android.content.res.Resources import android.content.res.TypedArray import android.util.AttributeSet import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserException internal fun XmlPullParser.isAtEnd(): Boolean = eventType == XmlPullParser.END_DOCUMENT || (depth < 1 && eventType == XmlPullParser.END_TAG) /** * Helper method to seek to the first tag within the VectorDrawable xml asset */ @Throws(XmlPullParserException::class) internal fun XmlPullParser.seekToStartTag(): XmlPullParser { var type = next() while (type != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty loop type = next() } if (type != XmlPullParser.START_TAG) { throw XmlPullParserException("No start tag found") } return this } /** * Assuming that we are at the [XmlPullParser.START_TAG start] of the specified [tag], iterates * though the events until we see a corresponding [XmlPullParser.END_TAG]. */ internal inline fun XmlPullParser.forEachChildOf( tag: String, action: XmlPullParser.() -> Unit ) { next() while (!isAtEnd()) { if (eventType == XmlPullParser.END_TAG && name == tag) { break } action() next() } } internal inline fun <T> AttributeSet.attrs( res: Resources, theme: Resources.Theme?, styleable: IntArray, body: (a: TypedArray) -> T ): T { val a = theme?.obtainStyledAttributes(this, styleable, 0, 0) ?: res.obtainAttributes(this, styleable) try { return body(a) } finally { a.recycle() } }
compose/animation/animation-graphics/src/androidMain/kotlin/androidx/compose/animation/graphics/vector/compat/XmlPullParserUtils.android.kt
3202240237
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.input.pointer import android.content.Context import android.view.MotionEvent import android.view.MotionEvent.ACTION_DOWN import android.view.MotionEvent.ACTION_UP import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.test.TestActivity import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.nhaarman.mockitokotlin2.clearInvocations import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith // Tests that pointer offsets are correct when a pointer is dispatched from Android through // Compose and back into Android and each layer offsets the pointer during dispatch. @MediumTest @RunWith(AndroidJUnit4::class) class PointerInteropFilterAndroidViewOffsetsTest { private lateinit var five: View private val theHitListener: () -> Unit = mock() @get:Rule val rule = createAndroidComposeRule<TestActivity>() @Before fun setup() { rule.activityRule.scenario.onActivity { activity -> // one: Android View that is the touch target, inside // two: Android View with 1x2 padding, inside // three: Compose Box with 2x12 padding, inside // four: Android View with 3x13 padding, inside // five: Android View with 4x14 padding // // With all of the padding, "one" is at 10 x 50 relative to "five" and the tests // dispatch MotionEvents to "five". val one = CustomView(activity).apply { layoutParams = ViewGroup.LayoutParams(1, 1) hitListener = theHitListener } val two = FrameLayout(activity).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) setPadding(1, 11, 0, 0) addView(one) } val four = ComposeView(activity).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) setPadding(3, 13, 0, 0) setContent { with(LocalDensity.current) { // Box is "three" Box( Modifier.padding(start = (2f / density).dp, top = (12f / density).dp) ) { AndroidView({ two }) } } } } five = FrameLayout(activity).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) setPadding(4, 14, 0, 0) addView(four) } activity.setContentView(five) } } @Test fun uiClick_inside_hits() { uiClick(10, 50, true) } @Test fun uiClick_justOutside_misses() { uiClick(9, 50, false) uiClick(10, 49, false) uiClick(11, 50, false) uiClick(10, 51, false) } // Gets reused to should always clean up state. private fun uiClick(x: Int, y: Int, hits: Boolean) { clearInvocations(theHitListener) rule.activityRule.scenario.onActivity { val down = MotionEvent( 0, ACTION_DOWN, 1, 0, arrayOf(PointerProperties(1)), arrayOf(PointerCoords(x.toFloat(), y.toFloat())), five ) val up = MotionEvent( 10, ACTION_UP, 1, 0, arrayOf(PointerProperties(1)), arrayOf(PointerCoords(x.toFloat(), y.toFloat())), five ) five.dispatchTouchEvent(down) five.dispatchTouchEvent(up) } if (hits) { verify(theHitListener, times(2)).invoke() } else { verify(theHitListener, never()).invoke() } } } private class CustomView(context: Context) : View(context) { lateinit var hitListener: () -> Unit override fun onTouchEvent(event: MotionEvent?): Boolean { hitListener() return true } }
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/input/pointer/PointerInteropFilterAndroidViewOffsetsTest.kt
1133515077
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.inspection import android.view.View import android.view.inspector.WindowInspector import androidx.compose.ui.inspection.compose.AndroidComposeViewWrapper import androidx.compose.ui.inspection.compose.convertToParameterGroup import androidx.compose.ui.inspection.compose.flatten import androidx.compose.ui.inspection.framework.flatten import androidx.compose.ui.inspection.inspector.InspectorNode import androidx.compose.ui.inspection.inspector.LayoutInspectorTree import androidx.compose.ui.inspection.inspector.NodeParameterReference import androidx.compose.ui.inspection.proto.StringTable import androidx.compose.ui.inspection.proto.convert import androidx.compose.ui.inspection.proto.toComposableRoot import androidx.compose.ui.inspection.util.ThreadUtils import androidx.compose.ui.unit.IntOffset import androidx.inspection.Connection import androidx.inspection.Inspector import androidx.inspection.InspectorEnvironment import androidx.inspection.InspectorFactory import com.google.protobuf.ByteString import com.google.protobuf.InvalidProtocolBufferException import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.Command import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetAllParametersCommand import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetAllParametersResponse import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetComposablesCommand import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetComposablesResponse import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetParameterDetailsCommand import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetParameterDetailsResponse import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetParametersCommand import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetParametersResponse import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.Response import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.UnknownCommandResponse import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.UpdateSettingsCommand import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.UpdateSettingsResponse private const val LAYOUT_INSPECTION_ID = "layoutinspector.compose.inspection" private const val MAX_RECURSIONS = 2 private const val MAX_ITERABLE_SIZE = 5 // created by java.util.ServiceLoader class ComposeLayoutInspectorFactory : InspectorFactory<ComposeLayoutInspector>(LAYOUT_INSPECTION_ID) { override fun createInspector( connection: Connection, environment: InspectorEnvironment ): ComposeLayoutInspector { return ComposeLayoutInspector(connection, environment) } } class ComposeLayoutInspector( connection: Connection, environment: InspectorEnvironment ) : Inspector(connection) { /** Cache data which allows us to reuse previously queried inspector nodes */ private class CacheData( val rootView: View, val trees: List<CacheTree> ) { /** The cached nodes as a map from node id to InspectorNode */ val lookup: Map<Long, InspectorNode> get() = _lookup ?: trees.flatMap { it.nodes } .flatMap { it.flatten() } .associateBy { it.id } .also { _lookup = it } private var _lookup: Map<Long, InspectorNode>? = null } /** Cache data for a tree of [InspectorNode]s under a [viewParent] */ internal class CacheTree( val viewParent: View, val nodes: List<InspectorNode>, val viewsToSkip: List<Long> ) private val layoutInspectorTree = LayoutInspectorTree() private val recompositionHandler = RecompositionHandler(environment.artTooling()) private var delayParameterExtractions = false // Sidestep threading concerns by only ever accessing cachedNodes on the inspector thread private val inspectorThread = Thread.currentThread() private val _cachedNodes = mutableMapOf<Long, CacheData>() private var cachedGeneration = 0 private var cachedSystemComposablesSkipped = false private var cachedHasAllParameters = false private val cachedNodes: MutableMap<Long, CacheData> get() { check(Thread.currentThread() == inspectorThread) return _cachedNodes } override fun onReceiveCommand(data: ByteArray, callback: CommandCallback) { val command = try { Command.parseFrom(data) } catch (ignored: InvalidProtocolBufferException) { handleUnknownCommand(data, callback) return } when (command.specializedCase) { Command.SpecializedCase.GET_COMPOSABLES_COMMAND -> { handleGetComposablesCommand(command.getComposablesCommand, callback) } Command.SpecializedCase.GET_PARAMETERS_COMMAND -> { handleGetParametersCommand(command.getParametersCommand, callback) } Command.SpecializedCase.GET_ALL_PARAMETERS_COMMAND -> { handleGetAllParametersCommand(command.getAllParametersCommand, callback) } Command.SpecializedCase.GET_PARAMETER_DETAILS_COMMAND -> { handleGetParameterDetailsCommand(command.getParameterDetailsCommand, callback) } Command.SpecializedCase.UPDATE_SETTINGS_COMMAND -> { handleUpdateSettingsCommand(command.updateSettingsCommand, callback) } else -> handleUnknownCommand(data, callback) } } private fun handleUnknownCommand(commandBytes: ByteArray, callback: CommandCallback) { callback.reply { unknownCommandResponse = UnknownCommandResponse.newBuilder().apply { this.commandBytes = ByteString.copyFrom(commandBytes) }.build() } } private fun handleGetComposablesCommand( getComposablesCommand: GetComposablesCommand, callback: CommandCallback ) { val data = getComposableNodes( getComposablesCommand.rootViewId, getComposablesCommand.skipSystemComposables, getComposablesCommand.extractAllParameters || !delayParameterExtractions, getComposablesCommand.generation, getComposablesCommand.generation == 0 ) val location = IntArray(2) data?.rootView?.getLocationOnScreen(location) val windowPos = IntOffset(location[0], location[1]) val stringTable = StringTable() val trees = data?.trees ?: emptyList() val roots = trees.map { it.toComposableRoot(stringTable, windowPos, recompositionHandler) } callback.reply { getComposablesResponse = GetComposablesResponse.newBuilder().apply { addAllStrings(stringTable.toStringEntries()) addAllRoots(roots) }.build() } } private fun handleGetParametersCommand( getParametersCommand: GetParametersCommand, callback: CommandCallback ) { val foundComposable = if (delayParameterExtractions && !cachedHasAllParameters) { getComposableFromAnchor(getParametersCommand.anchorHash) } else { getComposableNodes( getParametersCommand.rootViewId, getParametersCommand.skipSystemComposables, true, getParametersCommand.generation )?.lookup?.get(getParametersCommand.composableId) } val semanticsNode = getCachedComposableNodes( getParametersCommand.rootViewId )?.lookup?.get(getParametersCommand.composableId) callback.reply { getParametersResponse = if (foundComposable != null) { val stringTable = StringTable() GetParametersResponse.newBuilder().apply { parameterGroup = foundComposable.convertToParameterGroup( semanticsNode ?: foundComposable, layoutInspectorTree, getParametersCommand.rootViewId, getParametersCommand.maxRecursions.orElse(MAX_RECURSIONS), getParametersCommand.maxInitialIterableSize.orElse(MAX_ITERABLE_SIZE), stringTable ) addAllStrings(stringTable.toStringEntries()) }.build() } else { GetParametersResponse.getDefaultInstance() } } } private fun handleGetAllParametersCommand( getAllParametersCommand: GetAllParametersCommand, callback: CommandCallback ) { val allComposables = getComposableNodes( getAllParametersCommand.rootViewId, getAllParametersCommand.skipSystemComposables, true, getAllParametersCommand.generation )?.lookup?.values ?: emptyList() callback.reply { val stringTable = StringTable() val parameterGroups = allComposables.map { composable -> composable.convertToParameterGroup( composable, layoutInspectorTree, getAllParametersCommand.rootViewId, getAllParametersCommand.maxRecursions.orElse(MAX_RECURSIONS), getAllParametersCommand.maxInitialIterableSize.orElse(MAX_ITERABLE_SIZE), stringTable ) } getAllParametersResponse = GetAllParametersResponse.newBuilder().apply { rootViewId = getAllParametersCommand.rootViewId addAllParameterGroups(parameterGroups) addAllStrings(stringTable.toStringEntries()) }.build() } } private fun handleGetParameterDetailsCommand( getParameterDetailsCommand: GetParameterDetailsCommand, callback: CommandCallback ) { val reference = NodeParameterReference( getParameterDetailsCommand.reference.composableId, getParameterDetailsCommand.reference.anchorHash, getParameterDetailsCommand.reference.kind.convert(), getParameterDetailsCommand.reference.parameterIndex, getParameterDetailsCommand.reference.compositeIndexList ) val foundComposable = if (delayParameterExtractions && !cachedHasAllParameters) { getComposableFromAnchor(reference.anchorId) } else { getComposableNodes( getParameterDetailsCommand.rootViewId, getParameterDetailsCommand.skipSystemComposables, true, getParameterDetailsCommand.generation )?.lookup?.get(reference.nodeId) } val semanticsNode = getCachedComposableNodes( getParameterDetailsCommand.rootViewId )?.lookup?.get(getParameterDetailsCommand.reference.composableId) val expanded = foundComposable?.let { composable -> layoutInspectorTree.expandParameter( getParameterDetailsCommand.rootViewId, semanticsNode ?: composable, reference, getParameterDetailsCommand.startIndex, getParameterDetailsCommand.maxElements, getParameterDetailsCommand.maxRecursions.orElse(MAX_RECURSIONS), getParameterDetailsCommand.maxInitialIterableSize.orElse(MAX_ITERABLE_SIZE), ) } callback.reply { getParameterDetailsResponse = if (expanded != null) { val stringTable = StringTable() GetParameterDetailsResponse.newBuilder().apply { rootViewId = getParameterDetailsCommand.rootViewId parameter = expanded.convert(stringTable) addAllStrings(stringTable.toStringEntries()) }.build() } else { GetParameterDetailsResponse.getDefaultInstance() } } } private fun handleUpdateSettingsCommand( updateSettingsCommand: UpdateSettingsCommand, callback: CommandCallback ) { recompositionHandler.changeCollectionMode( updateSettingsCommand.includeRecomposeCounts, updateSettingsCommand.keepRecomposeCounts ) delayParameterExtractions = updateSettingsCommand.delayParameterExtractions callback.reply { updateSettingsResponse = UpdateSettingsResponse.newBuilder().apply { canDelayParameterExtractions = true }.build() } } /** * Get all [InspectorNode]s found under the layout tree rooted by [rootViewId]. They will be * mapped with their ID as the key. * * This will return cached data if possible, but may request new data otherwise, blocking the * current thread potentially. */ private fun getComposableNodes( rootViewId: Long, skipSystemComposables: Boolean, includeAllParameters: Boolean, generation: Int, forceRegeneration: Boolean = false ): CacheData? { if (!forceRegeneration && generation == cachedGeneration && skipSystemComposables == cachedSystemComposablesSkipped && (!includeAllParameters || cachedHasAllParameters) ) { return cachedNodes[rootViewId] } val data = ThreadUtils.runOnMainThread { layoutInspectorTree.resetAccumulativeState() layoutInspectorTree.includeAllParameters = includeAllParameters val composeViews = getAndroidComposeViews(rootViewId, skipSystemComposables, generation) val composeViewsByRoot = composeViews.groupBy { it.rootView.uniqueDrawingId } val data = composeViewsByRoot.mapValues { (_, composeViews) -> CacheData( composeViews.first().rootView, composeViews.map { CacheTree(it.viewParent, it.createNodes(), it.viewsToSkip) } ) } layoutInspectorTree.resetAccumulativeState() data }.get() cachedNodes.clear() cachedNodes.putAll(data) cachedGeneration = generation cachedSystemComposablesSkipped = skipSystemComposables cachedHasAllParameters = includeAllParameters return cachedNodes[rootViewId] } /** * Return the cached [InspectorNode]s found under the layout tree rooted by [rootViewId]. */ private fun getCachedComposableNodes(rootViewId: Long): CacheData? = cachedNodes[rootViewId] /** * Find an [InspectorNode] with extracted parameters that represent the composable with the * specified anchor hash. */ private fun getComposableFromAnchor(anchorId: Int): InspectorNode? = ThreadUtils.runOnMainThread { layoutInspectorTree.resetAccumulativeState() layoutInspectorTree.includeAllParameters = false val composeViews = getAndroidComposeViews(-1L, false, 1) composeViews.firstNotNullOfOrNull { it.findParameters(anchorId) } }.get() /** * Get all AndroidComposeView instances found within the layout tree rooted by [rootViewId]. */ private fun getAndroidComposeViews( rootViewId: Long, skipSystemComposables: Boolean, generation: Int ): List<AndroidComposeViewWrapper> { ThreadUtils.assertOnMainThread() val roots = WindowInspector.getGlobalWindowViews() .asSequence() .filter { root -> root.visibility == View.VISIBLE && root.isAttachedToWindow && (generation > 0 || root.uniqueDrawingId == rootViewId) } val wrappers = mutableListOf<AndroidComposeViewWrapper>() roots.forEach { root -> root.flatten().mapNotNullTo(wrappers) { view -> AndroidComposeViewWrapper.tryCreateFor( layoutInspectorTree, root, view, skipSystemComposables ) } } return wrappers } } private fun Inspector.CommandCallback.reply(initResponse: Response.Builder.() -> Unit) { val response = Response.newBuilder() response.initResponse() reply(response.build().toByteArray()) } // Provide default for older version: private fun Int.orElse(defaultValue: Int): Int = if (this == 0) defaultValue else this
compose/ui/ui-inspection/src/main/java/androidx/compose/ui/inspection/ComposeLayoutInspector.kt
2418674934
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation import androidx.benchmark.junit4.BenchmarkRule import androidx.benchmark.junit4.measureRepeated import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.testutils.TestNavigatorProvider import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @LargeTest class NavInflaterBenchmark { @get:Rule val benchmarkRule = BenchmarkRule() private val context = ApplicationProvider.getApplicationContext() as android.content.Context private var navInflater: NavInflater = NavInflater(context, TestNavigatorProvider()) @Test fun inflateSimple() { benchmarkRule.measureRepeated { navInflater.inflate(androidx.navigation.benchmark.test.R.navigation.nav_simple) } } @Test fun inflateSimple10() { benchmarkRule.measureRepeated { navInflater.inflate(androidx.navigation.benchmark.test.R.navigation.nav_simple_10) } } @Test fun inflateSimple50() { benchmarkRule.measureRepeated { navInflater.inflate(androidx.navigation.benchmark.test.R.navigation.nav_simple_50) } } @Test fun inflateSimple100() { benchmarkRule.measureRepeated { navInflater.inflate(androidx.navigation.benchmark.test.R.navigation.nav_simple_100) } } @Test fun inflateDeepLink() { benchmarkRule.measureRepeated { navInflater.inflate(androidx.navigation.benchmark.test.R.navigation.nav_deep_link) } } }
navigation/navigation-benchmark/src/androidTest/java/androidx/navigation/NavInflaterBenchmark.kt
3037206324
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.jetbrains.env.debug.smokeTests import com.jetbrains.env.debug.PythonDebuggerCythonSpeedupsTest import org.junit.runner.RunWith import org.junit.runners.Suite @RunWith(Suite::class) @Suite.SuiteClasses( PythonDebuggerCythonSpeedupsTest::class, PythonDebuggerRunsWithoutErrorsTest::class ) class PythonDebuggerSmokeTestsSuite
python/testSrc/com/jetbrains/env/debug/smokeTests/PythonDebuggerSmokeTestsSuite.kt
536650903
// !DIAGNOSTICS: -UNUSED_PARAMETER expect class Common fun takeCommon(c: Common) { }
plugins/kotlin/idea/tests/testData/mppCreationOfModulesAndServices/common/common.kt
3590410292
// "Create member function 'A.foo'" "true" class A<T>(val n: T) { fun foo(i: Int, s: String): A<T> = throw Exception() } fun test() { val a: A<Int> = A(1).foo(2<caret>) }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createFunction/call/funMissingArgs.kt
253326770
package com.intellij.xdebugger.impl.ui.attach.dialog import com.intellij.ui.SimpleTextAttributes import com.intellij.xdebugger.impl.ui.attach.dialog.extensions.XAttachDialogItemPresentationProvider import org.jetbrains.annotations.Nls class AttachDialogPresentationService { private val providers = XAttachDialogItemPresentationProvider.EP.extensions.sortedBy { it.getPriority() } fun getItemPresentationInfo(item: AttachDialogProcessItem): AttachDialogItemPresentationInfo { val provider = providers.firstOrNull { it.isApplicableFor(item) } ?: throw IllegalStateException("${AttachDialogDefaultItemPresentationProvider::class.java.simpleName} should always be available") return AttachDialogItemPresentationInfo(provider.getProcessExecutableText(item), provider.getProcessExecutableTextAttributes(item), provider.getProcessCommandLineText(item), provider.getProcessCommandLineTextAttributes(item), provider.getIndexedString(item)) } } data class AttachDialogItemPresentationInfo( @Nls val executableText: String, val executableTextAttributes: SimpleTextAttributes?, @Nls val commandLineText: String, val commandLineTextAttributes: SimpleTextAttributes?, val indexedString: String ) class AttachDialogDefaultItemPresentationProvider: XAttachDialogItemPresentationProvider { override fun isApplicableFor(item: AttachDialogProcessItem): Boolean = true override fun getPriority(): Int = Int.MAX_VALUE }
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/attach/dialog/AttachDialogPresentationService.kt
2852151118
fun <caret>x(a: Int): Int { x(1); }
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/ChangeReturnTypeBefore.kt
3425885916
/******************************************************************************* * 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 com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations import com.intellij.buildsystem.model.OperationFailure import com.intellij.buildsystem.model.OperationItem import com.intellij.buildsystem.model.unified.UnifiedCoordinates import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.openapi.application.readAction import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineProjectModuleOperationProvider import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyOperationMetadata import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageIdentifier import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion import com.jetbrains.packagesearch.intellij.plugin.util.logDebug import com.jetbrains.packagesearch.intellij.plugin.util.logTrace import com.jetbrains.packagesearch.intellij.plugin.util.nullIfBlank internal class ModuleOperationExecutor { private val operations = mutableListOf<suspend () -> Result>() sealed class Result { companion object { fun from(operation: PackageSearchOperation<*>, operationFailures: List<OperationFailure<out OperationItem>>) = if (operationFailures.isEmpty()) Success(operation) else Failure(operation, operationFailures) } abstract val operation: PackageSearchOperation<*> data class Success(override val operation: PackageSearchOperation<*>) : Result() data class Failure( override val operation: PackageSearchOperation<*>, val operationFailures: List<OperationFailure<out OperationItem>> ) : Result() { val message get() = "${operation.projectModule.name} - " + when (operation) { is PackageSearchOperation.Package.Install -> "${PackageSearchBundle.message("packagesearch.operation.verb.install")} ${operation.model.displayName}" is PackageSearchOperation.Package.Remove -> "${PackageSearchBundle.message("packagesearch.operation.verb.remove")} ${operation.model.displayName}" is PackageSearchOperation.Package.ChangeInstalled -> "${PackageSearchBundle.message("packagesearch.operation.verb.change")} ${operation.model.displayName}" is PackageSearchOperation.Repository.Install -> "${PackageSearchBundle.message("packagesearch.operation.verb.install")} ${operation.model.displayName}" is PackageSearchOperation.Repository.Remove -> "${PackageSearchBundle.message("packagesearch.operation.verb.remove")} ${operation.model.displayName}" } } } fun addOperation(operation: PackageSearchOperation<*>) = when (operation) { is PackageSearchOperation.Package.Install -> installPackage(operation) is PackageSearchOperation.Package.Remove -> removePackage(operation) is PackageSearchOperation.Package.ChangeInstalled -> changePackage(operation) is PackageSearchOperation.Repository.Install -> installRepository(operation) is PackageSearchOperation.Repository.Remove -> removeRepository(operation) } fun addOperations(operations: Iterable<PackageSearchOperation<*>>) = operations.forEach { addOperation(it) } private fun installPackage(operation: PackageSearchOperation.Package.Install) { val projectModule = operation.projectModule val operationProvider = CoroutineProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem( projectModule ) val operationMetadata = dependencyOperationMetadataFrom( projectModule = projectModule, dependency = operation.model, newVersion = operation.newVersion, newScope = operation.newScope ) operations.add { logDebug("ModuleOperationExecutor#installPackage()") { "Installing package ${operation.model.displayName} in ${projectModule.name}" } val errors = operationProvider.addDependencyToModule(operationMetadata, projectModule) if (errors.isEmpty()) { PackageSearchEventsLogger.logPackageInstalled( packageIdentifier = operation.model.coordinates.toIdentifier(), packageVersion = operation.newVersion, targetModule = operation.projectModule ) } logTrace("ModuleOperationExecutor#installPackage()") { if (errors.isEmpty()) { "Package ${operation.model.displayName} installed in ${projectModule.name}" } else { "Package ${operation.model.displayName} failed to be installed due to:" + "\n${errors.joinToString("\n") { it.error.stackTraceToString() }}" } } Result.from(operation, errors) } } private fun UnifiedCoordinates.toIdentifier() = PackageIdentifier("$groupId:$artifactId") private fun removePackage(operation: PackageSearchOperation.Package.Remove) { val projectModule = operation.projectModule val operationProvider = CoroutineProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem( projectModule ) val operationMetadata = dependencyOperationMetadataFrom(projectModule, operation.model) operations.add { logDebug("ModuleOperationExecutor#removePackage()") { "Removing package ${operation.model.displayName} from ${projectModule.name}" } val errors = operationProvider.removeDependencyFromModule(operationMetadata, projectModule) if (errors.isEmpty()) { PackageSearchEventsLogger.logPackageRemoved( packageIdentifier = operation.model.coordinates.toIdentifier(), packageVersion = operation.currentVersion, targetModule = operation.projectModule ) } logTrace("ModuleOperationExecutor#removePackage()") { if (errors.isEmpty()) { "Package ${operation.model.displayName} removed from ${projectModule.name}" } else { "Package ${operation.model.displayName} failed to be removed due to:" + "\n${errors.joinToString("\n") { it.error.stackTraceToString() }}" } } Result.from(operation, errors) } } private fun changePackage(operation: PackageSearchOperation.Package.ChangeInstalled) { val projectModule = operation.projectModule val operationProvider = CoroutineProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) val operationMetadata = dependencyOperationMetadataFrom( projectModule = projectModule, dependency = operation.model, newVersion = operation.newVersion, newScope = operation.newScope ) operations.add { logDebug("ModuleOperationExecutor#changePackage()") { "Changing package ${operation.model.displayName} in ${projectModule.name}" } val errors = operationProvider.updateDependencyInModule(operationMetadata, projectModule) if (errors.isEmpty()) { PackageSearchEventsLogger.logPackageUpdated( packageIdentifier = operation.model.coordinates.toIdentifier(), packageFromVersion = operation.currentVersion, packageVersion = operation.newVersion, targetModule = operation.projectModule ) } logTrace("ModuleOperationExecutor#changePackage()") { if (errors.isEmpty()) { "Package ${operation.model.displayName} changed in ${projectModule.name}" } else { "Package ${operation.model.displayName} failed to be changed due to:" + "\n${errors.joinToString("\n") { it.error.stackTraceToString() }}" } } Result.from(operation, errors) } } private fun dependencyOperationMetadataFrom( projectModule: ProjectModule, dependency: UnifiedDependency, newVersion: PackageVersion? = null, newScope: PackageScope? = null ) = DependencyOperationMetadata( module = projectModule, groupId = dependency.coordinates.groupId.nullIfBlank() ?: throw OperationException.InvalidPackage(dependency), artifactId = dependency.coordinates.artifactId.nullIfBlank() ?: throw OperationException.InvalidPackage(dependency), currentVersion = dependency.coordinates.version.nullIfBlank(), currentScope = dependency.scope.nullIfBlank(), newVersion = newVersion?.versionName.nullIfBlank() ?: dependency.coordinates.version.nullIfBlank(), newScope = newScope?.scopeName.nullIfBlank() ?: dependency.scope.nullIfBlank() ) private fun installRepository(operation: PackageSearchOperation.Repository.Install) { val projectModule = operation.projectModule val operationProvider = CoroutineProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem( projectModule ) operations.add { logDebug("ModuleOperationExecutor#installRepository()") { "Installing repository ${operation.model.displayName} in ${projectModule.name}" } val errors = operationProvider.addRepositoryToModule(operation.model, projectModule) if (errors.isEmpty()) { PackageSearchEventsLogger.logRepositoryAdded(operation.model) } logTrace("ModuleOperationExecutor#installRepository()") { if (errors.isEmpty()) { "Repository ${operation.model.displayName} installed in ${projectModule.name}" } else { "Repository ${operation.model.displayName} failed to be installed due to:" + "\n${errors.joinToString("\n") { it.error.stackTraceToString() }}" } } Result.from(operation, errors) } } private fun removeRepository(operation: PackageSearchOperation.Repository.Remove) { val projectModule = operation.projectModule val operationProvider = CoroutineProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem( projectModule ) operations.add { logDebug("ModuleOperationExecutor#removeRepository()") { "Removing repository ${operation.model.displayName} from ${projectModule.name}" } val errors = operationProvider.removeRepositoryFromModule(operation.model, projectModule) if (errors.isEmpty()) { PackageSearchEventsLogger.logRepositoryRemoved(operation.model) } logTrace("ModuleOperationExecutor#removeRepository()") { if (errors.isEmpty()) { "Repository ${operation.model.displayName} removed from ${projectModule.name}" } else { "Repository ${operation.model.displayName} failed to be removed due to:" + "\n${errors.joinToString("\n") { it.error.stackTraceToString() }}" } } Result.from(operation, errors) } } suspend fun execute() = operations.map { it() } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/operations/ModuleOperationExecutor.kt
2475165571
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.stash.ui import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataKey import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.savedPatches.SavedPatchesOperationsGroup import com.intellij.openapi.vcs.changes.savedPatches.SavedPatchesProvider import git4idea.stash.GitStashOperations import git4idea.stash.GitStashTracker import git4idea.ui.StashInfo val STASH_INFO = DataKey.create<List<StashInfo>>("GitStashInfoList") abstract class GitSingleStashAction : DumbAwareAction() { abstract fun perform(project: Project, stashInfo: StashInfo): Boolean override fun update(e: AnActionEvent) { e.presentation.isEnabled = e.project != null && e.getData(STASH_INFO)?.size == 1 e.presentation.isVisible = e.isFromActionToolbar || (e.project != null && e.getData(STASH_INFO) != null) } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun actionPerformed(e: AnActionEvent) { if (perform(e.project!!, e.getRequiredData(STASH_INFO).single())) { e.project!!.serviceIfCreated<GitStashTracker>()?.scheduleRefresh() } } } class GitDropStashAction : GitSingleStashAction() { override fun perform(project: Project, stashInfo: StashInfo): Boolean { return GitStashOperations.dropStashWithConfirmation(project, null, stashInfo) } } class GitPopStashAction : GitSingleStashAction() { override fun perform(project: Project, stashInfo: StashInfo): Boolean { return GitStashOperations.unstash(project, stashInfo, null, true, false) } } class GitApplyStashAction : GitSingleStashAction() { override fun perform(project: Project, stashInfo: StashInfo): Boolean { return GitStashOperations.unstash(project, stashInfo, null, false, false) } } class GitUnstashAsAction : GitSingleStashAction() { override fun perform(project: Project, stashInfo: StashInfo): Boolean { val dialog = GitUnstashAsDialog(project, stashInfo) if (dialog.showAndGet()) { return GitStashOperations.unstash(project, stashInfo, dialog.branch, dialog.popStash, dialog.keepIndex) } return false } } class GitStashOperationsGroup : SavedPatchesOperationsGroup() { override fun isApplicable(patchObject: SavedPatchesProvider.PatchObject<*>): Boolean { return patchObject.data is StashInfo } }
plugins/git4idea/src/git4idea/stash/ui/GitStashActions.kt
3069779988
// 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.codeInspection import com.intellij.codeInsight.CodeInsightBundle import com.intellij.ui.dsl.builder.panel import com.intellij.util.ui.CheckBox class NonAsciiCharactersInspectionFormUi(entry: InspectionProfileEntry) { val panel = panel { row { cell( CheckBox( CodeInsightBundle.message("non.ascii.chars.inspection.option.files.containing.bom.checkbox"), entry, "CHECK_FOR_FILES_CONTAINING_BOM" ) ) } buttonsGroup(CodeInsightBundle.message("non.ascii.chars.inspection.non.ascii.top.label")) { row { cell( CheckBox( CodeInsightBundle.message("non.ascii.chars.inspection.option.characters.in.identifiers.checkbox"), entry, "CHECK_FOR_NOT_ASCII_IDENTIFIER_NAME" ) ) comment(CodeInsightBundle.message("non.ascii.chars.inspection.example.characters.in.identifiers.label")) } row { cell( CheckBox( CodeInsightBundle.message("non.ascii.chars.inspection.option.characters.in.strings.checkbox"), entry, "CHECK_FOR_NOT_ASCII_STRING_LITERAL" ) ) comment(CodeInsightBundle.message("non.ascii.chars.inspection.example.characters.in.strings.label")) } row { cell( CheckBox( CodeInsightBundle.message("non.ascii.chars.inspection.option.characters.in.comments.checkbox"), entry, "CHECK_FOR_NOT_ASCII_COMMENT" ) ) comment(CodeInsightBundle.message("non.ascii.chars.inspection.example.characters.in.comments.label")) } row { cell( CheckBox( CodeInsightBundle.message("non.ascii.chars.inspection.option.characters.in.any.other.word.checkbox"), entry, "CHECK_FOR_NOT_ASCII_IN_ANY_OTHER_WORD" ) ) comment(CodeInsightBundle.message("non.ascii.chars.inspection.example.characters.in.any.other.word.label")) } } buttonsGroup(CodeInsightBundle.message("non.ascii.chars.inspection.mixed.chars.top.label")) { row { cell( CheckBox( CodeInsightBundle.message("non.ascii.chars.inspection.option.mixed.languages.in.identifiers.checkbox"), entry, "CHECK_FOR_DIFFERENT_LANGUAGES_IN_IDENTIFIER_NAME" ) ) comment(CodeInsightBundle.message("non.ascii.chars.inspection.example.mixed.languages.in.identifiers.label")) } row { cell( CheckBox( CodeInsightBundle.message("non.ascii.chars.inspection.option.mixed.languages.in.strings.checkbox"), entry, "CHECK_FOR_DIFFERENT_LANGUAGES_IN_STRING" ) ) comment(CodeInsightBundle.message("non.ascii.chars.inspection.example.mixed.languages.in.string.label")) } row { cell( CheckBox( CodeInsightBundle.message("non.ascii.chars.inspection.option.mixed.languages.in.comments.checkbox"), entry, "CHECK_FOR_DIFFERENT_LANGUAGES_IN_COMMENTS" ) ) comment(CodeInsightBundle.message("non.ascii.chars.inspection.example.mixed.languages.in.comments.label")) } row { cell( CheckBox( CodeInsightBundle.message("non.ascii.chars.inspection.option.mixed.languages.in.any.other.word.checkbox"), entry, "CHECK_FOR_DIFFERENT_LANGUAGES_IN_ANY_OTHER_WORD" ) ) comment(CodeInsightBundle.message("non.ascii.chars.inspection.example.mixed.languages.in.any.other.word.label")) } } } }
platform/lang-impl/src/com/intellij/codeInspection/NonAsciiCharactersInspectionFormUi.kt
4147234233
// 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.codeInliner import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import com.intellij.psi.SmartPsiElementPointer import com.intellij.psi.search.LocalSearchScope import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.isExtensionFunctionType import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.findUsages.ReferencesSearchScopeHelper import org.jetbrains.kotlin.idea.inspections.RedundantLambdaOrAnonymousFunctionInspection import org.jetbrains.kotlin.idea.inspections.RedundantUnitExpressionInspection import org.jetbrains.kotlin.idea.intentions.* import org.jetbrains.kotlin.idea.refactoring.inline.KotlinInlineAnonymousFunctionProcessor import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.ImportInsertHelper import com.intellij.openapi.application.runWriteAction import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.CompileTimeConstantUtils import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.* import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.utils.addIfNotNull import org.jetbrains.kotlin.utils.addToStdlib.safeAs class CodeInliner<TCallElement : KtElement>( private val languageVersionSettings: LanguageVersionSettings, private val usageExpression: KtSimpleNameExpression?, private val bindingContext: BindingContext, private val resolvedCall: ResolvedCall<out CallableDescriptor>, private val callElement: TCallElement, private val inlineSetter: Boolean, codeToInline: CodeToInline ) { private val codeToInline = codeToInline.toMutable() private val project = callElement.project private val psiFactory = KtPsiFactory(project) fun doInline(): KtElement? { val descriptor = resolvedCall.resultingDescriptor val file = callElement.containingKtFile val qualifiedElement = if (callElement is KtExpression) { callElement.getQualifiedExpressionForSelector() ?: callElement.callableReferenceExpressionForReference() ?: callElement } else callElement val assignment = (qualifiedElement as? KtExpression) ?.getAssignmentByLHS() ?.takeIf { it.operationToken == KtTokens.EQ } val callableForParameters = if (assignment != null && descriptor is PropertyDescriptor) descriptor.setter?.takeIf { inlineSetter && it.hasBody() } ?: descriptor else descriptor val elementToBeReplaced = assignment.takeIf { callableForParameters is PropertySetterDescriptor } ?: qualifiedElement val commentSaver = CommentSaver(elementToBeReplaced, saveLineBreaks = true) // if the value to be inlined is not used and has no side effects we may drop it if (codeToInline.mainExpression != null && !codeToInline.alwaysKeepMainExpression && assignment == null && elementToBeReplaced is KtExpression && !elementToBeReplaced.isUsedAsExpression(bindingContext) && !codeToInline.mainExpression.shouldKeepValue(usageCount = 0) && elementToBeReplaced.getStrictParentOfType<KtAnnotationEntry>() == null ) { codeToInline.mainExpression?.getCopyableUserData(CommentHolder.COMMENTS_TO_RESTORE_KEY)?.let { commentHolder -> codeToInline.addExtraComments(CommentHolder(emptyList(), commentHolder.leadingComments + commentHolder.trailingComments)) } codeToInline.mainExpression = null } var receiver = usageExpression?.receiverExpression() receiver?.marked(USER_CODE_KEY) var receiverType = if (receiver != null) bindingContext.getType(receiver) else null if (receiver == null) { val receiverValue = if (descriptor.isExtension) resolvedCall.extensionReceiver else resolvedCall.dispatchReceiver if (receiverValue is ImplicitReceiver) { val resolutionScope = elementToBeReplaced.getResolutionScope(bindingContext, elementToBeReplaced.getResolutionFacade()) receiver = receiverValue.asExpression(resolutionScope, psiFactory) receiverType = receiverValue.type } } receiver?.mark(RECEIVER_VALUE_KEY) if (receiver != null) { for (instanceExpression in codeToInline.collectDescendantsOfType<KtInstanceExpressionWithLabel> { // for this@ClassName we have only option to keep it as is (although it's sometimes incorrect but we have no other options) it is KtThisExpression && !it[CodeToInline.SIDE_RECEIVER_USAGE_KEY] && it.labelQualifier == null || it is KtSuperExpression && it[CodeToInline.FAKE_SUPER_CALL_KEY] }) { codeToInline.replaceExpression(instanceExpression, receiver) } } val introduceValuesForParameters = processValueParameterUsages(callableForParameters) processTypeParameterUsages() val lexicalScopeElement = callElement.parentsWithSelf .takeWhile { it !is KtBlockExpression } .last() as KtElement val lexicalScope = lexicalScopeElement.getResolutionScope(lexicalScopeElement.analyze(BodyResolveMode.PARTIAL_FOR_COMPLETION)) if (elementToBeReplaced is KtSafeQualifiedExpression && receiverType?.isMarkedNullable != false) { wrapCodeForSafeCall(receiver!!, receiverType, elementToBeReplaced) } else if (callElement is KtBinaryExpression && callElement.operationToken == KtTokens.IDENTIFIER) { keepInfixFormIfPossible() } codeToInline.convertToCallableReferenceIfNeeded(elementToBeReplaced) if (elementToBeReplaced is KtExpression) { if (receiver != null) { val thisReplaced = codeToInline.collectDescendantsOfType<KtExpression> { it[RECEIVER_VALUE_KEY] } if (receiver.shouldKeepValue(usageCount = thisReplaced.size)) { codeToInline.introduceValue(receiver, receiverType, thisReplaced, elementToBeReplaced) } } for ((parameter, value, valueType) in introduceValuesForParameters) { val usagesReplaced = codeToInline.collectDescendantsOfType<KtExpression> { it[PARAMETER_VALUE_KEY] == parameter } codeToInline.introduceValue( value, valueType, usagesReplaced, elementToBeReplaced, nameSuggestion = parameter.name.asString() ) } } for (importPath in codeToInline.fqNamesToImport) { val importDescriptor = file.resolveImportReference(importPath.fqName).firstOrNull() ?: continue ImportInsertHelper.getInstance(project).importDescriptor(file, importDescriptor, aliasName = importPath.alias) } codeToInline.extraComments?.restoreComments(elementToBeReplaced) findAndMarkNewDeclarations() val replacementPerformer = when (elementToBeReplaced) { is KtExpression -> { if (descriptor.isInvokeOperator) { val call = elementToBeReplaced.getPossiblyQualifiedCallExpression() val callee = call?.calleeExpression if (callee != null && callee.text != OperatorNameConventions.INVOKE.asString()) { val receiverExpression = (codeToInline.mainExpression as? KtQualifiedExpression)?.receiverExpression when { elementToBeReplaced is KtCallExpression && receiverExpression is KtThisExpression -> receiverExpression.replace(callee) elementToBeReplaced is KtDotQualifiedExpression -> receiverExpression?.replace(psiFactory.createExpressionByPattern("$0.$1", receiverExpression, callee)) } } } ExpressionReplacementPerformer(codeToInline, elementToBeReplaced) } is KtAnnotationEntry -> AnnotationEntryReplacementPerformer(codeToInline, elementToBeReplaced) is KtSuperTypeCallEntry -> SuperTypeCallEntryReplacementPerformer(codeToInline, elementToBeReplaced) else -> { assert(!canBeReplaced(elementToBeReplaced)) error("Unsupported element") } } assert(canBeReplaced(elementToBeReplaced)) return replacementPerformer.doIt(postProcessing = { range -> val newRange = postProcessInsertedCode(range, lexicalScope) if (!newRange.isEmpty) { commentSaver.restore(newRange) } newRange }) } private fun KtElement.callableReferenceExpressionForReference(): KtCallableReferenceExpression? = parent.safeAs<KtCallableReferenceExpression>()?.takeIf { it.callableReference == callElement } private fun KtSimpleNameExpression.receiverExpression(): KtExpression? = getReceiverExpression() ?: parent.safeAs<KtCallableReferenceExpression>()?.receiverExpression private fun MutableCodeToInline.convertToCallableReferenceIfNeeded(elementToBeReplaced: KtElement) { if (elementToBeReplaced !is KtCallableReferenceExpression) return val qualified = mainExpression?.safeAs<KtQualifiedExpression>() ?: return val reference = qualified.callExpression?.calleeExpression ?: qualified.selectorExpression ?: return val callableReference = if (elementToBeReplaced.receiverExpression == null) { psiFactory.createExpressionByPattern("::$0", reference) } else { psiFactory.createExpressionByPattern("$0::$1", qualified.receiverExpression, reference) } codeToInline.replaceExpression(qualified, callableReference) } private fun findAndMarkNewDeclarations() { for (it in codeToInline.statementsBefore) { if (it is KtNamedDeclaration) { it.mark(NEW_DECLARATION_KEY) } } } private fun renameDuplicates( declarations: List<KtNamedDeclaration>, lexicalScope: LexicalScope, endOfScope: Int, ) { val validator = CollectingNameValidator { !it.nameHasConflictsInScope(lexicalScope, languageVersionSettings) } for (declaration in declarations) { val oldName = declaration.name if (oldName != null && oldName.nameHasConflictsInScope(lexicalScope, languageVersionSettings)) { val newName = Fe10KotlinNameSuggester.suggestNameByName(oldName, validator) for (reference in ReferencesSearchScopeHelper.search(declaration, LocalSearchScope(declaration.parent))) { if (reference.element.startOffset < endOfScope) { reference.handleElementRename(newName) } } declaration.nameIdentifier?.replace(psiFactory.createNameIdentifier(newName)) } } } private fun processValueParameterUsages(descriptor: CallableDescriptor): Collection<IntroduceValueForParameter> { val introduceValuesForParameters = ArrayList<IntroduceValueForParameter>() // process parameters in reverse order because default values can use previous parameters for (parameter in descriptor.valueParameters.asReversed()) { val argument = argumentForParameter(parameter, descriptor) ?: continue val expression = argument.expression.apply { if (this is KtCallElement) { insertExplicitTypeArgument() } put(PARAMETER_VALUE_KEY, parameter) } val parameterName = parameter.name val usages = codeToInline.collectDescendantsOfType<KtExpression> { it[CodeToInline.PARAMETER_USAGE_KEY] == parameterName } usages.forEach { val usageArgument = it.parent as? KtValueArgument if (argument.isNamed) { usageArgument?.mark(MAKE_ARGUMENT_NAMED_KEY) } if (argument.isDefaultValue) { usageArgument?.mark(DEFAULT_PARAMETER_VALUE_KEY) } codeToInline.replaceExpression(it, expression.copied()) } if (expression.shouldKeepValue(usageCount = usages.size)) { introduceValuesForParameters.add(IntroduceValueForParameter(parameter, expression, argument.expressionType)) } } return introduceValuesForParameters } private fun KtCallElement.insertExplicitTypeArgument() { if (InsertExplicitTypeArgumentsIntention.isApplicableTo(this, bindingContext)) { InsertExplicitTypeArgumentsIntention.createTypeArguments(this, bindingContext)?.let { typeArgumentList -> clear(USER_CODE_KEY) for (child in children) { child.safeAs<KtElement>()?.mark(USER_CODE_KEY) } addAfter(typeArgumentList, calleeExpression) } } } private data class IntroduceValueForParameter( val parameter: ValueParameterDescriptor, val value: KtExpression, val valueType: KotlinType? ) private fun processTypeParameterUsages() { val typeParameters = resolvedCall.resultingDescriptor.original.typeParameters val callElement = resolvedCall.call.callElement val callExpression = callElement as? KtCallElement val explicitTypeArgs = callExpression?.typeArgumentList?.arguments if (explicitTypeArgs != null && explicitTypeArgs.size != typeParameters.size) return for ((index, typeParameter) in typeParameters.withIndex()) { val parameterName = typeParameter.name val usages = codeToInline.collectDescendantsOfType<KtExpression> { it[CodeToInline.TYPE_PARAMETER_USAGE_KEY] == parameterName } val type = resolvedCall.typeArguments[typeParameter] ?: continue val typeElement = if (explicitTypeArgs != null) { // we use explicit type arguments if available to avoid shortening val explicitArgTypeElement = explicitTypeArgs[index].typeReference?.typeElement ?: continue explicitArgTypeElement.marked(USER_CODE_KEY) } else { psiFactory.createType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type)).typeElement ?: continue } val typeClassifier = type.constructor.declarationDescriptor for (usage in usages) { val parent = usage.parent if (parent is KtClassLiteralExpression && typeClassifier != null) { // for class literal ("X::class") we need type arguments only for kotlin.Array val arguments = if (typeElement is KtUserType && KotlinBuiltIns.isArray(type)) typeElement.typeArgumentList?.text.orEmpty() else "" codeToInline.replaceExpression( usage, psiFactory.createExpression( IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(typeClassifier) + arguments ) ) } else if (parent is KtUserType) { parent.replace(typeElement) } else { //TODO: tests for this? codeToInline.replaceExpression(usage, psiFactory.createExpression(typeElement.text)) } } } } private fun wrapCodeForSafeCall(receiver: KtExpression, receiverType: KotlinType?, expressionToBeReplaced: KtExpression) { if (codeToInline.statementsBefore.isEmpty()) { val qualified = codeToInline.mainExpression as? KtQualifiedExpression if (qualified != null) { if (qualified.receiverExpression[RECEIVER_VALUE_KEY]) { if (qualified is KtSafeQualifiedExpression) return // already safe val selector = qualified.selectorExpression if (selector != null) { codeToInline.mainExpression = psiFactory.createExpressionByPattern("$0?.$1", receiver, selector) return } } } } if (codeToInline.statementsBefore.isEmpty() || expressionToBeReplaced.isUsedAsExpression(bindingContext)) { val thisReplaced = codeToInline.collectDescendantsOfType<KtExpression> { it[RECEIVER_VALUE_KEY] } codeToInline.introduceValue(receiver, receiverType, thisReplaced, expressionToBeReplaced, safeCall = true) } else { codeToInline.mainExpression = psiFactory.buildExpression { appendFixedText("if (") appendExpression(receiver) appendFixedText("!=null) {") with(codeToInline) { appendExpressionsFromCodeToInline(postfixForMainExpression = "\n") } appendFixedText("}") } codeToInline.statementsBefore.clear() } } private fun keepInfixFormIfPossible() { if (codeToInline.statementsBefore.isNotEmpty()) return val dotQualified = codeToInline.mainExpression as? KtDotQualifiedExpression ?: return val receiver = dotQualified.receiverExpression if (!receiver[RECEIVER_VALUE_KEY]) return val call = dotQualified.selectorExpression as? KtCallExpression ?: return val nameExpression = call.calleeExpression as? KtSimpleNameExpression ?: return val argument = call.valueArguments.singleOrNull() ?: return if (argument.isNamed()) return val argumentExpression = argument.getArgumentExpression() ?: return codeToInline.mainExpression = psiFactory.createExpressionByPattern("$0 ${nameExpression.text} $1", receiver, argumentExpression) } private fun KtExpression?.shouldKeepValue(usageCount: Int): Boolean { if (usageCount == 1) return false val sideEffectOnly = usageCount == 0 return when (this) { is KtSimpleNameExpression -> false is KtQualifiedExpression -> receiverExpression.shouldKeepValue(usageCount) || selectorExpression.shouldKeepValue(usageCount) is KtUnaryExpression -> operationToken in setOf(KtTokens.PLUSPLUS, KtTokens.MINUSMINUS) || baseExpression.shouldKeepValue(usageCount) is KtStringTemplateExpression -> entries.any { if (sideEffectOnly) it.expression.shouldKeepValue(usageCount) else it is KtStringTemplateEntryWithExpression } is KtThisExpression, is KtSuperExpression, is KtConstantExpression -> false is KtParenthesizedExpression -> expression.shouldKeepValue(usageCount) is KtArrayAccessExpression -> !sideEffectOnly || arrayExpression.shouldKeepValue(usageCount) || indexExpressions.any { it.shouldKeepValue(usageCount) } is KtBinaryExpression -> !sideEffectOnly || operationToken == KtTokens.IDENTIFIER || left.shouldKeepValue(usageCount) || right.shouldKeepValue(usageCount) is KtIfExpression -> !sideEffectOnly || condition.shouldKeepValue(usageCount) || then.shouldKeepValue(usageCount) || `else`.shouldKeepValue(usageCount) is KtBinaryExpressionWithTypeRHS -> !(sideEffectOnly && left.isNull()) is KtClassLiteralExpression -> false is KtCallableReferenceExpression -> false null -> false else -> true } } private class Argument( val expression: KtExpression, val expressionType: KotlinType?, val isNamed: Boolean = false, val isDefaultValue: Boolean = false ) private fun argumentForParameter(parameter: ValueParameterDescriptor, callableDescriptor: CallableDescriptor): Argument? { if (callableDescriptor is PropertySetterDescriptor) { val valueAssigned = (callElement as? KtExpression) ?.getQualifiedExpressionForSelectorOrThis() ?.getAssignmentByLHS() ?.right ?: return null return Argument(valueAssigned, bindingContext.getType(valueAssigned)) } when (val resolvedArgument = resolvedCall.valueArguments[parameter] ?: return null) { is ExpressionValueArgument -> { val valueArgument = resolvedArgument.valueArgument val expression = valueArgument?.getArgumentExpression() expression?.mark(USER_CODE_KEY) ?: return null val expressionType = bindingContext.getType(expression) val resultExpression = kotlin.run { if (expression !is KtLambdaExpression) return@run null if (valueArgument is LambdaArgument) { expression.mark(WAS_FUNCTION_LITERAL_ARGUMENT_KEY) } if (!parameter.type.isExtensionFunctionType) return@run null expression.functionLiteral.descriptor?.safeAs<FunctionDescriptor>()?.let { descriptor -> LambdaToAnonymousFunctionIntention.convertLambdaToFunction(expression, descriptor) } } ?: expression return Argument(resultExpression, expressionType, isNamed = valueArgument.isNamed()) } is DefaultValueArgument -> { val (defaultValue, parameterUsages) = OptionalParametersHelper.defaultParameterValue(parameter, project) ?: return null for ((param, usages) in parameterUsages) { usages.forEach { it.put(CodeToInline.PARAMETER_USAGE_KEY, param.name) } } val defaultValueCopy = defaultValue.copied() // clean up user data in original defaultValue.forEachDescendantOfType<KtExpression> { it.clear(CodeToInline.PARAMETER_USAGE_KEY) } return Argument(defaultValueCopy, null/*TODO*/, isDefaultValue = true) } is VarargValueArgument -> { val arguments = resolvedArgument.arguments val single = arguments.singleOrNull() if (single?.getSpreadElement() != null) { val expression = single.getArgumentExpression()!!.marked(USER_CODE_KEY) return Argument(expression, bindingContext.getType(expression), isNamed = single.isNamed()) } val elementType = parameter.varargElementType!! val expression = psiFactory.buildExpression { appendFixedText(arrayOfFunctionName(elementType)) appendFixedText("(") for ((i, argument) in arguments.withIndex()) { if (i > 0) appendFixedText(",") if (argument.getSpreadElement() != null) { appendFixedText("*") } appendExpression(argument.getArgumentExpression()!!.marked(USER_CODE_KEY)) } appendFixedText(")") } return Argument(expression, parameter.type, isNamed = single?.isNamed() ?: false) } else -> error("Unknown argument type: $resolvedArgument") } } private fun postProcessInsertedCode(range: PsiChildRange, lexicalScope: LexicalScope?): PsiChildRange { val pointers = range.filterIsInstance<KtElement>().map { it.createSmartPointer() }.toList() if (pointers.isEmpty()) return PsiChildRange.EMPTY lexicalScope?.let { scope -> val declarations = pointers.mapNotNull { pointer -> pointer.element?.takeIf { it[NEW_DECLARATION_KEY] } as? KtNamedDeclaration } if (declarations.isNotEmpty()) { val endOfScope = pointers.last().element?.endOffset ?: error("Can't find the end of the scope") renameDuplicates(declarations, scope, endOfScope) } } for (pointer in pointers) { restoreComments(pointer) introduceNamedArguments(pointer) restoreFunctionLiteralArguments(pointer) //TODO: do this earlier dropArgumentsForDefaultValues(pointer) removeRedundantLambdasAndAnonymousFunctions(pointer) simplifySpreadArrayOfArguments(pointer) removeExplicitTypeArguments(pointer) removeRedundantUnitExpressions(pointer) } val shortenFilter = { element: PsiElement -> if (element[USER_CODE_KEY]) { ShortenReferences.FilterResult.SKIP } else { val thisReceiver = (element as? KtQualifiedExpression)?.receiverExpression as? KtThisExpression if (thisReceiver != null && thisReceiver[USER_CODE_KEY]) // don't remove explicit 'this' coming from user's code ShortenReferences.FilterResult.GO_INSIDE else ShortenReferences.FilterResult.PROCESS } } // can simplify to single call after KTIJ-646 val newElements = pointers.mapNotNull { it.element?.let { element -> ShortenReferences { ShortenReferences.Options(removeThis = true) }.process(element, elementFilter = shortenFilter) } } for (element in newElements) { // clean up user data element.forEachDescendantOfType<KtExpression> { it.clear(CommentHolder.COMMENTS_TO_RESTORE_KEY) it.clear(USER_CODE_KEY) it.clear(CodeToInline.PARAMETER_USAGE_KEY) it.clear(CodeToInline.TYPE_PARAMETER_USAGE_KEY) it.clear(CodeToInline.FAKE_SUPER_CALL_KEY) it.clear(PARAMETER_VALUE_KEY) it.clear(RECEIVER_VALUE_KEY) it.clear(WAS_FUNCTION_LITERAL_ARGUMENT_KEY) it.clear(NEW_DECLARATION_KEY) } element.forEachDescendantOfType<KtValueArgument> { it.clear(MAKE_ARGUMENT_NAMED_KEY) it.clear(DEFAULT_PARAMETER_VALUE_KEY) } } return if (newElements.isEmpty()) PsiChildRange.EMPTY else PsiChildRange(newElements.first(), newElements.last()) } private fun removeRedundantLambdasAndAnonymousFunctions(pointer: SmartPsiElementPointer<KtElement>) { val element = pointer.element ?: return for (function in element.collectDescendantsOfType<KtFunction>().asReversed()) { val call = RedundantLambdaOrAnonymousFunctionInspection.findCallIfApplicableTo(function) if (call != null) { KotlinInlineAnonymousFunctionProcessor.performRefactoring(call, editor = null) } } } private fun restoreComments(pointer: SmartPsiElementPointer<KtElement>) { pointer.element?.forEachDescendantOfType<KtExpression> { it.getCopyableUserData(CommentHolder.COMMENTS_TO_RESTORE_KEY)?.restoreComments(it) } } private fun removeRedundantUnitExpressions(pointer: SmartPsiElementPointer<KtElement>) { pointer.element?.forEachDescendantOfType<KtReferenceExpression> { if (RedundantUnitExpressionInspection.isRedundantUnit(it)) { it.delete() } } } private fun introduceNamedArguments(pointer: SmartPsiElementPointer<KtElement>) { val element = pointer.element ?: return val callsToProcess = LinkedHashSet<KtCallExpression>() element.forEachDescendantOfType<KtValueArgument> { if (it[MAKE_ARGUMENT_NAMED_KEY] && !it.isNamed()) { val callExpression = (it.parent as? KtValueArgumentList)?.parent as? KtCallExpression callsToProcess.addIfNotNull(callExpression) } } for (callExpression in callsToProcess) { val resolvedCall = callExpression.resolveToCall() ?: return if (!resolvedCall.isReallySuccess()) return val argumentsToMakeNamed = callExpression.valueArguments.dropWhile { !it[MAKE_ARGUMENT_NAMED_KEY] } for (argument in argumentsToMakeNamed) { if (argument.isNamed()) continue if (argument is KtLambdaArgument) continue val argumentMatch = resolvedCall.getArgumentMapping(argument) as ArgumentMatch val name = argumentMatch.valueParameter.name //TODO: not always correct for vararg's val newArgument = psiFactory.createArgument(argument.getArgumentExpression()!!, name, argument.getSpreadElement() != null) if (argument[DEFAULT_PARAMETER_VALUE_KEY]) { newArgument.mark(DEFAULT_PARAMETER_VALUE_KEY) } argument.replace(newArgument) } } } private fun dropArgumentsForDefaultValues(pointer: SmartPsiElementPointer<KtElement>) { val result = pointer.element ?: return val project = result.project val newBindingContext = result.analyze() val argumentsToDrop = ArrayList<ValueArgument>() // we drop only those arguments that added to the code from some parameter's default fun canDropArgument(argument: ValueArgument) = (argument as KtValueArgument)[DEFAULT_PARAMETER_VALUE_KEY] result.forEachDescendantOfType<KtCallElement> { callExpression -> val resolvedCall = callExpression.getResolvedCall(newBindingContext) ?: return@forEachDescendantOfType argumentsToDrop.addAll(OptionalParametersHelper.detectArgumentsToDropForDefaults(resolvedCall, project, ::canDropArgument)) } for (argument in argumentsToDrop) { argument as KtValueArgument val argumentList = argument.parent as KtValueArgumentList argumentList.removeArgument(argument) if (argumentList.arguments.isEmpty()) { val callExpression = argumentList.parent as KtCallElement if (callExpression.lambdaArguments.isNotEmpty()) { argumentList.delete() } } } } private fun arrayOfFunctionName(elementType: KotlinType): String { return when { KotlinBuiltIns.isInt(elementType) -> "kotlin.intArrayOf" KotlinBuiltIns.isLong(elementType) -> "kotlin.longArrayOf" KotlinBuiltIns.isShort(elementType) -> "kotlin.shortArrayOf" KotlinBuiltIns.isChar(elementType) -> "kotlin.charArrayOf" KotlinBuiltIns.isBoolean(elementType) -> "kotlin.booleanArrayOf" KotlinBuiltIns.isByte(elementType) -> "kotlin.byteArrayOf" KotlinBuiltIns.isDouble(elementType) -> "kotlin.doubleArrayOf" KotlinBuiltIns.isFloat(elementType) -> "kotlin.floatArrayOf" elementType.isError -> "kotlin.arrayOf" else -> "kotlin.arrayOf<" + IdeDescriptorRenderers.SOURCE_CODE.renderType(elementType) + ">" } } private fun removeExplicitTypeArguments(pointer: SmartPsiElementPointer<KtElement>) { val result = pointer.element ?: return for (typeArgumentList in result.collectDescendantsOfType<KtTypeArgumentList>(canGoInside = { !it[USER_CODE_KEY] }).asReversed()) { if (RemoveExplicitTypeArgumentsIntention.isApplicableTo(typeArgumentList, approximateFlexible = true)) { typeArgumentList.delete() } } } private fun simplifySpreadArrayOfArguments(pointer: SmartPsiElementPointer<KtElement>) { val result = pointer.element ?: return //TODO: test for nested val argumentsToExpand = ArrayList<Pair<KtValueArgument, Collection<KtValueArgument>>>() result.forEachDescendantOfType<KtValueArgument>(canGoInside = { !it[USER_CODE_KEY] }) { argument -> if (argument.getSpreadElement() != null && !argument.isNamed()) { val argumentExpression = argument.getArgumentExpression() ?: return@forEachDescendantOfType val resolvedCall = argumentExpression.resolveToCall() ?: return@forEachDescendantOfType val callExpression = resolvedCall.call.callElement as? KtCallElement ?: return@forEachDescendantOfType if (CompileTimeConstantUtils.isArrayFunctionCall(resolvedCall)) { argumentsToExpand.add(argument to callExpression.valueArgumentList?.arguments.orEmpty()) } } } for ((argument, replacements) in argumentsToExpand) { argument.replaceByMultiple(replacements) } } private fun KtValueArgument.replaceByMultiple(arguments: Collection<KtValueArgument>) { val list = parent as KtValueArgumentList if (arguments.isEmpty()) { list.removeArgument(this) } else { var anchor = this for (argument in arguments) { anchor = list.addArgumentAfter(argument, anchor) } list.removeArgument(this) } } private fun restoreFunctionLiteralArguments(pointer: SmartPsiElementPointer<KtElement>) { val expression = pointer.element ?: return val callExpressions = ArrayList<KtCallExpression>() expression.forEachDescendantOfType<KtExpression>(fun(expr) { if (!expr[WAS_FUNCTION_LITERAL_ARGUMENT_KEY]) return assert(expr.unpackFunctionLiteral() != null) val argument = expr.parent as? KtValueArgument ?: return if (argument is KtLambdaArgument) return val argumentList = argument.parent as? KtValueArgumentList ?: return if (argument != argumentList.arguments.last()) return val callExpression = argumentList.parent as? KtCallExpression ?: return if (callExpression.lambdaArguments.isNotEmpty()) return callExpression.resolveToCall() ?: return callExpressions.add(callExpression) }) callExpressions.forEach { if (it.canMoveLambdaOutsideParentheses()) { it.moveFunctionLiteralOutsideParentheses() } } } private operator fun <T : Any> PsiElement.get(key: Key<T>): T? = getCopyableUserData(key) private operator fun PsiElement.get(key: Key<Unit>): Boolean = getCopyableUserData(key) != null private fun <T : Any> KtElement.clear(key: Key<T>) = putCopyableUserData(key, null) private fun <T : Any> KtElement.put(key: Key<T>, value: T) = putCopyableUserData(key, value) private fun KtElement.mark(key: Key<Unit>) = putCopyableUserData(key, Unit) private fun <T : KtElement> T.marked(key: Key<Unit>): T { putCopyableUserData(key, Unit) return this } companion object { // keys below are used on expressions private val USER_CODE_KEY = Key<Unit>("USER_CODE") private val PARAMETER_VALUE_KEY = Key<ValueParameterDescriptor>("PARAMETER_VALUE") private val RECEIVER_VALUE_KEY = Key<Unit>("RECEIVER_VALUE") private val WAS_FUNCTION_LITERAL_ARGUMENT_KEY = Key<Unit>("WAS_FUNCTION_LITERAL_ARGUMENT") private val NEW_DECLARATION_KEY = Key<Unit>("NEW_DECLARATION") // these keys are used on KtValueArgument private val MAKE_ARGUMENT_NAMED_KEY = Key<Unit>("MAKE_ARGUMENT_NAMED") private val DEFAULT_PARAMETER_VALUE_KEY = Key<Unit>("DEFAULT_PARAMETER_VALUE") fun canBeReplaced(element: KtElement): Boolean = when (element) { is KtExpression, is KtAnnotationEntry, is KtSuperTypeCallEntry -> true else -> false } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/CodeInliner.kt
2342700438
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet") package org.jetbrains.intellij.build.impl.compilation import com.github.luben.zstd.Zstd import com.github.luben.zstd.ZstdDirectBufferCompressingStreamNoFinalizer import com.intellij.diagnostic.telemetry.forkJoinTask import com.intellij.diagnostic.telemetry.use import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.decodeFromStream import okhttp3.* import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody import okio.* import org.jetbrains.intellij.build.TraceManager.spanBuilder import java.nio.ByteBuffer import java.nio.channels.FileChannel import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption import java.util.* import java.util.concurrent.* import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong private val MEDIA_TYPE_JSON = "application/json".toMediaType() internal val READ_OPERATION = EnumSet.of(StandardOpenOption.READ) internal const val MAX_BUFFER_SIZE = 4_000_000 internal fun uploadArchives(reportStatisticValue: (key: String, value: String) -> Unit, config: CompilationCacheUploadConfiguration, metadataJson: String, httpClient: OkHttpClient, items: List<PackAndUploadItem>, bufferPool: DirectFixedSizeByteBufferPool) { val uploadedCount = AtomicInteger() val uploadedBytes = AtomicLong() val reusedCount = AtomicInteger() val reusedBytes = AtomicLong() var fallbackToHeads = false val alreadyUploaded: Set<String> = try { if (config.checkFiles) { spanBuilder("fetch info about already uploaded files").use { HashSet(getFoundAndMissingFiles(metadataJson, config.serverUrl, httpClient).found) } } else { emptySet() } } catch (e: Throwable) { Span.current().recordException(e, Attributes.of( AttributeKey.stringKey("message"), "failed to fetch info about already uploaded files, will fallback to HEAD requests" )) fallbackToHeads = true emptySet() } ForkJoinTask.invokeAll(items.mapNotNull { item -> if (alreadyUploaded.contains(item.name)) { reusedCount.getAndIncrement() reusedBytes.getAndAdd(Files.size(item.archive)) return@mapNotNull null } forkJoinTask(spanBuilder("upload archive").setAttribute("name", item.name).setAttribute("hash", item.hash!!)) { val isUploaded = uploadFile(url = "${config.serverUrl}/$uploadPrefix/${item.name}/${item.hash!!}.jar", file = item.archive, useHead = fallbackToHeads, span = Span.current(), httpClient = httpClient, bufferPool = bufferPool) val size = Files.size(item.archive) if (isUploaded) { uploadedCount.getAndIncrement() uploadedBytes.getAndAdd(size) } else { reusedCount.getAndIncrement() reusedBytes.getAndAdd(size) } } }) Span.current().addEvent("upload complete", Attributes.of( AttributeKey.longKey("reusedParts"), reusedCount.get().toLong(), AttributeKey.longKey("uploadedParts"), uploadedCount.get().toLong(), AttributeKey.longKey("reusedBytes"), reusedBytes.get(), AttributeKey.longKey("uploadedBytes"), uploadedBytes.get(), AttributeKey.longKey("totalBytes"), reusedBytes.get() + uploadedBytes.get(), AttributeKey.longKey("totalCount"), (reusedCount.get() + uploadedCount.get()).toLong(), )) reportStatisticValue("compile-parts:reused:bytes", reusedBytes.get().toString()) reportStatisticValue("compile-parts:reused:count", reusedCount.get().toString()) reportStatisticValue("compile-parts:uploaded:bytes", uploadedBytes.get().toString()) reportStatisticValue("compile-parts:uploaded:count", uploadedCount.get().toString()) reportStatisticValue("compile-parts:total:bytes", (reusedBytes.get() + uploadedBytes.get()).toString()) reportStatisticValue("compile-parts:total:count", (reusedCount.get() + uploadedCount.get()).toString()) } private fun getFoundAndMissingFiles(metadataJson: String, serverUrl: String, client: OkHttpClient): CheckFilesResponse { client.newCall(Request.Builder() .url("$serverUrl/check-files") .post(metadataJson.toRequestBody(MEDIA_TYPE_JSON)) .build()).execute().useSuccessful { return Json.decodeFromStream(it.body.byteStream()) } } // Using ZSTD dictionary doesn't make the difference, even slightly worse (default compression level 3). // That's because in our case we compress a relatively large archive of class files. private fun uploadFile(url: String, file: Path, useHead: Boolean, span: Span, httpClient: OkHttpClient, bufferPool: DirectFixedSizeByteBufferPool): Boolean { if (useHead) { val request = Request.Builder().url(url).head().build() val code = httpClient.newCall(request).execute().use { it.code } when { code == 200 -> { span.addEvent("already exist on server, nothing to upload", Attributes.of( AttributeKey.stringKey("url"), url, )) return false } code != 404 -> { span.addEvent("responded with unexpected", Attributes.of( AttributeKey.longKey("code"), code.toLong(), AttributeKey.stringKey("url"), url, )) } } } val fileSize = Files.size(file) if (Zstd.compressBound(fileSize) <= MAX_BUFFER_SIZE) { compressSmallFile(file = file, fileSize = fileSize, bufferPool = bufferPool, url = url) } else { val request = Request.Builder() .url(url) .put(object : RequestBody() { override fun contentType() = MEDIA_TYPE_BINARY override fun writeTo(sink: BufferedSink) { compressFile(file = file, output = sink, bufferPool = bufferPool) } }) .build() httpClient.newCall(request).execute().useSuccessful { } } return true } private fun compressSmallFile(file: Path, fileSize: Long, bufferPool: DirectFixedSizeByteBufferPool, url: String) { val targetBuffer = bufferPool.allocate() try { var readOffset = 0L val sourceBuffer = bufferPool.allocate() var isSourceBufferReleased = false try { FileChannel.open(file, READ_OPERATION).use { input -> do { readOffset += input.read(sourceBuffer, readOffset) } while (readOffset < fileSize) } sourceBuffer.flip() Zstd.compress(targetBuffer, sourceBuffer, 3, false) targetBuffer.flip() bufferPool.release(sourceBuffer) isSourceBufferReleased = true } finally { if (!isSourceBufferReleased) { bufferPool.release(sourceBuffer) } } val compressedSize = targetBuffer.remaining() val request = Request.Builder() .url(url) .put(object : RequestBody() { override fun contentLength() = compressedSize.toLong() override fun contentType() = MEDIA_TYPE_BINARY override fun writeTo(sink: BufferedSink) { targetBuffer.mark() sink.write(targetBuffer) targetBuffer.reset() } }) .build() httpClient.newCall(request).execute().useSuccessful { } } finally { bufferPool.release(targetBuffer) } } private fun compressFile(file: Path, output: BufferedSink, bufferPool: DirectFixedSizeByteBufferPool) { val targetBuffer = bufferPool.allocate() object : ZstdDirectBufferCompressingStreamNoFinalizer(targetBuffer, 3) { override fun flushBuffer(toFlush: ByteBuffer): ByteBuffer { toFlush.flip() while (toFlush.hasRemaining()) { output.write(toFlush) } toFlush.clear() return toFlush } override fun close() { try { super.close() } finally { bufferPool.release(targetBuffer) } } }.use { compressor -> val sourceBuffer = bufferPool.allocate() try { var offset = 0L FileChannel.open(file, READ_OPERATION).use { input -> val fileSize = input.size() while (offset < fileSize) { val actualBlockSize = (fileSize - offset).toInt() if (sourceBuffer.remaining() > actualBlockSize) { sourceBuffer.limit(sourceBuffer.position() + actualBlockSize) } var readOffset = offset do { readOffset += input.read(sourceBuffer, readOffset) } while (sourceBuffer.hasRemaining()) sourceBuffer.flip() compressor.compress(sourceBuffer) sourceBuffer.clear() offset = readOffset } } } finally { bufferPool.release(sourceBuffer) } } } @Serializable private data class CheckFilesResponse( val found: List<String> = emptyList(), )
platform/build-scripts/src/org/jetbrains/intellij/build/impl/compilation/upload.kt
2085530698
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.dataFlow.inference import com.intellij.codeInsight.Nullability import com.intellij.codeInspection.dataFlow.ContractReturnValue import com.intellij.codeInspection.dataFlow.StandardMethodContract import com.intellij.codeInspection.dataFlow.StandardMethodContract.ValueConstraint import com.intellij.openapi.util.io.DataInputOutputUtilRt.* import com.intellij.util.io.DataExternalizer import com.intellij.util.io.DataInputOutputUtil.readNullable import com.intellij.util.io.DataInputOutputUtil.writeNullable import java.io.DataInput import java.io.DataOutput import java.util.* internal object MethodDataExternalizer : DataExternalizer<Map<Int, MethodData>> { override fun save(out: DataOutput, value: Map<Int, MethodData>?) { writeSeq(out, value!!.toList()) { writeINT(out, it.first); writeMethod(out, it.second) } } override fun read(input: DataInput): Map<Int, MethodData> { return readSeq(input) { readINT(input) to readMethod(input) }.toMap() } private fun writeMethod(out: DataOutput, data: MethodData) { writeNullable(out, data.methodReturn) { writeNullity(out, it) } writeNullable(out, data.purity) { writePurity(out, it) } writeSeq(out, data.contracts) { writeContract(out, it) } writeBitSet(out, data.notNullParameters) writeINT(out, data.bodyStart) writeINT(out, data.bodyEnd) } private fun readMethod(input: DataInput): MethodData { val nullity = readNullable(input) { readNullity(input) } val purity = readNullable(input) { readPurity(input) } val contracts = readSeq(input) { readContract(input) } val notNullParameters = readBitSet(input) return MethodData(nullity, purity, contracts, notNullParameters, readINT(input), readINT(input)) } private fun writeBitSet(out: DataOutput, bitSet: BitSet) { val bytes = bitSet.toByteArray() val size = bytes.size // Write up to 255 bytes, thus up to 2040 bits which is far more than number of allowed Java method parameters assert(size in 0..255) out.writeByte(size) out.write(bytes) } private fun readBitSet(input: DataInput): BitSet { val size = input.readUnsignedByte() val bytes = ByteArray(size) input.readFully(bytes) return BitSet.valueOf(bytes) } private fun writeNullity(out: DataOutput, methodReturn: MethodReturnInferenceResult) { return when (methodReturn) { is MethodReturnInferenceResult.Predefined -> { out.writeByte(0) out.writeByte(methodReturn.value.ordinal) } is MethodReturnInferenceResult.FromDelegate -> { out.writeByte(1) out.writeByte(methodReturn.value.ordinal); writeRanges(out, methodReturn.delegateCalls) } else -> throw IllegalArgumentException(methodReturn.toString()) } } private fun readNullity(input: DataInput): MethodReturnInferenceResult { return when (input.readByte().toInt()) { 0 -> MethodReturnInferenceResult.Predefined(Nullability.values()[input.readByte().toInt()]) else -> MethodReturnInferenceResult.FromDelegate(Nullability.values()[input.readByte().toInt()], readRanges(input)) } } private fun writeRanges(out: DataOutput, ranges: List<ExpressionRange>) { writeSeq(out, ranges) { writeRange(out, it) } } private fun readRanges(input: DataInput) = readSeq(input) { readRange(input) } private fun writeRange(out: DataOutput, range: ExpressionRange) { writeINT(out, range.startOffset) writeINT(out, range.endOffset) } private fun readRange(input: DataInput) = ExpressionRange(readINT(input), readINT(input)) private fun writePurity(out: DataOutput, purity: PurityInferenceResult) { out.writeBoolean(purity.mutatesThis) writeRanges(out, purity.mutatedRefs) writeNullable(out, purity.singleCall) { writeRange(out, it) } } private fun readPurity(input: DataInput): PurityInferenceResult { return PurityInferenceResult(input.readBoolean(), readRanges(input), readNullable(input) { readRange(input) }) } private fun writeContract(out: DataOutput, contract: PreContract) { return when (contract) { is DelegationContract -> { out.writeByte(0) writeRange(out, contract.expression); out.writeBoolean(contract.negated) } is KnownContract -> { out.writeByte(1) writeContractArguments(out, contract.contract.constraints) out.writeByte(contract.contract.returnValue.ordinal()) } is MethodCallContract -> { out.writeByte(2) writeRange(out, contract.call) writeSeq(out, contract.states) { writeContractArguments(out, it) } } is NegatingContract -> { out.writeByte(3) writeContract(out, contract.negated) } is SideEffectFilter -> { out.writeByte(4) writeRanges(out, contract.expressionsToCheck) writeSeq(out, contract.contracts) { writeContract(out, it) } } else -> throw IllegalArgumentException(contract.toString()) } } private fun readContract(input: DataInput): PreContract { return when (input.readByte().toInt()) { 0 -> DelegationContract(readRange(input), input.readBoolean()) 1 -> KnownContract(StandardMethodContract(readContractArguments(input).toTypedArray(), readReturnValue(input))) 2 -> MethodCallContract(readRange(input), readSeq(input) { readContractArguments(input) }) 3 -> NegatingContract(readContract(input)) else -> SideEffectFilter(readRanges(input), readSeq(input) { readContract(input) }) } } private fun writeContractArguments(out: DataOutput, arguments: List<ValueConstraint>) { writeSeq(out, arguments) { out.writeByte(it.ordinal) } } private fun readContractArguments(input: DataInput): MutableList<ValueConstraint> { return readSeq(input) { readValueConstraint(input) } } private fun readValueConstraint(input: DataInput) = ValueConstraint.values()[input.readByte().toInt()] private fun readReturnValue(input: DataInput) = ContractReturnValue.valueOf(input.readByte().toInt()) }
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/MethodDataExternalizer.kt
3190817844
package pl.ches.citybikes.presentation.common.widget import android.content.Context import android.support.v4.widget.NestedScrollView import android.util.AttributeSet import android.view.MotionEvent import android.view.ViewConfiguration /** * @author Michał Seroczyński <michal.seroczynski@gmail.com> */ class FixedNestedScrollView : NestedScrollView { private var slop: Int = 0 private var xDistance: Float = 0.toFloat() private var yDistance: Float = 0.toFloat() private var lastX: Float = 0.toFloat() private var lastY: Float = 0.toFloat() constructor(context: Context) : super(context) { init(context) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(context) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init(context) } private fun init(context: Context) { val config = ViewConfiguration.get(context) slop = config.scaledEdgeSlop } override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { val x = ev.x val y = ev.y when (ev.action) { MotionEvent.ACTION_DOWN -> { xDistance = 0f yDistance = 0f lastX = ev.x lastY = ev.y // This is very important line that fixes computeScroll() } MotionEvent.ACTION_MOVE -> { val curX = ev.x val curY = ev.y xDistance += Math.abs(curX - lastX) yDistance += Math.abs(curY - lastY) lastX = curX lastY = curY if (xDistance > yDistance) { return false } } } return super.onInterceptTouchEvent(ev) } }
app/src/main/kotlin/pl/ches/citybikes/presentation/common/widget/FixedNestedScrollView.kt
412869770
// 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.declarations import com.intellij.codeInsight.editorActions.JoinLinesHandler import com.intellij.ide.DataManager import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import java.io.File abstract class AbstractJoinLinesTest : KotlinLightCodeInsightFixtureTestCase() { @Throws(Exception::class) fun doTest(unused: String) { myFixture.configureByFile(fileName()) val dataContext = DataManager.getInstance().getDataContext(editor.contentComponent) myFixture.project.executeWriteCommand("Join lines") { JoinLinesHandler(null).execute(editor, editor.caretModel.currentCaret, dataContext) } val testFile = testDataFile() val expectedFile = File(testFile.parentFile, testFile.name + ".after") myFixture.checkResultByFile(expectedFile) } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/intentions/declarations/AbstractJoinLinesTest.kt
3470965726
// 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.idea.maven.wizards.archetype import com.intellij.openapi.options.BoundConfigurable import com.intellij.openapi.project.Project import com.intellij.ui.dsl.builder.MutableProperty import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import org.jetbrains.idea.maven.indices.archetype.MavenCatalogManager import org.jetbrains.idea.maven.wizards.MavenWizardBundle class MavenCatalogsConfigurable(private val project: Project) : BoundConfigurable( MavenWizardBundle.message("maven.configurable.archetype.catalog.title"), helpTopic = "reference.settings.project.maven.archetype.catalogs" ) { override fun createPanel() = panel { val catalogsManager = MavenCatalogManager.getInstance() val table = MavenCatalogsTable(project) row { label(MavenWizardBundle.message("maven.configurable.archetype.catalog.label")) } row { cell(table.component) .horizontalAlign(HorizontalAlign.FILL) .verticalAlign(VerticalAlign.FILL) .bind( { table.catalogs }, { _, it -> table.catalogs = it }, MutableProperty( { catalogsManager.getCatalogs(project) }, { catalogsManager.setCatalogs(it) } ) ) }.resizableRow() } }
plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/archetype/MavenCatalogsConfigurable.kt
1939413973
// 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.inspections.blockingCallsDetection import com.intellij.codeInsight.actions.OptimizeImportsProcessor import com.intellij.openapi.components.service import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.parentOfType import org.jetbrains.kotlin.builtins.isSuspendFunctionType import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.formatter.commitAndUnblockDocument import org.jetbrains.kotlin.idea.inspections.collections.isCalling import org.jetbrains.kotlin.idea.intentions.receiverType import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.util.reformatted import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.calls.callUtil.getFirstArgumentExpression import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode internal object CoroutineBlockingCallInspectionUtils { fun isInSuspendLambdaOrFunction(ktElement: KtElement): Boolean { val lambdaArgument = ktElement.parentOfType<KtLambdaArgument>() if (lambdaArgument != null) { val callExpression = lambdaArgument.getStrictParentOfType<KtCallExpression>() ?: return false val call = callExpression.resolveToCall(BodyResolveMode.PARTIAL) ?: return false val parameterForArgument = call.getParameterForArgument(lambdaArgument) ?: return false return parameterForArgument.returnType?.isSuspendFunctionType ?: false } return ktElement.parentOfType<KtNamedFunction>()?.hasModifier(KtTokens.SUSPEND_KEYWORD) ?: false } fun isKotlinxOnClasspath(ktElement: KtElement): Boolean { val module = ModuleUtilCore.findModuleForPsiElement(ktElement) ?: return false val searchScope = GlobalSearchScope.moduleWithLibrariesScope(module) return module.project .service<JavaPsiFacade>() .findClass(DISPATCHERS_FQN, searchScope) != null } fun isInsideFlowChain(resolvedCall: ResolvedCall<*>): Boolean { val descriptor = resolvedCall.resultingDescriptor val isFlowGenerator = descriptor.fqNameOrNull()?.asString()?.startsWith(FLOW_PACKAGE_FQN) ?: false return descriptor.receiverType()?.fqName?.asString() == FLOW_FQN || (descriptor.receiverType() == null && isFlowGenerator) } fun isCalledInsideNonIoContext(resolvedCall: ResolvedCall<*>): Boolean { val callFqn = resolvedCall.resultingDescriptor?.fqNameSafe?.asString() ?: return false if (callFqn != WITH_CONTEXT_FQN) return false return isNonBlockingDispatcher(resolvedCall) } private fun isNonBlockingDispatcher(call: ResolvedCall<out CallableDescriptor>): Boolean { val dispatcherFqnOrNull = call.getFirstArgumentExpression() ?.resolveToCall() ?.resultingDescriptor ?.fqNameSafe?.asString() return dispatcherFqnOrNull != null && dispatcherFqnOrNull != IO_DISPATCHER_FQN } fun postProcessQuickFix(replacedElement: KtElement, project: Project) { val containingKtFile = replacedElement.containingKtFile ShortenReferences.DEFAULT.process(replacedElement.reformatted() as KtElement) OptimizeImportsProcessor(project, containingKtFile).run() containingKtFile.commitAndUnblockDocument() } tailrec fun KtExpression.findFlowOnCall(): ResolvedCall<out CallableDescriptor>? { val dotQualifiedExpression = this.getStrictParentOfType<KtDotQualifiedExpression>() ?: return null val candidate = dotQualifiedExpression .children .asSequence() .filterIsInstance<KtCallExpression>() .mapNotNull { it.resolveToCall(BodyResolveMode.PARTIAL) } .firstOrNull { it.isCalling(FqName(FLOW_ON_FQN)) } return candidate ?: dotQualifiedExpression.findFlowOnCall() } const val BLOCKING_EXECUTOR_ANNOTATION = "org.jetbrains.annotations.BlockingExecutor" const val NONBLOCKING_EXECUTOR_ANNOTATION = "org.jetbrains.annotations.NonBlockingExecutor" const val DISPATCHERS_FQN = "kotlinx.coroutines.Dispatchers" const val IO_DISPATCHER_FQN = "kotlinx.coroutines.Dispatchers.IO" const val MAIN_DISPATCHER_FQN = "kotlinx.coroutines.Dispatchers.Main" const val DEFAULT_DISPATCHER_FQN = "kotlinx.coroutines.Dispatchers.Default" const val COROUTINE_SCOPE = "kotlinx.coroutines.CoroutineScope" const val COROUTINE_CONTEXT = "kotlin.coroutines.CoroutineContext" const val FLOW_ON_FQN = "kotlinx.coroutines.flow.flowOn" const val FLOW_PACKAGE_FQN = "kotlinx.coroutines.flow" const val FLOW_FQN = "kotlinx.coroutines.flow.Flow" const val WITH_CONTEXT_FQN = "kotlinx.coroutines.withContext" }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/blockingCallsDetection/CoroutineBlockingCallInspectionUtils.kt
2531502359
// WITH_STDLIB fun foo(s: String?) { val t = s?.hashCode() ?:<caret> throw Exception() }
plugins/kotlin/idea/tests/testData/intentions/branched/elvisToIfThen/assignmentAndThrow.kt
1544389359
// 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.util import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode fun KtModifierListOwner.addAnnotation( annotationFqName: FqName, annotationInnerText: String? = null, whiteSpaceText: String = "\n", addToExistingAnnotation: ((KtAnnotationEntry) -> Boolean)? = null ): Boolean { val annotationText = when (annotationInnerText) { null -> "@${annotationFqName.render()}" else -> "@${annotationFqName.render()}($annotationInnerText)" } val psiFactory = KtPsiFactory(this) val modifierList = modifierList if (modifierList == null) { val addedAnnotation = addAnnotationEntry(psiFactory.createAnnotationEntry(annotationText)) ShortenReferences.DEFAULT.process(addedAnnotation) return true } val entry = findAnnotation(annotationFqName) if (entry == null) { // no annotation val newAnnotation = psiFactory.createAnnotationEntry(annotationText) val addedAnnotation = modifierList.addBefore(newAnnotation, modifierList.firstChild) as KtElement val whiteSpace = psiFactory.createWhiteSpace(whiteSpaceText) modifierList.addAfter(whiteSpace, addedAnnotation) ShortenReferences.DEFAULT.process(addedAnnotation) return true } if (addToExistingAnnotation != null) { return addToExistingAnnotation(entry) } return false } fun KtAnnotated.findAnnotation(annotationFqName: FqName): KtAnnotationEntry? { if (annotationEntries.isEmpty()) return null val context = analyze(bodyResolveMode = BodyResolveMode.PARTIAL) val descriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, this] ?: return null // Make sure all annotations are resolved descriptor.annotations.toList() return annotationEntries.firstOrNull { entry -> context.get(BindingContext.ANNOTATION, entry)?.fqName == annotationFqName } } fun KtAnnotated.hasJvmFieldAnnotation(): Boolean = findAnnotation(JvmAbi.JVM_FIELD_ANNOTATION_FQ_NAME) != null
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/util/modifierListModifactor.kt
1920106688
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.PsiMethod import com.intellij.psi.PsiNewExpression import com.intellij.psi.PsiType import com.intellij.psi.ResolveResult import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* @ApiStatus.Internal class JavaUObjectLiteralExpression( override val sourcePsi: PsiNewExpression, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), UObjectLiteralExpression, UCallExpression, UMultiResolvable { override val declaration: UClass by lz { JavaUClass.create(sourcePsi.anonymousClass!!, this) } override val classReference: UReferenceExpression? by lz { sourcePsi.classReference?.let { ref -> JavaConverter.convertReference(ref, this) as? UReferenceExpression } } override val valueArgumentCount: Int get() = sourcePsi.argumentList?.expressions?.size ?: 0 override val valueArguments: List<UExpression> by lz { sourcePsi.argumentList?.expressions?.map { JavaConverter.convertOrEmpty(it, this) } ?: emptyList() } override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i) override val typeArgumentCount: Int by lz { sourcePsi.classReference?.typeParameters?.size ?: 0 } override val typeArguments: List<PsiType> get() = sourcePsi.classReference?.typeParameters?.toList() ?: emptyList() override fun resolve(): PsiMethod? = sourcePsi.resolveMethod() override fun multiResolve(): Iterable<ResolveResult> = sourcePsi.classReference?.multiResolve(false)?.asIterable() ?: emptyList() }
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUObjectLiteralExpression.kt
1037256514
/* * 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 org.jetbrains.plugins.groovy.runner.util import com.intellij.execution.CommonProgramRunConfigurationParameters open class CommonProgramRunConfigurationParametersDelegate( delegate: CommonProgramRunConfigurationParameters ) : CommonProgramRunConfigurationParameters by delegate
plugins/groovy/src/org/jetbrains/plugins/groovy/runner/util/CommonProgramRunConfigurationParametersDelegate.kt
3779869818
package boxReturnValue inline fun <X: Any> useInline(x: X) { // EXPRESSION: x // RESULT: instance of java.lang.Integer(id=ID): Ljava/lang/Integer; //Breakpoint! val a = 1 } fun main(args: Array<String>) { useInline(1) }
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/boxReturnValue.kt
3749709429
package net.fudiyama.libqx1.ssdp class ServiceInfo(val type: String, val url: String) { override fun toString(): String { return "ServiceInfo(type='$type', url='$url')" } }
src/main/kotlin/net/fudiyama/libqx1/ssdp/ServiceInfo.kt
873120505
package ksax import org.assertj.core.api.Assertions.assertThat import org.junit.Assert.fail import org.junit.Ignore import org.junit.Test import org.xml.sax.SAXParseException import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.math.BigDecimal data class Book(val id: String, val author: String, val title: String, val price: BigDecimal) class TooManyValuesException(message: String) : RuntimeException(message) class KSAXTest { companion object { val CATALOG = "catalog" val BOOK = "$CATALOG/book" val BOOKS = "Books" val BOOK_ID = "$BOOK@id" val BOOK_AUTHOR = "$BOOK/author" val BOOK_TITLE = "$BOOK/title" val BOOK_PRICE = "$BOOK/price" val data = read("books.xml") } @Suppress("UNCHECKED") val parser = parseRules { push(BOOK_ID) push(BOOK_AUTHOR) push(BOOK_TITLE) push(BOOK_PRICE) pushToList(BOOK to BOOKS) { ctx -> Book( id = ctx.popNonNull(BOOK_ID), author = ctx.popNonNull(BOOK_AUTHOR), title = ctx.popNonNull(BOOK_TITLE), price = BigDecimal(ctx.pop(BOOK_PRICE) ?: "0") ) } withTooManyValuesExFactory(::TooManyValuesException) @Suppress("UNCHECKED_CAST") withResultBuilder { ctx -> ctx[BOOKS] as List<Book> } } fun doTest() { ByteArrayInputStream(data).use { val parsedObjects = parser.parse(it) assertThat(parsedObjects).hasSize(12) assertThat(parsedObjects?.filter { it.price == BigDecimal.ZERO }).hasSize(2) } } @Test fun test() { val start = System.currentTimeMillis() doTest() println("Elapsed ${System.currentTimeMillis() - start} msec.") } class MyEx(message: String): RuntimeException(message) @Test fun `test with non-existent rules`() { val parser = parseRules { push("a/b/c") push("a/b/c@d") pushToList("a/b" to "B") { it } withExFactory { MyEx(it.joinToString("|")) } withResultBuilder { it } } try { parser.parse(ByteArrayInputStream(data)) fail() } catch (e: MyEx) { listOf("a/b/c", "a/b/c@d", "a/b").forEach { assertThat(e.message).contains(it) } } } @Test(expected = SAXParseException::class) fun `test with invalid XML`() { parser.parse(ByteArrayInputStream("12345".toByteArray())) } @Test fun `when duplicated values found on same parent node parsing should fails`() { try { parser.parse(ByteArrayInputStream(read("books-with-duplicated-nodes.xml"))) } catch(e: TooManyValuesException) { assertThat(e.message).contains(BOOK_AUTHOR) } } @Test(expected = SAXParseException::class) fun `when found duplicated attrs on same node parsing should fails`() { parser.parse(ByteArrayInputStream(read("books-with-duplicated-attributes.xml"))) } @Test @Ignore fun performanceTest() { val count = 500000 var total = 0L (1..count).forEach { total += measureTime { doTest() } } println("Average time is ${total / count.toDouble()} msec.") } fun measureTime(block: () -> Unit): Long { val start = System.currentTimeMillis() block() return System.currentTimeMillis() - start } } private fun read(resourceName: String) = run { val output = ByteArrayOutputStream() KSAXTest::class.java.classLoader.getResourceAsStream(resourceName)!!.use { it.copyTo(output) } output.toByteArray() }
src/test/kotlin/ksax/KSAXTest.kt
3633301763
package com.cognifide.gradle.aem.common.instance.oak import com.cognifide.gradle.aem.AemException open class OakRunException : AemException { constructor(message: String, cause: Throwable) : super(message, cause) constructor(message: String) : super(message) }
src/main/kotlin/com/cognifide/gradle/aem/common/instance/oak/OakRunException.kt
1918300676
/* * * * 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.domain.repo.base import com.sinyuk.fanfou.domain.api.RestAPI import javax.inject.Inject /** * Created by sinyuk on 2017/11/28. * */ abstract class AbstractRepository @Inject constructor(restAPI: RestAPI)
domain/src/main/java/com/sinyuk/fanfou/domain/repo/base/AbstractRepository.kt
1181041892
package io.vertx.lang.kotlin.example.core.http.websockets import io.vertx.kotlin.core.Vertx import io.vertx.kotlin.core.buffer.Buffer import io.vertx.lang.kotlin.KotlinVerticle import io.vertx.lang.kotlin.example.utils.deployCallback fun main(args: Array<String>) { val vertx = Vertx.vertx() vertx.deployVerticle(Server(), { deployCallback(vertx, Client(), it) }) } class Server : KotlinVerticle() { val path = "io/vertx/lang/kotlin/example/core/http/websockets" override fun start() { vertx.createHttpServer().websocketHandler { ws -> ws.handler { data -> ws.writeBinaryMessage(data) } }.requestHandler { request -> if (request.uri().equals("/")) request.response().sendFile("$path/ws.html") }.listen(8080) } } class Client : KotlinVerticle() { override fun start() { val client = vertx.createHttpClient() client.websocket(8080, "localhost", "/") { websocket -> websocket.handler { data -> println("Client received data: ${data.toString("ISO-8859-1")}") client.close() } websocket.writeBinaryMessage(Buffer.buffer("Hello world")) } client.getNow(8080, "localhost", "/") { it.bodyHandler { println("Client received another data: $it") } } } }
kotlin-examples/src/main/kotlin/io/vertx/lang/kotlin/example/core/http/websockets/ClientServer.kt
2955171825
package net.simno.dmach.patch import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.buffer import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking import net.simno.dmach.db.PatchRepository import net.simno.dmach.db.TestPatchDao import net.simno.dmach.machine.MachineProcessor import net.simno.dmach.playback.AudioFocus import net.simno.dmach.playback.PureData import org.junit.Before import org.junit.Test import org.mockito.Mockito.mock @DelicateCoroutinesApi class PatchProcessorTests { private lateinit var repository: PatchRepository private lateinit var testDao: TestPatchDao private lateinit var patchProcessor: PatchProcessor private suspend fun processAction(action: Action): Result = processActions(action).first() private suspend fun processActions( vararg actions: Action ): List<Result> = actions.asFlow() .onEach { delay(10L) } .buffer(0) .shareIn(GlobalScope, SharingStarted.Lazily) .let(patchProcessor) .take(actions.size) .toList() @Before fun setup() { testDao = TestPatchDao() repository = PatchRepository(testDao) patchProcessor = PatchProcessor(repository) setupRepository() } private fun setupRepository() = runBlocking { flowOf(net.simno.dmach.machine.LoadAction) .onEach { delay(10L) } .buffer(0) .shareIn(GlobalScope, SharingStarted.Lazily) .let(MachineProcessor(emptySet(), mock(PureData::class.java), mock(AudioFocus::class.java), repository)) .take(1) .toList() } @Test fun load() = runBlocking { val actual = processAction(LoadAction) as LoadResult assertThat(actual.title).isEqualTo(testDao.patch.title) } @Test fun dismiss() = runBlocking { val actual = processAction(DismissAction) val expected = DismissResult assertThat(actual).isEqualTo(expected) } @Test fun confirmOverwrite() = runBlocking { val actual = processAction(ConfirmOverwriteAction) val expected = ConfirmOverwriteResult assertThat(actual).isEqualTo(expected) } @Test fun confirmDelete() = runBlocking { val actual = processAction(ConfirmDeleteAction) val expected = ConfirmDeleteResult assertThat(actual).isEqualTo(expected) } @Test fun savePatch() = runBlocking { val title = "1337" val actual = processAction(SavePatchAction(title)) val expected = SavePatchResult(false, title) assertThat(actual).isEqualTo(expected) } @Test fun deletePatch() = runBlocking { val title = "1337" val actual = processAction(DeletePatchAction(title)) val expected = DeletePatchResult(title) processAction(ConfirmDeleteAction) assertThat(actual).isEqualTo(expected) assertThat(testDao.deleteTitle).isEqualTo(title) } @Test fun selectPatch() = runBlocking { val title = "1337" val actual = processAction(SelectPatchAction(title)) val expected = SelectPatchResult assertThat(actual).isEqualTo(expected) } }
app/src/test/java/net/simno/dmach/patch/PatchProcessorTests.kt
2087482684
package com.github.musichin.ktupnp.discovery import java.net.InetAddress data class SsdpPacket( val message: SsdpMessage, val address: InetAddress, val port: Int )
ktupnp-discovery/src/main/java/com/github/musichin/ktupnp/discovery/SsdpPacket.kt
2229145054
package ch.rmy.android.http_shortcuts.activities.settings.importexport.usecases import android.app.Activity import android.app.Dialog import ch.rmy.android.framework.extensions.addOrRemove import ch.rmy.android.framework.extensions.runFor import ch.rmy.android.framework.viewmodel.WithDialog import ch.rmy.android.framework.viewmodel.viewstate.DialogState import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutId import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutRepository import ch.rmy.android.http_shortcuts.utils.DialogBuilder import com.afollestad.materialdialogs.WhichButton import com.afollestad.materialdialogs.actions.getActionButton import com.afollestad.materialdialogs.callbacks.onShow import javax.inject.Inject class GetShortcutSelectionDialogUseCase @Inject constructor( private val shortcutRepository: ShortcutRepository, ) { suspend operator fun invoke(onConfirm: (Collection<ShortcutId>?) -> Unit): DialogState { val shortcuts = shortcutRepository.getShortcuts() return object : DialogState { override val id = "select-shortcuts-for-export" private val selectedShortcutIds = shortcuts.map { it.id }.toMutableSet() private var onSelectionChanged: (() -> Unit)? = null override fun createDialog(activity: Activity, viewModel: WithDialog?): Dialog = DialogBuilder(activity) .title(R.string.dialog_title_select_shortcuts_for_export) .runFor(shortcuts) { shortcut -> checkBoxItem( name = shortcut.name, shortcutIcon = shortcut.icon, checked = { shortcut.id in selectedShortcutIds }, ) { isChecked -> selectedShortcutIds.addOrRemove(shortcut.id, isChecked) onSelectionChanged?.invoke() } } .positive(R.string.dialog_button_export) { onConfirm(selectedShortcutIds.takeUnless { it.size == shortcuts.size }) } .negative(R.string.dialog_cancel) .dismissListener { onSelectionChanged = null viewModel?.onDialogDismissed(this) } .build() .onShow { dialog -> val okButton = dialog.getActionButton(WhichButton.POSITIVE) onSelectionChanged = { okButton.isEnabled = selectedShortcutIds.isNotEmpty() } onSelectionChanged?.invoke() } } } }
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/settings/importexport/usecases/GetShortcutSelectionDialogUseCase.kt
2201347662
package glorantq.ramszesz.commands import glorantq.ramszesz.utils.BotUtils import glorantq.ramszesz.memes.* import org.slf4j.Logger import org.slf4j.LoggerFactory import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent import sx.blah.discord.handle.obj.IUser import sx.blah.discord.util.EmbedBuilder import java.util.* import kotlin.concurrent.thread /** * Created by glora on 2017. 07. 26.. */ class MemeCommand : ICommand { override val commandName: String get() = "memegen" override val description: String get() = "Generate memes in Discord" override val permission: Permission get() = Permission.USER override val extendedHelp: String get() = "Generate memes in Discord." override val aliases: List<String> get() = listOf("meme") override val usage: String get() = "Meme [Arguments]" companion object { val memes: ArrayList<IMeme> = ArrayList() } init { memes.add(MemeList()) memes.add(TriggeredMeme()) memes.add(NumberOneMeme()) memes.add(ThinkingMeme()) memes.add(EmojiMovieMeme()) memes.add(RainbowMeme()) memes.add(OpenCVDemo()) memes.add(LensflareMeme()) } val logger: Logger = LoggerFactory.getLogger(this::class.java) val checkIDRegex: Regex = Regex("^<@![0-9]{18}>$|^<@[0-9]{18}>$") val replaceTagsRegex: Regex = Regex("<@!|<@|>") override fun execute(event: MessageReceivedEvent, args: List<String>) { if(args.isEmpty()) { BotUtils.sendUsageEmbed("You need to provide a meme, and optionally arguments", "Meme", event.author, event, this) return } val parts: List<String> = event.message.content.split(" ") val memeArgs: List<String> = if (parts.size == 1) { java.util.ArrayList() } else { parts.subList(1, parts.size) } for(meme: IMeme in memes) { if(meme.name.equals(args[0], true)) { if(meme.parameters.isNotEmpty()) { if(memeArgs.size - 1 < meme.parameters.size) { BotUtils.sendUsageEmbed("This meme requires more arguments!", "Meme", event.author, event, this) return } else if(memeArgs.size - 1 > meme.parameters.size) { BotUtils.sendUsageEmbed("This meme requires fewer arguments!", "Meme", event.author, event, this) return } else { for(i: Int in 1 until memeArgs.size) { when(meme.parameters[i - 1].type) { MemeParameter.Companion.Type.STRING -> { setParam(i - 1, meme, memeArgs[i]) } MemeParameter.Companion.Type.INT -> { try { setParam(i - 1, meme, memeArgs[i].toInt()) } catch (e: NumberFormatException) { BotUtils.sendMessage(BotUtils.createSimpleEmbed("Meme", "`${memeArgs[i]}` is not a valid number!", event.author), event.channel) return } } MemeParameter.Companion.Type.USER -> { val idParam: String = memeArgs[i] val userId: Long if(idParam.equals("random_user", true)) { userId = event.guild.users[Random().nextInt(event.guild.users.size)].longID } else { if (!idParam.matches(checkIDRegex)) { BotUtils.sendMessage(BotUtils.createSimpleEmbed("Meme", "`$idParam` is not a valid tag!", event.author), event.channel) return } else { userId = idParam.replace(replaceTagsRegex, "").toLong() } } val user: IUser? = event.guild.getUserByID(userId) if(user == null) { BotUtils.sendMessage(BotUtils.createSimpleEmbed("Meme", "`$userId` is not a valid ID!", event.author), event.channel) return } else { setParam(i - 1, meme, user) } } } } } } exec(event, meme) return } } BotUtils.sendMessage(BotUtils.createSimpleEmbed("Meme Generator", "`${args[0]}` is not a valid meme", event.author), event.channel) } private fun exec(event: MessageReceivedEvent, meme: IMeme) { thread(name = "MemeExec-${meme.name}-${event.author.name}-${System.nanoTime()}", isDaemon = true, start = true) { logger.info("Executing meme...") try { meme.execute(event) } catch (e: Exception) { val embed: EmbedBuilder = BotUtils.embed("Meme Generator", event.author) embed.withDescription("I couldn't deliver your meme because @glorantq can't code") embed.appendField(e::class.simpleName, e.message, false) BotUtils.sendMessage(embed.build(), event.channel) } logger.info("Finished!") } } private fun setParam(index: Int, meme: IMeme, value: Any) { val param: MemeParameter = meme.parameters[index] param.value = value val parameters: ArrayList<MemeParameter> = meme.parameters.clone() as ArrayList<MemeParameter> parameters[index] = param meme.parameters = parameters println(meme.parameters[index].value) } }
src/glorantq/ramszesz/commands/MemeCommand.kt
1181407801
package com.sksamuel.kotest.specs.expect import io.kotest.core.spec.style.ExpectSpec class ExpectSpecTest : ExpectSpec() { init { context("some context") { expect("some test") { // test here } expect("some test 2").config(enabled = true) { // test here } context("another nested context") { expect("some test") { // test here } expect("some test 2").config(enabled = false) { // test here } xexpect("disabled") { error("Boom") } xexpect("xtest with config").config(invocations = 3) { error("Boom") } } xcontext("disabled nested context") { error("Boom") } } xcontext("should be ignored 1") { expect("disabled") { error("Boom") } } xcontext("should be ignored 2") { error("Boom") } } }
kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/specs/expect/ExpectSpecTest.kt
3730984156
/* * 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 org.jetbrains.settingsRepository import com.intellij.openapi.progress.ProgressIndicator import gnu.trove.THashSet import java.io.InputStream import java.util.Collections public interface RepositoryManager { public fun createRepositoryIfNeed(): Boolean /** * Think twice before use */ public fun deleteRepository() public fun isRepositoryExists(): Boolean public fun getUpstream(): String? public fun hasUpstream(): Boolean /** * Return error message if failed */ public fun setUpstream(url: String?, branch: String? = null) public fun read(path: String): InputStream? /** * Returns false if file is not written (for example, due to ignore rules). */ public fun write(path: String, content: ByteArray, size: Int): Boolean public fun delete(path: String) public fun processChildren(path: String, filter: (name: String) -> Boolean, processor: (name: String, inputStream: InputStream) -> Boolean) /** * Not all implementations support progress indicator (will not be updated on progress). * * syncType will be passed if called before sync. * * If fixStateIfCannotCommit, repository state will be fixed before commit. */ public fun commit(indicator: ProgressIndicator? = null, syncType: SyncType? = null, fixStateIfCannotCommit: Boolean = true): Boolean public fun getAheadCommitsCount(): Int public fun commit(paths: List<String>) public fun push(indicator: ProgressIndicator? = null) public fun fetch(indicator: ProgressIndicator? = null): Updater public fun pull(indicator: ProgressIndicator? = null): UpdateResult? public fun has(path: String): Boolean public fun resetToTheirs(indicator: ProgressIndicator): UpdateResult? public fun resetToMy(indicator: ProgressIndicator, localRepositoryInitializer: (() -> Unit)?): UpdateResult? public fun canCommit(): Boolean public interface Updater { fun merge(): UpdateResult? // valid only if merge was called before val definitelySkipPush: Boolean } } public interface UpdateResult { val changed: Collection<String> val deleted: Collection<String> } val EMPTY_UPDATE_RESULT = ImmutableUpdateResult(Collections.emptySet(), Collections.emptySet()) public data class ImmutableUpdateResult(override val changed: Collection<String>, override val deleted: Collection<String>) : UpdateResult { public fun toMutable(): MutableUpdateResult = MutableUpdateResult(changed, deleted) } public data class MutableUpdateResult(changed: Collection<String>, deleted: Collection<String>) : UpdateResult { override val changed = THashSet(changed) override val deleted = THashSet(deleted) fun add(result: UpdateResult?): MutableUpdateResult { if (result != null) { add(result.changed, result.deleted) } return this } fun add(newChanged: Collection<String>, newDeleted: Collection<String>): MutableUpdateResult { changed.removeAll(newDeleted) deleted.removeAll(newChanged) changed.addAll(newChanged) deleted.addAll(newDeleted) return this } fun addChanged(newChanged: Collection<String>): MutableUpdateResult { deleted.removeAll(newChanged) changed.addAll(newChanged) return this } } public fun UpdateResult?.isEmpty(): Boolean = this == null || (changed.isEmpty() && deleted.isEmpty()) public fun UpdateResult?.concat(result: UpdateResult?): UpdateResult? { if (result.isEmpty()) { return this } else if (isEmpty()) { return result } else { this!! return MutableUpdateResult(changed, deleted).add(result!!) } } public class AuthenticationException(cause: Throwable) : RuntimeException(cause.getMessage(), cause)
plugins/settings-repository/src/RepositoryManager.kt
3711959614
package com.seino.daniel.racing_app.util /** * Created by dabal on 2/09/17. */ /** * Contains a static reference to [IdlingResource], only available in the 'mock' build type. */ object EspressoIdlingResource { private val RESOURCE = "GLOBAL" val countingIdlingResource = SimpleCountingIdlingResource(RESOURCE) fun increment() { countingIdlingResource.increment() } fun decrement() { countingIdlingResource.decrement() } }
app/src/main/java/com/seino/daniel/racing_app/util/EspressoIdlingResource.kt
2398077251
package com.github.kerubistan.kerub.model.dynamic import com.github.kerubistan.kerub.model.AbstractDataRepresentationTest import com.github.kerubistan.kerub.model.dynamic.gvinum.MirroredGvinumConfiguration import com.github.kerubistan.kerub.model.dynamic.gvinum.SimpleGvinumConfiguration import com.github.kerubistan.kerub.testFreeBsdHost import com.github.kerubistan.kerub.testGvinumCapability import com.github.kerubistan.kerub.testHost import io.github.kerubistan.kroki.size.GB import io.github.kerubistan.kroki.size.TB import org.junit.Assert.assertEquals import org.junit.Test import java.util.UUID.randomUUID class VirtualStorageGvinumAllocationTest : AbstractDataRepresentationTest<VirtualStorageGvinumAllocation>() { override val testInstances = listOf( VirtualStorageGvinumAllocation( capabilityId = testGvinumCapability.id, hostId = testFreeBsdHost.id, actualSize = 4.TB, configuration = SimpleGvinumConfiguration( diskName = "test-disk" ) ) ) override val clazz = VirtualStorageGvinumAllocation::class.java @Test fun getRedundancyLevel() { assertEquals( 0.toByte(), VirtualStorageGvinumAllocation( hostId = testHost.id, actualSize = 1.GB, capabilityId = randomUUID(), configuration = SimpleGvinumConfiguration( diskName = "/dev/sda" ) ).getRedundancyLevel()) assertEquals( 1.toByte(), VirtualStorageGvinumAllocation( hostId = testHost.id, actualSize = 1.GB, capabilityId = randomUUID(), configuration = MirroredGvinumConfiguration( disks = listOf("/dev/sda", "/dev/sdb") ) ).getRedundancyLevel()) } }
src/test/kotlin/com/github/kerubistan/kerub/model/dynamic/VirtualStorageGvinumAllocationTest.kt
791057399
/* * Copyright (C) 2017 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.action.view import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView import jp.hazuki.yuzubrowser.legacy.action.Action import jp.hazuki.yuzubrowser.legacy.action.ActionList import jp.hazuki.yuzubrowser.legacy.action.ActionNameArray class ActionListViewAdapter(context: Context, objects: ActionList, array: ActionNameArray?) : ArrayAdapter<Action>(context, 0, objects) { private val mActionNameArray = array ?: ActionNameArray(context) override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view = convertView ?: LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, null) getItem(position)?.let { view.findViewById<TextView>(android.R.id.text1).text = it.toString(mActionNameArray) } return view } }
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/view/ActionListViewAdapter.kt
2963615999
package com.github.stephanenicolas.heatcontrol.features.control.state const val MOCK = "Mock" class SettingState(var key:String? = null, var hostList:ArrayList<Host> = ArrayList()) class Host(var name:String, var address:String, var isSelected:Boolean = false)
app/src/main/java/com/github/stephanenicolas/heatcontrol/features/setting/state/SettingState.kt
171042229
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.chat.bukkit.chatchannel.undirected import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.chatchannel.pipeline.UndirectedChatChannelPipelineComponent import com.rpkit.chat.bukkit.context.UndirectedChatChannelMessageContext import org.bukkit.Bukkit import org.bukkit.configuration.serialization.ConfigurationSerializable import org.bukkit.configuration.serialization.SerializableAs import java.io.BufferedWriter import java.io.File import java.io.FileWriter import java.io.IOException import java.text.SimpleDateFormat import java.util.* /** * Log component. * Logs messages to a dated log file. */ @SerializableAs("LogComponent") class LogComponent(private val plugin: RPKChatBukkit): UndirectedChatChannelPipelineComponent, ConfigurationSerializable { override fun process(context: UndirectedChatChannelMessageContext): UndirectedChatChannelMessageContext { val logDirectory = File(plugin.dataFolder, "logs") val logDateFormat = SimpleDateFormat("yyyy-MM-dd") val datedLogDirectory = File(logDirectory, logDateFormat.format(Date())) if (!datedLogDirectory.exists()) { if (!datedLogDirectory.mkdirs()) throw IOException("Could not create log directory. Does the server have permission to write to the directory?") } val log = File(datedLogDirectory, context.chatChannel.name + ".log") if (!log.exists()) { if (!log.createNewFile()) throw IOException("Failed to create log file. Does the server have permission to write to the directory?") } val writer = BufferedWriter(FileWriter(log, true)) val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") writer.append("[").append(dateFormat.format(Date())).append("] ").append(context.message).append("\n") writer.close() return context } override fun serialize(): MutableMap<String, Any> { return mutableMapOf() } companion object { @JvmStatic fun deserialize(serialized: MutableMap<String, Any>): LogComponent { return LogComponent(Bukkit.getPluginManager().getPlugin("rpk-chat-bukkit") as RPKChatBukkit) } } }
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/chatchannel/undirected/LogComponent.kt
4119969251
package com.soywiz.kpspemu.util inline fun <T> ignoreErrors(callback: () -> T): T? = try { callback() } catch (e: Throwable) { null }
src/commonMain/kotlin/com/soywiz/kpspemu/util/ignoreErrors.kt
4139105537
package nice3point.by.schedule.ScheduleDialogChanger interface iMScheduleChanger { fun addItemToRealm(databaseday: String?, subject: String?, name: String?, startTime: String?, endTime: String?, type: String?, cabinet: String?) fun closeRealm() fun editRealmItem(newData: Array<String?>, teacher: String, subject: String, cabinet: String, time: String, type: String) fun deleteRealmItem(databaseName: String, teacher: String, subject: String, cabinet: String, time: String, type: String) }
app/src/main/java/nice3point/by/schedule/ScheduleDialogChanger/iMScheduleChanger.kt
2467881386
package org.gradle.kotlin.dsl.integration import org.gradle.kotlin.dsl.fixtures.AbstractKotlinIntegrationTest import org.hamcrest.CoreMatchers.containsString import org.hamcrest.MatcherAssert.assertThat import org.junit.Test /** * See https://docs.gradle.org/current/userguide/build_environment.html */ class DelegatedGradlePropertiesIntegrationTest : AbstractKotlinIntegrationTest() { @Test fun `non-nullable delegated property access of non-existing gradle property throws`() { withSettings( """ val nonExisting: String by settings println(nonExisting) """ ) assertThat( buildAndFail("help").error, containsString("Cannot get non-null property 'nonExisting' on settings '${projectRoot.name}' as it does not exist") ) withSettings("") withBuildScript( """ val nonExisting: String by project println(nonExisting) """ ) assertThat( buildAndFail("help").error, containsString("Cannot get non-null property 'nonExisting' on root project '${projectRoot.name}' as it does not exist") ) } @Test fun `delegated properties follow Gradle mechanics and allow to model optional properties via nullable kotlin types`() { // given: build root gradle.properties file withFile( "gradle.properties", """ setBuildProperty=build value emptyBuildProperty= userHomeOverriddenBuildProperty=build value cliOverriddenBuildProperty=build value projectMutatedBuildProperty=build value """.trimIndent() ) // and: gradle user home gradle.properties file withFile( "gradle-user-home/gradle.properties", """ setUserHomeProperty=user home value emptyUserHomeProperty= userHomeOverriddenBuildProperty=user home value cliOverriddenUserHomeProperty=user home value projectMutatedUserHomeProperty=user home value """.trimIndent() ) // and: isolated gradle user home executer.withGradleUserHomeDir(existing("gradle-user-home")) executer.requireIsolatedDaemons() // and: gradle command line with properties val buildArguments = arrayOf( "-PsetCliProperty=cli value", "-PemptyCliProperty=", "-PcliOverriddenBuildProperty=cli value", "-PcliOverriddenUserHomeProperty=cli value", "-Dorg.gradle.project.setOrgGradleProjectSystemProperty=system property value", "-Dorg.gradle.project.emptyOrgGradleProjectSystemProperty=", "help" ) // when: both settings and project scripts asserting on delegated properties withSettings(requirePropertiesFromSettings()) withBuildScript(requirePropertiesFromProject()) // then: build(*buildArguments) // when: project script buildscript block asserting on delegated properties withSettings("") withBuildScript( """ buildscript { ${requirePropertiesFromProject()} } """ ) // then: build(*buildArguments) } private fun requirePropertiesFromSettings() = """ ${requireNotOverriddenPropertiesFrom("settings")} ${requireOverriddenPropertiesFrom("settings")} ${requireEnvironmentPropertiesFrom("settings")} ${requireProjectMutatedPropertiesOriginalValuesFrom("settings")} """.trimIndent() private fun requirePropertiesFromProject() = """ ${requireNotOverriddenPropertiesFrom("project")} ${requireOverriddenPropertiesFrom("project")} ${requireEnvironmentPropertiesFrom("project")} ${requireProjectExtraProperties()} ${requireProjectMutatedPropertiesOriginalValuesFrom("project")} ${requireProjectPropertiesMutation()} """.trimIndent() private fun requireNotOverriddenPropertiesFrom(source: String) = """ ${requireProperty<String>(source, "setUserHomeProperty", """"user home value"""")} ${requireProperty<String>(source, "emptyUserHomeProperty", """""""")} ${requireProperty<String>(source, "setBuildProperty", """"build value"""")} ${requireProperty<String>(source, "emptyBuildProperty", """""""")} ${requireProperty<String>(source, "setCliProperty", """"cli value"""")} ${requireProperty<String>(source, "emptyCliProperty", """""""")} ${requireNullableProperty<String>(source, "unsetProperty", "null")} """.trimIndent() private fun requireOverriddenPropertiesFrom(source: String) = """ ${requireProperty<String>(source, "userHomeOverriddenBuildProperty", """"user home value"""")} ${requireProperty<String>(source, "cliOverriddenBuildProperty", """"cli value"""")} ${requireProperty<String>(source, "cliOverriddenUserHomeProperty", """"cli value"""")} """.trimIndent() private fun requireEnvironmentPropertiesFrom(source: String) = """ ${requireProperty<String>(source, "setOrgGradleProjectSystemProperty", """"system property value"""")} ${requireProperty<String>(source, "emptyOrgGradleProjectSystemProperty", """""""")} """.trimIndent() private fun requireProjectExtraProperties() = """ run { extra["setExtraProperty"] = "extra value" extra["emptyExtraProperty"] = "" extra["unsetExtraProperty"] = null val setExtraProperty: String by project require(setExtraProperty == "extra value") val emptyExtraProperty: String by project require(emptyExtraProperty == "") val unsetExtraProperty: String? by project require(unsetExtraProperty == null) setProperty("setExtraProperty", "mutated") require(setExtraProperty == "mutated") } """.trimIndent() private fun requireProjectMutatedPropertiesOriginalValuesFrom(source: String) = """ ${requireProperty<String>(source, "projectMutatedBuildProperty", """"build value"""")} ${requireProperty<String>(source, "projectMutatedUserHomeProperty", """"user home value"""")} """.trimIndent() private fun requireProjectPropertiesMutation() = """ run { val projectMutatedBuildProperty: String by project require(projectMutatedBuildProperty == "build value") setProperty("projectMutatedBuildProperty", "mutated") require(projectMutatedBuildProperty == "mutated") val projectMutatedUserHomeProperty: String by project require(projectMutatedUserHomeProperty == "user home value") setProperty("projectMutatedUserHomeProperty", "mutated") require(projectMutatedUserHomeProperty == "mutated") } """.trimIndent() private inline fun <reified T : Any> requireProperty(source: String, name: String, valueRepresentation: String) = requireProperty(source, name, T::class.qualifiedName!!, valueRepresentation) private inline fun <reified T : Any> requireNullableProperty(source: String, name: String, valueRepresentation: String) = requireProperty(source, name, "${T::class.qualifiedName!!}?", valueRepresentation) private fun requireProperty(source: String, name: String, type: String, valueRepresentation: String) = """ run { val $name: $type by $source require($name == $valueRepresentation) { ${"\"".repeat(3)}expected $name to be '$valueRepresentation' but was '${'$'}$name'${"\"".repeat(3)} } } """.trimIndent() }
subprojects/kotlin-dsl/src/integTest/kotlin/org/gradle/kotlin/dsl/integration/DelegatedGradlePropertiesIntegrationTest.kt
3913549505
import java.util.Calendar import java.util.HashMap import java.util.Scanner /************************************** * How to use: * Enter a date like: * [day] [month] [year] * EXAMPLE: * 01 01 2000 */ internal fun IsLeapYear(y: Int): Boolean { var bl = false if (y % 4 == 0) { bl = true } return bl } internal fun MonthSize(m: Int, y: Int): Int { var size = 0 val monthsize = HashMap<Int, Int>() monthsize.put(1, 31) monthsize.put(2, 28) monthsize.put(3, 31) monthsize.put(4, 30) monthsize.put(5, 31) monthsize.put(6, 30) monthsize.put(7, 31) monthsize.put(8, 31) monthsize.put(9, 30) monthsize.put(10, 31) monthsize.put(11, 30) monthsize.put(12, 31) if (IsLeapYear(y) && m == 2) { size = 29 } else { size = monthsize[m] as Int } return size } internal fun GetDayCount(curday: Int, curmonth: Int, curyear: Int, gday: Int, gmonth: Int, gyear: Int): Int { var calc = 0 // calculate year days if (gmonth < curmonth) { for (c in gyear..curyear - 1) { if (IsLeapYear(c)) { calc += 366 } else { calc += 365 } } } else if (gmonth == curmonth) { if (gday <= curday) { for (c in gyear..curyear - 1) { if (IsLeapYear(c)) { calc += 366 } else { calc += 365 } } } } else { for (c in gyear + 1..curyear - 1) { if (IsLeapYear(c)) { calc += 366 } else { calc += 365 } } } if ((curyear - gyear) / 100 >= 1) { calc -= (curyear - gyear) / 100 } // calculate month days if (gmonth > curmonth) { for (c in gmonth..12) { calc += MonthSize(c, curyear - 1) } for (c in 1..curmonth - 1) { calc += MonthSize(c, curyear) } } else { if (gday > curday) { for (c in gmonth..curmonth - 1 - 1) { calc += MonthSize(c, curyear) } } else { for (c in gmonth..curmonth - 1) { calc += MonthSize(c, curyear) } } } // calculate days if (gday > curday) { if (curmonth == 1) { for (c in gday..MonthSize(12, curyear - 1) - 1) { calc += 1 } } else { for (c in gday..MonthSize(curmonth - 1, curyear) - 1) { calc += 1 } } for (c in 1..curday) { calc += 1 } } else { for (c in gday..curday - 1) { calc += 1 } } return calc } fun main(args: Array<String>) { try { arrayOf("", "") val currentyear = Calendar.getInstance().get(Calendar.YEAR) val currentmonth = Calendar.getInstance().get(Calendar.MONTH) + 1 val currentday = Calendar.getInstance().get(Calendar.DAY_OF_MONTH) var inputday = 0 var inputmonth = 0 var inputyear = 0 val inp = Scanner(System.`in`) val input = inp.nextLine().split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val inpn = intArrayOf(Integer.parseInt(input[0]), Integer.parseInt(input[1]), Integer.parseInt(input[2])) var cont = true if (Integer.parseInt(input[0]) < 1 || Integer.parseInt(input[0]) > 31) { println("Please enter valid day. 1 | 31") cont = false } else { inputday = Integer.parseInt(input[0]) } if (Integer.parseInt(input[1]) < 1 || Integer.parseInt(input[1]) > 12) { println("Please enter valid month. 1 | 12") cont = false } else { inputmonth = Integer.parseInt(input[1]) } if (Integer.parseInt(input[2]) < 1) { println("Please enter valid year. 1 | " + currentyear) cont = false } else { inputyear = Integer.parseInt(input[2]) } if (inpn[2] > currentyear) { println("Please enter day in the past.") cont = false } else if (inpn[2] == currentyear) { if (inpn[1] > currentmonth) { println("Please enter day in the past.") cont = false } else if (inpn[1] == currentmonth) { if (inpn[0] > currentday) { println("Please enter day in the past.") cont = false } else if (inpn[0] == currentday) { println("You entered today!") cont = false } else if (inpn[0] < currentday) { cont = true } } } if (cont) { println("\n\n\n\n$inputday/$inputmonth/$inputyear Was:") println("-----------------") println(GetDayCount(currentday, currentmonth, currentyear, inputday, inputmonth, inputyear)) println("-----------------") println("Days ago. \n") } } catch (e: Exception) { println("Error, Please enter input as '[day] [month] [year]' EXAMPLE: 01 01 2000") } }
calendar/dayssince.kt
2071887877
package openbaseball.vertx import io.vertx.core.AsyncResult import io.vertx.core.Vertx import io.vertx.core.json.JsonObject import io.vertx.core.logging.LoggerFactory abstract class VerticleDeployer { private val logger = LoggerFactory.getLogger(javaClass) /** * Deploy a verticle. * * @param vertx a Vertx instance to deploy the verticle. * @param config the root (top-level) JSON configuration object. * @param result callback for handling success or failure of the deployment. */ abstract fun deploy(vertx: Vertx, config: JsonObject, result: (AsyncResult<String>) -> Unit) /** * Deploy a verticle unconditionally. If the verticle fails to deploy for whatever reason then the vertx instance * will be shutdown. * * @param vertx a Vertx instance to deploy the verticle. * @param config the root (top-level) JSON configuration object. */ fun deployRequired(vertx: Vertx, config: JsonObject) { deploy(vertx, config, { if (it.failed()) { vertx.close() logger.error("Required verticle deploy failed. Server shutdown initiated!", it.cause()) } }) } }
src/main/kotlin/openbaseball/vertx/VerticleDeployer.kt
864580128
package com.andretietz.retroauth.demo.auth import android.annotation.SuppressLint import android.os.Bundle import android.webkit.CookieManager import android.webkit.WebView import android.webkit.WebViewClient import androidx.lifecycle.lifecycleScope import com.andretietz.retroauth.AuthenticationActivity import com.andretietz.retroauth.Credentials import com.andretietz.retroauth.demo.databinding.ActivityLoginBinding import com.github.scribejava.core.oauth.OAuth20Service import com.squareup.moshi.JsonClass import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import retrofit2.http.GET import retrofit2.http.Header import javax.inject.Inject @AndroidEntryPoint class LoginActivity : AuthenticationActivity() { @Inject lateinit var helper: OAuth20Service @Inject lateinit var api: SignInApi @SuppressLint("SetJavaScriptEnabled") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) CookieManager.getInstance().removeAllCookies { } val views = ActivityLoginBinding.inflate(layoutInflater) setContentView(views.root) views.webView.loadUrl(helper.authorizationUrl) views.webView.settings.javaScriptEnabled = true views.webView.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { val authorization = helper.extractAuthorization(url) val code = authorization.code if (code == null) { view.loadUrl(url) } else { lifecycleScope.launch(Dispatchers.IO) { val token = helper.getAccessToken(code) val userInfo = api.getUser("Bearer ${token.accessToken}") withContext(Dispatchers.Main) { val account = createOrGetAccount(userInfo.login) storeCredentials( account, GithubAuthenticator.createTokenType(application), Credentials(token.accessToken) ) // storeUserData(account, "email", userInfo.email) finalizeAuthentication(account) } } } return true } } } interface SignInApi { /** * We call this method right after authentication in order to get user information * to store within the account. At this point of time, the account and it's token isn't stored * yet, why we cannot use the annotation. * * https://docs.github.com/en/rest/reference/users#get-the-authenticated-user */ @GET("user") suspend fun getUser(@Header("Authorization") token: String): User @JsonClass(generateAdapter = true) data class User( val login: String ) } }
demo-android/src/main/java/com/andretietz/retroauth/demo/auth/LoginActivity.kt
789701191
/*- * ========================LICENSE_START================================= * ids-dataflow-control * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.dataflowcontrol.lucon import alice.tuprolog.Struct import alice.tuprolog.Term import de.fhg.aisec.ids.api.router.CounterExample import java.util.LinkedList class CounterExampleImpl(term: Term) : CounterExample() { init { val traceIterator = (term as Struct).listIterator() val steps = LinkedList<String>() // process explanation val reasonIterator = (traceIterator.next() as Struct).listIterator() val sb = StringBuilder() .append("Service ") .append(reasonIterator.next().toString()) .append(" may receive messages") reasonIterator.next() // val explanation = reasonIterator.next() // if (explanation.isList) { // sb.append(" labeled [") // appendCSList(sb, explanation) // sb.append("]") // } sb.append(", which is forbidden by rule \"") .append(reasonIterator.next().toString()) .append("\".") this.explanation = sb.toString() // process steps and prepend them to list (inverse trace to get the right order) traceIterator.forEachRemaining { t: Term? -> steps.addFirst(termToStep(t)) } this.steps = steps } companion object { fun termToStep(t: Term?): String? { if (t == null) { return null } val traceEntry = t as Struct val sb = StringBuilder() // node name is the head of the list val node = traceEntry.listHead().toString() sb.append(node) // the label list is the new head of the remaining list (tail) val labelList = traceEntry.listTail().listHead() return if (!labelList.isEmptyList) { sb.append(" receives message labelled ") appendCSList(sb, labelList) sb.toString() } else { sb.append(" receives message without labels").toString() } } private fun appendCSList(sb: StringBuilder?, l: Term?) { if (sb == null || l == null) { return } if (l.isList && !l.isEmptyList) { val listIterator = (l as Struct).listIterator() // add first element sb.append(listIterator.next().toString()) // add remaining elements listIterator.forEachRemaining { lt: Term -> sb.append(", ").append(lt.toString()) } } } } }
ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/CounterExampleImpl.kt
3554564850
package io.magnaura.server import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.slf4j.LoggerFactory object Logger { private val logger = LoggerFactory.getLogger("io.magnaura.server") fun reportFromCompiler(severity: CompilerMessageSeverity, message: String) { when (severity) { CompilerMessageSeverity.EXCEPTION, CompilerMessageSeverity.ERROR -> logger.error("$message") CompilerMessageSeverity.STRONG_WARNING, CompilerMessageSeverity.WARNING -> logger.warn("$message") CompilerMessageSeverity.INFO, CompilerMessageSeverity.LOGGING, CompilerMessageSeverity.OUTPUT -> logger.info("$message") } } }
server/src/io/magnaura/server/Logger.kt
2813135703
package i_introduction._9_Extension_Functions import org.junit.Assert.assertEquals import org.junit.Test class _09_Extension_Functions() { @Test fun testIntExtension() { assertEquals("Rational number creation error: ", RationalNumber(4, 1), 4.r()) } @Test fun testPairExtension() { assertEquals("Rational number creation error: ", RationalNumber(2, 3), Pair(2, 3).r()) } }
test/i_introduction/_9_Extension_Functions/_09_Extension_Functions.kt
2550654373
package net.yuzumone.bergamio.di import android.content.Context import android.support.v4.app.Fragment import dagger.Module import dagger.Provides @Module class FragmentModule(val fragment: Fragment) { @Provides fun provideContext(): Context { return fragment.context!! } }
app/src/main/kotlin/net/yuzumone/bergamio/di/FragmentModule.kt
2865446610
package com.muhron.kotlin_java_interpolator fun main(args: Array<String>) { f10() } fun f10(): Unit { val str = Utility.returnStringJava() println(str?.length) println(str.length) val strNotNull: String = str val strNullable: String? = str } fun f11(): Unit { val str: String = Utility.returnStringJava() println(str.length) println(str?.length) } fun f12(): Unit { val str: String? = Utility.returnStringJava() println(str?.length) // println(str.length)は、コンパイルエラー }
kotlin/kotlin_java_interpolator/src/main/kotlin/com/muhron/kotlin_java_interpolator/java_method_usage.kt
19200311
/* 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.action import uk.co.nickthecoder.tickle.Actor class EventAction(val actor: Actor, val eventName: String) : Action { override fun act(): Boolean { actor.event(eventName) return true } }
tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/action/EventAction.kt
507199593
package br.com.wakim.eslpodclient.ui.rx import rx.subjects.PublishSubject class ConnectivityPublishSubject { companion object { val INSTANCE: PublishSubject<Boolean> = PublishSubject.create<Boolean>() } }
app/src/main/java/br/com/wakim/eslpodclient/ui/rx/ConnectivityPublishSubject.kt
3437058762
package mcgars.com.zoomimage.listeners import android.view.View import android.widget.ImageView import com.alexvasilkov.gestures.animation.ViewPositionAnimator import com.alexvasilkov.gestures.transition.ViewsCoordinator import com.alexvasilkov.gestures.transition.ViewsTracker import com.alexvasilkov.gestures.transition.ViewsTransitionAnimator class FromImageViewListener<ID>( private val imageView: ImageView, private val mTracker: ViewsTracker<ID>, private val mAnimator: ViewsTransitionAnimator<ID> ) : ViewsCoordinator.OnRequestViewListener<ID> { init { mAnimator.addPositionUpdateListener(UpdateListener()) } override fun onRequestView(id: ID) { // Trying to find requested view on screen. If it is not currently on screen // or it is not fully visible than we should scroll to it at first. val position = mTracker.getPositionForId(id) if (position == ViewsTracker.NO_POSITION) { return // Nothing we can do } mAnimator.setFromView(id, imageView) } private inner class UpdateListener : ViewPositionAnimator.PositionUpdateListener { override fun onPositionUpdate(state: Float, isLeaving: Boolean) { imageView.visibility = if (state == 0f && isLeaving) View.VISIBLE else View.INVISIBLE } } }
zoomimage/src/main/java/mcgars/com/zoomimage/listeners/FromImageViewListener.kt
4019326901
package com.fsck.k9.ui.messagelist import com.fsck.k9.Preferences import com.fsck.k9.mailstore.MessageListRepository import kotlinx.coroutines.CoroutineScope class MessageListLiveDataFactory( private val messageListLoader: MessageListLoader, private val preferences: Preferences, private val messageListRepository: MessageListRepository ) { fun create(coroutineScope: CoroutineScope, config: MessageListConfig): MessageListLiveData { return MessageListLiveData(messageListLoader, preferences, messageListRepository, coroutineScope, config) } }
app/ui/legacy/src/main/java/com/fsck/k9/ui/messagelist/MessageListLiveDataFactory.kt
433242001
package com.incentive.yellowpages.utils import android.content.Context import android.support.v4.view.animation.PathInterpolatorCompat import android.transition.Transition import android.view.animation.AnimationUtils import android.view.animation.Interpolator class AnimUtils private constructor() { init { throw RuntimeException("Unable to instantiate class " + javaClass.canonicalName) } open class TransitionListenerAdapter : Transition.TransitionListener { override fun onTransitionStart(transition: Transition) { } override fun onTransitionEnd(transition: Transition) { } override fun onTransitionCancel(transition: Transition) { } override fun onTransitionPause(transition: Transition) { } override fun onTransitionResume(transition: Transition) { } } companion object { private var overshoot: Interpolator? = null val EASE_OUT_CUBIC = PathInterpolatorCompat.create(0.215f, 0.61f, 0.355f, 1f)!! fun getOvershootInterpolator(context: Context): Interpolator { if (overshoot == null) { overshoot = AnimationUtils.loadInterpolator(context, android.R.interpolator.overshoot) } return overshoot!! } } }
app/src/main/kotlin/com/incentive/yellowpages/utils/AnimUtils.kt
3376237821
package com.github.thetric.iliasdownloader.connector import com.github.thetric.iliasdownloader.connector.model.CourseFile import com.github.thetric.iliasdownloader.connector.model.CourseFolder /** * Visitor for the traversal of the Ilias course items. * * @param C context of the traversal (e.g. the current dir, upload URL) */ interface IliasItemListener<C> { /** * Handles the visitation of a [CourseFolder]. * * @return resolved context of the child items. */ fun handleFolder(parentContext: C, folder: CourseFolder): C fun handleFile(parentContext: C, file: CourseFile) }
src/main/kotlin/com/github/thetric/iliasdownloader/connector/IliasItemListener.kt
3968524461
package com.fuyoul.sanwenseller.ui.order import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator import com.fuyoul.sanwenseller.R import com.fuyoul.sanwenseller.base.BaseActivity import com.fuyoul.sanwenseller.configs.TopBarOption import com.fuyoul.sanwenseller.structure.model.EmptyM import com.fuyoul.sanwenseller.structure.presenter.EmptyP import com.fuyoul.sanwenseller.structure.view.EmptyV import com.fuyoul.sanwenseller.ui.order.fragment.NormalTestFragment import com.fuyoul.sanwenseller.ui.order.fragment.QuickTestFragment import com.fuyoul.sanwenseller.utils.AddFragmentUtils import com.netease.nim.uikit.StatusBarUtils import kotlinx.android.synthetic.main.appointmentlayout.* import net.lucode.hackware.magicindicator.FragmentContainerHelper import net.lucode.hackware.magicindicator.buildins.UIUtil import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView /** * @author: chen * @CreatDate: 2017\10\30 0030 * @Desc: */ class AppointMentTimeActivity : BaseActivity<EmptyM, EmptyV, EmptyP>() { private val mFragmentContainerHelper = FragmentContainerHelper() override fun setLayoutRes(): Int = R.layout.appointmentlayout override fun initData(savedInstanceState: Bundle?) { StatusBarUtils.setTranslucentForImageView(this, topFuncLayout) StatusBarUtils.StatusBarLightMode(this, R.color.color_white) val fragments = ArrayList<Fragment>() fragments.add(NormalTestFragment()) fragments.add(QuickTestFragment()) val addFragmentUtils = AddFragmentUtils(this, R.id.appointmentContent) val commonNavigator = CommonNavigator(this) commonNavigator.adapter = object : CommonNavigatorAdapter() { override fun getTitleView(p0: Context?, p1: Int): IPagerTitleView { val colorTransitionPagerTitleView = ColorTransitionPagerTitleView(this@AppointMentTimeActivity) colorTransitionPagerTitleView.width = UIUtil.getScreenWidth(this@AppointMentTimeActivity) / 4 colorTransitionPagerTitleView.normalColor = resources.getColor(R.color.color_666666) colorTransitionPagerTitleView.selectedColor = resources.getColor(R.color.color_3CC5BC) colorTransitionPagerTitleView.text = when (p1) { 0 -> "详测" 1 -> "闪测" else -> "闪测" } colorTransitionPagerTitleView.setOnClickListener({ mFragmentContainerHelper.handlePageSelected(p1, true) addFragmentUtils.showFragment(fragments[p1], fragments[p1].javaClass.name) }) return colorTransitionPagerTitleView } override fun getCount(): Int = fragments.size override fun getIndicator(p0: Context?): IPagerIndicator { val indicator = LinePagerIndicator(this@AppointMentTimeActivity) indicator.mode = LinePagerIndicator.MODE_EXACTLY indicator.lineHeight = UIUtil.dip2px(this@AppointMentTimeActivity, 4.0).toFloat() indicator.lineWidth = UIUtil.dip2px(this@AppointMentTimeActivity, 15.0).toFloat() indicator.roundRadius = UIUtil.dip2px(this@AppointMentTimeActivity, 3.0).toFloat() indicator.startInterpolator = AccelerateInterpolator() indicator.endInterpolator = DecelerateInterpolator(2.0f) indicator.setColors(resources.getColor(R.color.color_3CC5BC)) return indicator } } appointmentIndicator.navigator = commonNavigator mFragmentContainerHelper.attachMagicIndicator(appointmentIndicator) mFragmentContainerHelper.handlePageSelected(0, false) addFragmentUtils.showFragment(fragments[0], fragments[0].javaClass.name) } override fun setListener() { toolbarBack.setOnClickListener { finish() } } override fun getPresenter(): EmptyP = EmptyP(initViewImpl()) override fun initViewImpl(): EmptyV = EmptyV() override fun initTopBar(): TopBarOption = TopBarOption() }
app/src/main/java/com/fuyoul/sanwenseller/ui/order/AppointMentTimeActivity.kt
2014422097
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.services import ink.abb.pogo.scraper.Bot import ink.abb.pogo.scraper.Context import ink.abb.pogo.scraper.Settings import ink.abb.pogo.scraper.startBot import ink.abb.pogo.scraper.util.Log import ink.abb.pogo.scraper.util.credentials.GoogleAutoCredentials import ink.abb.pogo.scraper.util.io.SettingsJSONWriter import okhttp3.OkHttpClient import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import java.io.File import java.util.concurrent.CountDownLatch import javax.annotation.PreDestroy import kotlin.concurrent.thread @Service class BotService { @Autowired lateinit var http: OkHttpClient private val bots: MutableList<Bot> = mutableListOf() val settingsJSONWriter = SettingsJSONWriter() fun submitBot(name: String): Settings { val settings = settingsJSONWriter.load(name) addBot(startBot(settings, http)) settingsJSONWriter.save(settings) // Is this needed after starting? return settings } @Synchronized fun addBot(bot: Bot) { bots.add(bot) } @Synchronized fun removeBot(bot: Bot) { bots.remove(bot) } fun getJSONConfigBotNames(): List<String> { return settingsJSONWriter.getJSONConfigBotNames() } fun getBotContext(name: String): Context { val bot = bots.find { it.settings.name == name } bot ?: throw IllegalArgumentException("Bot $name doesn't exists !") return bot.ctx } @Synchronized fun getAllBotSettings(): List<Settings> { return bots.map { it.settings.copy(credentials = GoogleAutoCredentials(), restApiPassword = "") } } @Synchronized fun doWithBot(name: String, action: (bot: Bot) -> Unit): Boolean { val bot = bots.find { it.settings.name == name } ?: return false action(bot) return true } @PreDestroy @Synchronized fun stopAllBots() { val latch = CountDownLatch(bots.size) bots.forEach { thread { it.stop() latch.countDown() } } latch.await() } }
src/main/kotlin/ink/abb/pogo/scraper/services/BotService.kt
3655044706
package com.sleazyweasel.eboshi import org.junit.Assert.assertEquals import org.junit.Test import org.mockito.Mockito.`when` import org.mockito.Mockito.verify import spark.Request import spark.Response import java.util.* class ClientRoutesTest { private val clientDataAccess = mock(ClientDataAccess::class) @Test fun testGetAll() { val createdDate = Date() val expected = JsonApiResponse(listOf(JsonApiObject("5", "clients", mapOf("name" to "John", "created_at" to createdDate)))) clientDataAccess.allClients = { listOf(Client(mapOf("id" to 5, "name" to "John", "created_at" to createdDate))) } val testClass = ClientRoutes(clientDataAccess) val result = testClass.getAll() assertEquals(expected, result) } @Test fun testCreate() { val createdAtString = "1970-08-07T10:20:00Z" val clientAttributes = mapOf("name" to "John", "created_at" to createdAtString) val convertedAttributes = mapOf("name" to "John", "created_at" to isoDateFormat.parse(createdAtString)) val request = JsonApiRequest(JsonApiObject(null, "clients", clientAttributes)) val expected = mapOf("data" to JsonApiObject("555", "clients", convertedAttributes)) clientDataAccess.insert = { client: Client -> assertEquals(Client(convertedAttributes), client); Client(convertedAttributes.plus("id" to 555)) } val response = mock(Response::class) val testClass = ClientRoutes(clientDataAccess) val result = testClass.create(request, response) assertEquals(expected, result) verify(response).status(201) } @Test fun testDelete() { val response = mock(Response::class) val request = mock(Request::class) var calledValue: Int? = null clientDataAccess.delete = { i: Int -> calledValue = i } `when`(request.params(":id")).thenReturn("555") val testClass = ClientRoutes(clientDataAccess) testClass.delete(request, response) verify(response).status(204) assertEquals(555, calledValue) } }
kotlin_spark/src/test/java/com/sleazyweasel/eboshi/ClientRoutesTest.kt
221613878
/* * Copyright 2016 Nicolas Fränkel * * 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 ch.frankel.kaadin.common import ch.frankel.kaadin.* import com.vaadin.server.* import org.mockito.Mockito.* import org.testng.annotations.* import java.util.Locale.* class SessionTest { private lateinit var vaadinSession: VaadinSession @BeforeMethod private fun setUp() { vaadinSession = mock(VaadinSession::class.java) VaadinSession.setCurrent(vaadinSession) } @Test fun `session should be configurable`() { session { this.locale = FRENCH } verify(vaadinSession).locale = FRENCH } @Test fun `session locale should be set`() { sessionLocale(FRENCH) verify(vaadinSession).locale = FRENCH } @AfterMethod private fun tearDown() { VaadinSession.setCurrent(null) } }
kaadin-core/src/test/kotlin/ch/frankel/kaadin/common/SessionTest.kt
1258757734
package io.innofang.abstract_factory.example.kotlin /** * Created by Inno Fang on 2017/9/2. */ abstract class CakeCream { abstract fun cream() }
src/io/innofang/abstract_factory/example/kotlin/CakeCream.kt
3905752569
package com.ghstudios.android.features.weapons.detail import android.graphics.Typeface import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.ghstudios.android.AssetLoader import com.ghstudios.android.data.classes.ElementStatus import com.ghstudios.android.data.classes.Weapon import com.ghstudios.android.mhgendatabase.R import com.ghstudios.android.mhgendatabase.databinding.ViewWeaponDetailBowBinding import com.ghstudios.android.util.getColorCompat /** * Inflates bow data into a view and binds the bow data. * Use in the WeaponDetailFragment or any sort of fragment to show full bow data. */ class WeaponBowDetailViewHolder(parent: ViewGroup) : WeaponDetailViewHolder { private val binding: ViewWeaponDetailBowBinding private val chargeCells: List<TextView> init { val inflater = LayoutInflater.from(parent.context) binding = ViewWeaponDetailBowBinding.inflate(inflater, parent, true) chargeCells = with(binding) { listOf( weaponBowCharge1, weaponBowCharge2, weaponBowCharge3, weaponBowCharge4 ) } } override fun bindWeapon(weapon: Weapon) { val context = binding.root.context with(binding) { // Usual weapon parameters attackValue.text = weapon.attack.toString() affinityValue.text = weapon.affinity + "%" defenseValue.text = weapon.defense.toString() slots.setSlots(weapon.numSlots, 0) // bind weapon element (todo: if awaken element ever returns...make an isAwakened flag instead) if (weapon.elementEnum != ElementStatus.NONE) { element1Icon.setImageDrawable(AssetLoader.loadIconFor(weapon.elementEnum)) element1Value.text = weapon.elementAttack.toString() element1Group.visibility = View.VISIBLE } weaponBowArc.text = weapon.recoil // Charge levels for ((view, level) in chargeCells.zip(weapon.charges)) { view.visibility = View.VISIBLE view.text = AssetLoader.localizeChargeLevel(level) if (level.locked) { val lockColor = context.getColorCompat(R.color.text_color_secondary) view.setTextColor(lockColor) } } // Internal function to "enable" a weapon coating view fun setCoating(enabled: Boolean, view: TextView) { if (enabled) { val color = context.getColorCompat(R.color.text_color_focused) view.setTextColor(color) view.setTypeface(null, Typeface.BOLD) } } weapon.coatings?.let { coatings -> setCoating(coatings.power1, power1Text) setCoating(coatings.power2, power2Text) setCoating(coatings.elem1, element1Text) setCoating(coatings.elem2, element2Text) setCoating(coatings.crange, crangeText) setCoating(coatings.poison, poisonText) setCoating(coatings.para, paraText) setCoating(coatings.sleep, sleepText) setCoating(coatings.exhaust, exhaustText) setCoating(coatings.blast, blastText) setCoating(coatings.hasPower, powerLabel) setCoating(coatings.hasElem, elementLabel) } } } }
app/src/main/java/com/ghstudios/android/features/weapons/detail/WeaponBowDetailViewHolder.kt
26152217
/* * 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 org.intellij.plugins.hcl.codeinsight import com.intellij.codeInsight.FileModificationService import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleManager import org.intellij.plugins.hcl.psi.HCLPsiUtil import org.intellij.plugins.hcl.psi.impl.HCLStringLiteralMixin class AddClosingQuoteQuickFix(element: PsiElement) : LocalQuickFixAndIntentionActionOnPsiElement(element) { companion object { private val LOG = Logger.getInstance(AddClosingQuoteQuickFix::class.java) } override fun getText(): String { return "Add closing quote" } override fun getFamilyName(): String { return text } override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) { if (!FileModificationService.getInstance().prepareFileForWrite(file)) return val element = startElement val rawText = element.text if (element !is HCLStringLiteralMixin) { LOG.error("Quick fix was applied to unexpected element", rawText, element.parent.text) return } if (rawText.isEmpty()) { LOG.error("Quick fix was applied to empty string element", rawText, element.parent.text) return } val content = HCLPsiUtil.stripQuotes(rawText) val quote = element.quoteSymbol CodeStyleManager.getInstance(project).performActionWithFormatterDisabled { element.updateText(quote + content + quote) } } }
src/kotlin/org/intellij/plugins/hcl/codeinsight/AddClosingQuoteQuickFix.kt
2583640829
package com.getroadmap.r2rlib.models import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName /** * Created by jan on 11/07/16. */ /** * airline integer Airline (index into airlines array) * flight string Flight number */ data class AirCodeshare(@SerializedName("airline") @Expose val airline: Int?, @SerializedName("flight") @Expose val flight: String?) : Parcelable { constructor(parcel: Parcel) : this( parcel.readValue(Int::class.java.classLoader) as? Int, parcel.readString()) { } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeValue(airline) parcel.writeString(flight) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<AirCodeshare> { override fun createFromParcel(parcel: Parcel): AirCodeshare { return AirCodeshare(parcel) } override fun newArray(size: Int): Array<AirCodeshare?> { return arrayOfNulls(size) } } }
library/src/main/java/com/getroadmap/r2rlib/models/AirCodeshare.kt
282912671
package com.github.christophpickl.kpotpourri.http4k.internal import com.github.christophpickl.kpotpourri.common.web.QueryParams import com.github.christophpickl.kpotpourri.http4k.AnyRequestOpts import com.github.christophpickl.kpotpourri.http4k.BaseUrlByString import com.github.christophpickl.kpotpourri.http4k.GlobalHttp4kConfigurable import com.github.christophpickl.kpotpourri.test4k.hamkrest_matcher.shouldMatchValue import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.whenever import org.testng.annotations.DataProvider import org.testng.annotations.Test @Test class UrlBuilderTest { private val emptyParams = emptyMap<String, String>() @DataProvider fun provideUrlBuildings(): Array<Array<out Any?>> = arrayOf( arrayOf("", null, mapOf("request" to "1"), emptyParams, "?request=1"), arrayOf("", null, emptyParams, mapOf("global" to "1"), "?global=1"), arrayOf("", null, mapOf("request" to "1"), mapOf("global" to "2"), "?global=2&request=1"), arrayOf("", null, mapOf("key" to "request"), mapOf("key" to "global"), "?key=request"), arrayOf("url?u=0", null, mapOf("r" to "1"), mapOf("g" to "2"), "url?u=0&g=2&r=1"), arrayOf("url?key=inUrl", null, mapOf("key" to "request"), mapOf("key" to "global"), "url?key=request"), arrayOf("url?key=inUrl", null, emptyParams, mapOf("key" to "global"), "url?key=global"), arrayOf("url?key=inUrl", null, mapOf("key" to "request"), emptyParams, "url?key=request"), arrayOf("relativeUrl", "globalBaseUrl", emptyParams, emptyParams, "globalBaseUrl/relativeUrl") ) @Test(dataProvider = "provideUrlBuildings") fun `buildUrl - sunshine`(url: String, givenBaseUrl: String?, requestParams: QueryParams, globalParams: QueryParams, expected: String) { val requestOpts = mock<AnyRequestOpts>() whenever(requestOpts.disableBaseUrl).thenReturn(givenBaseUrl == null) whenever(requestOpts.queryParams).thenReturn(requestParams.toMutableMap()) val globalConfig = mock<GlobalHttp4kConfigurable>() if (givenBaseUrl != null) whenever(globalConfig.baseUrl).thenReturn(BaseUrlByString(givenBaseUrl)) whenever(globalConfig.queryParams).thenReturn(globalParams.toMutableMap()) buildUrl(url, globalConfig, requestOpts) shouldMatchValue expected } }
http4k/src/test/kotlin/com/github/christophpickl/kpotpourri/http4k/internal/UrlBuilderTest.kt
1596704363
package com.github.christophpickl.kpotpourri.wiremock4k.response import com.github.christophpickl.kpotpourri.wiremock4k.WiremockMethod import com.github.christophpickl.kpotpourri.wiremock4k.testng.InjectMockPort import com.github.christophpickl.kpotpourri.wiremock4k.testng.WiremockTestngListener import com.github.kittinunf.fuel.Fuel import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.testng.annotations.Listeners import org.testng.annotations.Test @Test @Listeners(WiremockTestngListener::class) class PrepareResponseTest { // MINOR @InjectWiremockUrl private lateinit var wiremockUrl: String @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") @InjectMockPort private lateinit var port: Integer fun `given - When requested, Then not throws`() { givenWiremock(WiremockMethod.GET, "/", 201, "response body") val (_, response, _) = Fuel.get("http://localhost:$port").response() assertThat(String(response.data), equalTo("response body")) assertThat(response.httpStatusCode, equalTo(201)) } } @Test class PrepareResponseExtensionsTest { fun `ResponseDefinitionBuilder withHeaders - sunshine`() { assertThat(ResponseDefinitionBuilder().withHeaders("a" to "1").build().headers.getHeader("a").values()[0], equalTo("1")) } }
wiremock4k/src/test/kotlin/com/github/christophpickl/kpotpourri/wiremock4k/response/prepare_response_test.kt
1011093909
package com.oboenikui.campusfelica import android.Manifest import android.app.PendingIntent import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.nfc.NfcAdapter import android.nfc.Tag import android.nfc.TagLostException import android.nfc.tech.NfcF import android.os.Bundle import android.os.Handler import android.support.v13.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.widget.TextView import android.widget.Toast import java.io.ByteArrayOutputStream import java.util.* import kotlin.concurrent.thread import com.oboenikui.campusfelica.ExecuteNfcF as ex class ScannerActivity : AppCompatActivity() { lateinit var adapter: NfcAdapter private var filters: Array<IntentFilter>? = null private var techLists: Array<Array<String>>? = null private var pendingIntent: PendingIntent? = null private val REQUEST_WRITE_STORAGE = 112 private var index = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_scanner) adapter = NfcAdapter.getDefaultAdapter(this) val tech = IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED) tech.priority = IntentFilter.SYSTEM_HIGH_PRIORITY filters = arrayOf(tech) pendingIntent = PendingIntent.getActivity(this, 0, Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0) techLists = arrayOf(arrayOf<String>(NfcF::class.java.name)) val hasPermission = (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) if (!hasPermission) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_WRITE_STORAGE) } } public override fun onResume() { adapter.enableForegroundDispatch( this, pendingIntent, filters, techLists) super.onResume() } public override fun onPause() { if (this.isFinishing) { adapter.disableForegroundDispatch(this) } super.onPause() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { REQUEST_WRITE_STORAGE -> { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { } else { Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show() } } } } override fun onNewIntent(intent: Intent) { val action = intent.action if (action == NfcAdapter.ACTION_TECH_DISCOVERED) { val handler = Handler() val textView = findViewById(R.id.scan_results) as TextView thread { val nfcF = NfcF.get(intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)) nfcF.connect() val idm = try { Arrays.copyOfRange(nfcF.transceive(ex.POLLING_COMMAND), 2, 10) } catch (e: TagLostException) { return@thread } val stream = ByteArrayOutputStream() println(nfcF.maxTransceiveLength) val service = ex.createService(CampusFeliCa.SERVICE_CODE_INFORMATION, CampusFeliCa.SERVICE_CODE_BALANCE) val block = ex.createBlock(3, 1) stream.write(2 + idm.size + service.size + block.size) stream.write(6) stream.write(idm) stream.write(service) stream.write(block) val array = stream.toByteArray() stream.close() val result = ex.bytesToText(nfcF.transceive(array)) handler.post { textView.text = result } /*for (i in index..65535) { val stream = ByteArrayOutputStream() if (i % 100 == 0) { println(i) } val blockList = ex.createBlock(10) stream.write(2 + idm.size + 3 + blockList.size) stream.write(6) stream.write(idm) stream.write(1) stream.write(ByteBuffer.allocate(2).putChar(i.toChar()).array()) stream.write(blockList) try { val response = nfcF.transceive(stream.toByteArray()) if (i == 0) { first = response } else { handler.post { file.appendText("$i:${ex.bytesToText(response ?: byteArrayOf())}\n") } } index = i } catch (e: TagLostException) { e.printStackTrace() System.err.println(i) break } finally { stream.close() } }*/ nfcF.close() } } } }
app/src/main/java/com/oboenikui/campusfelica/ScannerActivity.kt
3805400595
// Copyright 2020 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.gcloud.spanner import com.google.cloud.spanner.DatabaseId import com.google.cloud.spanner.Spanner import java.time.Duration import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit import java.util.logging.Logger import kotlinx.coroutines.TimeoutCancellationException /** * Wraps a connection to a Spanner database for convenient access to an [AsyncDatabaseClient], the * [DatabaseId], waiting for the connection to be ready, etc. */ class SpannerDatabaseConnector( projectName: String, instanceName: String, databaseName: String, private val readyTimeout: Duration, transactionTimeout: Duration, maxTransactionThreads: Int, emulatorHost: String?, ) : AutoCloseable { init { require(maxTransactionThreads > 0) } private val spanner: Spanner = buildSpanner(projectName, emulatorHost).also { Runtime.getRuntime() .addShutdownHook( Thread { System.err.println("Ensuring Spanner is closed...") if (!it.isClosed) { it.close() } System.err.println("Spanner closed") } ) } private val transactionExecutor: Lazy<ExecutorService> = lazy { if (emulatorHost == null) { ThreadPoolExecutor(1, maxTransactionThreads, 60L, TimeUnit.SECONDS, LinkedBlockingQueue()) } else { // Spanner emulator only supports a single read-write transaction at a time. Executors.newSingleThreadExecutor() } } val databaseId: DatabaseId = DatabaseId.of(projectName, instanceName, databaseName) val databaseClient: AsyncDatabaseClient by lazy { spanner.getAsyncDatabaseClient(databaseId, transactionExecutor.value, transactionTimeout) } /** * Suspends until [databaseClient] is ready, throwing a * [kotlinx.coroutines.TimeoutCancellationException] if [readyTimeout] is reached. */ suspend fun waitUntilReady() { databaseClient.waitUntilReady(readyTimeout) } override fun close() { spanner.close() if (transactionExecutor.isInitialized()) { transactionExecutor.value.shutdown() } } /** * Executes [block] with this [SpannerDatabaseConnector] once it's ready, ensuring that this is * closed when done. */ suspend fun <R> usingSpanner(block: suspend (spanner: SpannerDatabaseConnector) -> R): R { use { spanner -> try { logger.info { "Waiting for Spanner connection to $databaseId to be ready..." } spanner.waitUntilReady() logger.info { "Spanner connection to $databaseId ready" } } catch (e: TimeoutCancellationException) { // Closing Spanner can take a long time (e.g. 1 minute) and delay the // exception being surfaced, so we log here to give immediate feedback. logger.severe { "Timed out waiting for Spanner to be ready" } throw e } return block(spanner) } } companion object { private val logger = Logger.getLogger(this::class.java.name) } } /** Builds a [SpannerDatabaseConnector] from these flags. */ private fun SpannerFlags.toSpannerDatabaseConnector(): SpannerDatabaseConnector { return SpannerDatabaseConnector( projectName = projectName, instanceName = instanceName, databaseName = databaseName, readyTimeout = readyTimeout, transactionTimeout = transactionTimeout, maxTransactionThreads = maxTransactionThreads, emulatorHost = emulatorHost, ) } /** * Executes [block] with a [SpannerDatabaseConnector] resource once it's ready, ensuring that the * resource is closed. */ suspend fun <R> SpannerFlags.usingSpanner( block: suspend (spanner: SpannerDatabaseConnector) -> R ): R { return toSpannerDatabaseConnector().usingSpanner(block) }
src/main/kotlin/org/wfanet/measurement/gcloud/spanner/SpannerDatabaseConnector.kt
348600507
@file:Suppress("DEPRECATION") package com.thanosfisherman.mayi import android.app.Fragment import android.content.pm.PackageManager import android.os.Build import androidx.annotation.RequiresApi class MayIFragment : Fragment(), PermissionToken { companion object { const val TAG = "MayIFragment" private const val PERMISSION_REQUEST_CODE = 1001 } private var permissionResultSingleListener: ((PermissionBean) -> Unit)? = null private var rationaleSingleListener: ((PermissionBean, PermissionToken) -> Unit)? = null private var permissionResultMultiListener: ((List<PermissionBean>) -> Unit)? = null private var rationaleMultiListener: ((List<PermissionBean>, PermissionToken) -> Unit)? = null private var isShowingNativeDialog: Boolean = false private lateinit var rationalePermissions: List<String> private lateinit var permissionMatcher: PermissionMatcher @RequiresApi(api = Build.VERSION_CODES.M) override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == PERMISSION_REQUEST_CODE) { isShowingNativeDialog = false if (grantResults.isEmpty()) return val beansResultList = mutableListOf<PermissionBean>() for (i in permissions.indices) { if (grantResults[i] == PackageManager.PERMISSION_DENIED) { if (shouldShowRequestPermissionRationale(permissions[i])) beansResultList.add(PermissionBean(permissions[i], isGranted = false, isPermanentlyDenied = false)) else beansResultList.add(PermissionBean(permissions[i], isGranted = false, isPermanentlyDenied = true)) } else { beansResultList.add(PermissionBean(permissions[i], isGranted = true, isPermanentlyDenied = false)) } } permissionResultSingleListener?.invoke(beansResultList[0]) permissionResultMultiListener?.let { val grantedBeans = permissionMatcher.grantedPermissions.map { PermissionBean(it, true) } it(beansResultList.plus(grantedBeans)) } } } @RequiresApi(api = Build.VERSION_CODES.M) internal fun checkPermissions(permissionMatcher: PermissionMatcher) { this.permissionMatcher = permissionMatcher rationalePermissions = permissionMatcher.deniedPermissions.filter(this::shouldShowRequestPermissionRationale) val rationaleBeanList = rationalePermissions.map { PermissionBean(it) } if (rationaleBeanList.isEmpty()) { if (!isShowingNativeDialog) requestPermissions(permissionMatcher.deniedPermissions.toTypedArray(), PERMISSION_REQUEST_CODE) isShowingNativeDialog = true } else { rationaleSingleListener?.invoke(rationaleBeanList[0], PermissionRationaleToken(this)) rationaleMultiListener?.invoke(rationaleBeanList, PermissionRationaleToken(this)) } } @RequiresApi(api = Build.VERSION_CODES.M) override fun continuePermissionRequest() { if (!isShowingNativeDialog) requestPermissions(permissionMatcher.deniedPermissions.toTypedArray(), PERMISSION_REQUEST_CODE) isShowingNativeDialog = true } override fun skipPermissionRequest() { isShowingNativeDialog = false permissionResultSingleListener?.invoke(PermissionBean(rationalePermissions[0])) val totalBeanGranted = permissionMatcher.grantedPermissions.map { PermissionBean(it, true) } val totalBeanDenied = permissionMatcher.deniedPermissions.map { PermissionBean(it) } val totalBeanPermanentlyDenied = permissionMatcher.permissions .filterNot { s -> permissionMatcher.deniedPermissions.contains(s) } .filterNot { s -> permissionMatcher.grantedPermissions.contains(s) } .map { PermissionBean(it, isGranted = false, isPermanentlyDenied = true) } permissionResultMultiListener?.invoke(totalBeanGranted.asSequence() .plus(totalBeanDenied) .plus(totalBeanPermanentlyDenied) .toList()) } internal fun setListeners(listenerResult: ((PermissionBean) -> Unit)?, listenerResultMulti: ((List<PermissionBean>) -> Unit)?, rationaleSingle: ((PermissionBean, PermissionToken) -> Unit)?, rationaleMulti: ((List<PermissionBean>, PermissionToken) -> Unit)?) { permissionResultSingleListener = listenerResult permissionResultMultiListener = listenerResultMulti rationaleSingleListener = rationaleSingle rationaleMultiListener = rationaleMulti } /* private fun isPermissionsDialogShowing(): Boolean { val am = activity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val cn = am.getRunningTasks(1).get(0).topActivity return "com.android.packageinstaller.permission.ui.GrantPermissionsActivity" == cn.className }*/ }
mayi/src/main/java/com/thanosfisherman/mayi/MayIFragment.kt
194555692
package reactivecircus.flowbinding.material import android.content.DialogInterface import androidx.annotation.CheckResult import androidx.fragment.app.DialogFragment import com.google.android.material.datepicker.MaterialDatePicker import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.conflate import reactivecircus.flowbinding.common.checkMainThread /** * Create a [Flow] of dismiss events on the [MaterialDatePicker] instance. * This emits whenever the underlying [DialogFragment] is dismissed, no matter how it is dismissed. * * Note: Created flow keeps a strong reference to the [MaterialDatePicker] instance * until the coroutine that launched the flow collector is cancelled. * * Example of usage: * * ``` * datePicker.dismisses() * .onEach { * // handle date picker dismissed * } * .launchIn(uiScope) * ``` */ @CheckResult @OptIn(ExperimentalCoroutinesApi::class) public fun <S> MaterialDatePicker<S>.dismisses(): Flow<Unit> = callbackFlow { checkMainThread() val listener = DialogInterface.OnDismissListener { trySend(Unit) } addOnDismissListener(listener) awaitClose { removeOnDismissListener(listener) } }.conflate()
flowbinding-material/src/main/java/reactivecircus/flowbinding/material/MaterialDatePickerDismissFlow.kt
1545081644
package io.particle.mesh.setup.flow.setupsteps import io.particle.firmwareprotos.ctrl.Config.DeviceMode import io.particle.firmwareprotos.ctrl.Config.Feature import io.particle.mesh.setup.flow.* import io.particle.mesh.setup.flow.context.SetupContexts import kotlinx.coroutines.delay class StepEnsureCorrectEthernetFeatureStatus : MeshSetupStep() { override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) { // only run this step if we've been asked to detect ethernet, // and we haven't already attempted to do so if (!ctxs.device.shouldDetectEthernet || ctxs.device.ethernetDetectionComplete) { return } val target = ctxs.targetDevice.transceiverLD.value!! val detectReply = target.sendGetFeature(Feature.ETHERNET_DETECTION).throwOnErrorOrAbsent() ctxs.device.ethernetDetectionComplete = true if (!detectReply.enabled) { target.sendSetFeature(Feature.ETHERNET_DETECTION, true).throwOnErrorOrAbsent() ctxs.device.isDetectEthernetSent = true target.sendStartupMode(DeviceMode.LISTENING_MODE).throwOnErrorOrAbsent() target.sendReset().throwOnErrorOrAbsent() target.disconnect() delay(4000) throw MeshSetupFlowException( message = "Resetting device to enable ethernet detection!", severity = ExceptionType.EXPECTED_FLOW ) } } }
mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepEnsureCorrectEthernetFeatureStatus.kt
1716093514
package ru.icarumbas.bagel.engine.controller import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input class WASDPlayerController : PlayerMoveController{ override fun isUpPressed(): Boolean { return Gdx.input.isKeyPressed(Input.Keys.SPACE) } override fun isDownPressed(): Boolean { return Gdx.input.isKeyPressed(Input.Keys.S) } override fun isLeftPressed(): Boolean { return Gdx.input.isKeyPressed(Input.Keys.A) } override fun isRightPressed(): Boolean { return Gdx.input.isKeyPressed(Input.Keys.D) } }
core/src/ru/icarumbas/bagel/engine/controller/WASDPlayerController.kt
1075162256
/* * Copyright 2019 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.runningbuilds.view import android.app.Activity import android.view.View import androidx.annotation.StringRes import com.github.vase4kin.teamcityapp.R import com.github.vase4kin.teamcityapp.base.list.view.SimpleSectionedRecyclerViewAdapter import com.github.vase4kin.teamcityapp.buildlist.data.BuildListDataModel import com.github.vase4kin.teamcityapp.buildlist.data.OnBuildListPresenterListener import com.github.vase4kin.teamcityapp.buildlist.view.BuildListActivity import com.github.vase4kin.teamcityapp.buildlist.view.BuildListAdapter import com.github.vase4kin.teamcityapp.buildlist.view.BuildListViewImpl import com.github.vase4kin.teamcityapp.filter_bottom_sheet_dialog.filter.Filter import com.github.vase4kin.teamcityapp.filter_bottom_sheet_dialog.filter.FilterProvider import java.util.ArrayList /** * impl of [RunningBuildListView] */ open class RunningBuildsListViewImpl( view: View, activity: Activity, @StringRes emptyMessage: Int, adapter: SimpleSectionedRecyclerViewAdapter<BuildListAdapter>, protected val filterProvider: FilterProvider ) : BuildListViewImpl(view, activity, emptyMessage, adapter), RunningBuildListView { /** * @return default tool bar title */ protected open val title: String get() = activity.getString(R.string.running_builds_drawer_item) /** * {@inheritDoc} */ override fun showData(dataModel: BuildListDataModel) { val baseAdapter = adapter.baseAdapter baseAdapter.dataModel = dataModel baseAdapter.setOnBuildListPresenterListener(listener ?: OnBuildListPresenterListener.EMPTY) val sections = ArrayList<SimpleSectionedRecyclerViewAdapter.Section>() if (dataModel.itemCount != 0) { for (i in 0 until dataModel.itemCount) { val buildTypeTitle = if (dataModel.hasBuildTypeInfo(i)) dataModel.getBuildTypeFullName(i) else dataModel.getBuildTypeId(i) if (sections.size != 0) { val prevSection = sections[sections.size - 1] if (prevSection.title != buildTypeTitle) { sections.add(SimpleSectionedRecyclerViewAdapter.Section(i, buildTypeTitle)) } } else { sections.add(SimpleSectionedRecyclerViewAdapter.Section(i, buildTypeTitle)) } } adapter.setListener { position -> val buildTypeName = dataModel.getBuildTypeName(position) val buildTypeId = dataModel.getBuildTypeId(position) BuildListActivity.start(buildTypeName, buildTypeId, null, activity) } } val userStates = arrayOfNulls<SimpleSectionedRecyclerViewAdapter.Section>(sections.size) adapter.setSections(sections.toArray(userStates)) recyclerView.adapter = adapter recyclerView.adapter?.notifyDataSetChanged() } /** * {@inheritDoc} */ override fun showRunBuildFloatActionButton() { // Do not show running build float action button here } /** * {@inheritDoc} */ override fun hideRunBuildFloatActionButton() { // Do not show running build float action button here } /** * {@inheritDoc} */ override val emptyMessage: Int get() = if (filterProvider.runningBuildsFilter === Filter.RUNNING_FAVORITES) { R.string.empty_list_message_favorite_running_builds } else { R.string.empty_list_message_running_builds } /** * {@inheritDoc} */ override fun emptyTitleId(): Int { return R.id.running_empty_title_view } /** * {@inheritDoc} */ override fun recyclerViewId(): Int { return R.id.running_builds_recycler_view } }
app/src/main/java/com/github/vase4kin/teamcityapp/runningbuilds/view/RunningBuildsListViewImpl.kt
3411837564
package br.com.bloder.blormlib.validation import android.view.View /** * Created by bloder on 03/09/16. */ abstract class Validation { var field: View? = null var errorMessage: String? = null abstract fun validate() : Validate }
blormlib/src/main/java/br/com/bloder/blormlib/validation/Validation.kt
102090529
package com.yy.codex.uikit /** * Created by adi on 17/1/13. */ class CGTransformScale(var sx: Double, var sy: Double) : CGTransform(true)
library/src/main/java/com/yy/codex/uikit/CGTransformScale.kt
3234766212
package com.exsilicium.scripture.shared.model import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import java.text.ParseException internal class BookDeserializationTest { @Test fun `Parse invalid book name`() { assertThrows(ParseException::class.java, { Book.parse("Johnny") }).let { assertEquals("Could not parse book name", it.message) } } @Test fun `Parse book with period`() { assertEquals(Book.EXODUS, Book.parse("Ex.")) } @Test fun `Parse Genesis`() { assertEquals(Book.GENESIS, Book.parse("Genesis")) assertEquals(Book.GENESIS, Book.parse("Gen")) assertEquals(Book.GENESIS, Book.parse("Ge")) assertEquals(Book.GENESIS, Book.parse("Gn")) } @Test fun `Parse uppercase book`() { assertEquals(Book.REVELATION, Book.parse("THE REVELATION")) } @Test fun `Parse book with whitespace`() { assertEquals(Book.MATTHEW, Book.parse(" Matt ")) } @Test fun `Verify no duplicate abbreviations`() { Book.values().flatMap { it.abbreviations }.let { assertEquals(it, it.distinct()) } } }
src/test/kotlin/com/exsilicium/scripture/shared/model/BookDeserializationTest.kt
2703574882
/********************************************************************************* * Copyright 2017-present trivago GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **********************************************************************************/ package com.trivago.reportoire.core.sources /** * Base interface for every Source you build. */ interface Source<out TModel, in TInput> { // Result /** * The result type that wil be delivered by any source. */ sealed class Result<out TModel> { /** * Success cases which may contain a model. */ class Success<out TModel>(val model: TModel?) : Result<TModel>() /** * Error cases which may contain a throwable. */ class Error<out TModel>(val throwable: Throwable?) : Result<TModel>() } // Interface API /** * Tells the source that its on-going task should be cancelled. */ fun cancel() /** * Tells the source that everything that has been cached so far should be reset. */ fun reset() /** * Returns true if the source is currently getting the result. Otherwise false. */ fun isGettingResult(): Boolean }
core/src/main/kotlin/com/trivago/reportoire/core/sources/Source.kt
2423664886