content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("PyIfStatementNavigator") package com.jetbrains.python.psi.impl import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.jetbrains.python.psi.PyIfStatement fun getIfStatementByIfKeyword(ifKeyword: PsiElement?): PyIfStatement? { val statement = PsiTreeUtil.getParentOfType(ifKeyword, PyIfStatement::class.java) ?: return null return if (statement.ifPart.firstChild === ifKeyword) statement else null }
python/src/com/jetbrains/python/psi/impl/PyIfStatementNavigator.kt
788002084
package fr.jeantuffier.reminder.free.home.injection import android.content.Context import dagger.Module import dagger.Provides import fr.jeantuffier.reminder.free.common.dao.TaskDao import fr.jeantuffier.reminder.free.home.presentation.HomeContract import fr.jeantuffier.reminder.free.home.presentation.HomePresenter @Module class HomePresenterModule { @Provides fun provideHomePresenter(context: Context, view: HomeContract.View, taskDao: TaskDao): HomeContract.Presenter { return HomePresenter(context, view, taskDao) } }
app/src/main/java/fr/jeantuffier/reminder/free/home/injection/HomePresenterModule.kt
186509407
@file:JvmName("Offsets") package org.abendigo.csgo.offsets import org.abendigo.csgo.Client.clientDLL import org.abendigo.csgo.csgoModule import org.abendigo.csgo.engineDLL val worldDecal by scanOffset(clientDLL, 0, 0, 0, "DT_TEWorldDecal") val firstClass by scanOffset(clientDLL, 0x2B, 0, READ, worldDecal) val gameDirectoryPointer by scanOffset(csgoModule, 1, 0, READ or SUBTRACT, 0xB9, 0, 0, 0, 0, 0x8D, 0x51) // client.dll offsets const val m_bDormant = 0xE9 const val m_dwIndex = 0x64 const val m_dwModel = 0x6C val m_dwRadarBase by scanOffset(clientDLL, 1, 0, READ or SUBTRACT, 161, 0, 0, 0, 0, 139, 12, 176, 139, 1, 255, 80, 0, 70, 59, 53, 0, 0, 0, 0, 124, 234, 139, 13, 0, 0, 0, 0) val m_dwWeaponTable by scanOffset(clientDLL, 1, 0, READ or SUBTRACT, 161, 0, 0, 0, 0, 15, 183, 201, 3, 201, 139, 68, 0, 12, 195) val m_dwWeaponTableIndex by scanOffset(clientDLL, 3, 0, READ, 102, 139, 142, 0, 0, 0, 0, 232, 0, 0, 0, 0, 5, 0, 0, 0, 0, 80) val m_dwInput by scanOffset(clientDLL, 1, 0, READ or SUBTRACT, 0xB9, 0, 0, 0, 0, 0xFF, 0x75, 0x08, 0xE8, 0, 0, 0, 0, 0x8B, 0x06) val m_dwGlowObject by scanOffset(clientDLL, 1, 4, READ or SUBTRACT, 0xA1, 0, 0, 0, 0, 0xA8, 0x01, 0x75, 0x4E, 0x0F, 0x57, 0xC0) val m_dwForceJump by scanOffset(clientDLL, 2, 0, READ or SUBTRACT, 137, 21, 0, 0, 0, 0, 139, 21, 0, 0, 0, 0, 246, 194, 3, 116, 3, 131, 206, 8) val m_dwForceAttack by scanOffset(clientDLL, 2, 0, READ or SUBTRACT, 137, 21, 0, 0, 0, 0, 139, 21, 0, 0, 0, 0, 246, 194, 3, 116, 3, 131, 206, 4) val m_dwViewMatrix by scanOffset(clientDLL, 828, 176, READ or SUBTRACT, 129, 198, 0, 0, 0, 0, 136, 69, 154, 15, 182, 192) val m_dwEntityList by scanOffset(clientDLL, 1, 0, READ or SUBTRACT, 187, 0, 0, 0, 0, 131, 255, 1, 15, 140, 0, 0, 0, 0, 59, 248) val m_dwLocalPlayer by scanOffset(clientDLL, 1, 16, READ or SUBTRACT, 163, 0, 0, 0, 0, 199, 5, 0, 0, 0, 0, 0, 0, 0, 0, 232, 0, 0, 0, 0, 89, 195, 106, 0) // engine.dll offsets val m_dwGlobalVars by scanOffset(engineDLL, 18, 0, READ or SUBTRACT, 0x8B, 0x0D, 0x0, 0x0, 0x0, 0x0, 0x83, 0xC4, 0x04, 0x8B, 0x01, 0x68, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x35) val m_dwClientState by scanOffset(engineDLL, 1, 0, READ or SUBTRACT, 161, 0, 0, 0, 0, 243, 15, 17, 128, 0, 0, 0, 0, 217, 70, 4, 217, 5, 0, 0, 0, 0) val m_dwInGame by scanOffset(engineDLL, 2, 0, READ, 131, 185, 0, 0, 0, 0, 6, 15, 148, 192, 195) val m_dwMaxPlayer by scanOffset(engineDLL, 7, 0, READ, 161, 0, 0, 0, 0, 139, 128, 0, 0, 0, 0, 195, 204, 204, 204, 204, 85, 139, 236, 139, 69, 8) val m_dwMapDirectory by scanOffset(engineDLL, 1, 0, READ, 5, 0, 0, 0, 0, 195, 204, 204, 204, 204, 204, 204, 204, 128, 61) val m_dwMapname by scanOffset(engineDLL, 1, 0, READ, 5, 0, 0, 0, 0, 195, 204, 204, 204, 204, 204, 204, 204, 161, 0, 0, 0, 0) val m_dwPlayerInfo by scanOffset(engineDLL, 2, 0, READ, 139, 136, 0, 0, 0, 0, 139, 1, 139, 64, 0, 255, 208, 139, 248) val m_dwViewAngles by scanOffset(engineDLL, 4, 0, READ, 0xF3, 0x0F, 0x11, 0x80, 0, 0, 0, 0, 0xD9, 0x46, 0x04, 0xD9, 0x05, 0, 0, 0, 0) val m_dwEnginePosition by scanOffset(engineDLL, 4, 0, READ or SUBTRACT, 243, 15, 17, 21, 0, 0, 0, 0, 243, 15, 17, 13, 0, 0, 0, 0, 243, 15, 17, 5, 0, 0, 0, 0, 243, 15, 17, 61, 0, 0, 0, 0) val m_bSendPacket by scanOffset(engineDLL, 0, 0, SUBTRACT, 0x01, 0x8B, 0x01, 0x8B, 0x40, 0x10) // thanks WasserEsser! val m_dwForceFullUpdate by scanOffset(engineDLL, 0x3, 0, READ or SUBTRACT, 0xB0, 0xFF, 0xB7, 0x00, 0x00, 0x00, 0x00, 0xE8) // DT_BaseEntity val m_bSpotted by beNetVar() val m_vecOrigin by beNetVar() val m_iTeamNum by beNetVar() // DT_BasePlayer val m_fFlags by bpNetVar() val m_iHealth by bpNetVar() val m_vecViewOffset by bpNetVar(index = 0) val m_vecVelocity by bpNetVar(index = 0) val m_vecPunch by bpNetVar("m_aimPunchAngle") val nActiveWeapon by bpNetVar() val nTickBase by bpNetVar() val m_lifeState by bpNetVar() val m_hActiveWeapon by bpNetVar() val m_nTickBase by bpNetVar() val m_nButtons by bpNetVar() val m_hMyWeapons by bpNetVar() // DT_CSPlayer val m_iCrossHairID by cspNetVar("m_bHasDefuser", 0x5C) val m_bIsScoped by cspNetVar() val m_iShotsFired by cspNetVar() val m_flFlashMaxAlpha by cspNetVar() // DT_BaseAnimating val m_dwBoneMatrix by netVar("DT_BaseAnimating", "m_nForceBone", 0x1C) // DT_BaseCombatWeapon val m_flNextPrimaryAttack by bcwNetVar() val m_iClip1 by bcwNetVar() val m_iClip2 by bcwNetVar() // DT_WeaponCSBase val m_iWeaponID by netVar("DT_WeaponCSBase", "m_fAccuracyPenalty", 0x30) // thanks n1BogOLlyQ val m_iItemDefinitionIndex by wepNetVar() val m_iAccountID by wepNetVar() val m_OriginalOwnerXuidLow by wepNetVar() val m_OriginalOwnerXuidHigh by wepNetVar() val m_iItemIDLow by wepNetVar() val m_iItemIDHigh by wepNetVar() val m_nFallbackPaintKit by wepNetVar() val m_nFallbackSeed by wepNetVar() val m_flFallbackWear by wepNetVar() val m_nFallbackStatTrak by wepNetVar() val m_iEntityQuality by wepNetVar() val m_szCustomName by wepNetVar()
Client Files/IntrepidClient/src/main/kotlin/org/abendigo/csgo/offsets/Offsets.kt
956408891
/* * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.docs.features.externalconfig.typesafeconfigurationproperties.constructorbinding.nonnull import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.context.properties.bind.DefaultValue import java.net.InetAddress @ConfigurationProperties("my.service") // tag::code[] class MyProperties(val enabled: Boolean, val remoteAddress: InetAddress, @DefaultValue val security: Security) { class Security(val username: String?, val password: String?, @param:DefaultValue("USER") val roles: List<String>) } // end::code[]
spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/constructorbinding/nonnull/MyProperties.kt
90304567
package com.virtlink.editorservices.resources import com.virtlink.editorservices.Offset import com.virtlink.editorservices.Position import java.io.LineNumberReader /** * Represents the content of a document. * * This object is immutable. */ interface IContent { /** * Gets the size of the document, in characters. */ val length: Long /** * The last-modification stamp. */ val lastModificationStamp: Long /** * Gets the number of lines in the document. * * This is greater than or equal to 1. If the * document ends with a newline, the following * (empty) line is treated as a line as well. */ val lineCount: Int /** * Gets the text in the document. */ val text: String /** * Returns a new document content object with the specified changes applied. * * @param changes The changes to apply, in terms of this content. * @param newStamp The new modification stamp. * @return The resulting content. */ fun withChanges(changes: List<TextChange>, newStamp: Long): IContent }
aesi/src/main/kotlin/com/virtlink/editorservices/resources/IContent.kt
1704072731
package com.appunite.firebasetestlabplugin.model data class TestResults(val isSuccessful: Boolean, val message: String)
plugin/src/main/java/com/appunite/firebasetestlabplugin/model/TestResults.kt
3791872990
package com.apollographql.apollo3.gradle.api import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.Property /** * A [Registry] represents a connection to the [Apollo Registry](https://www.apollographql.com/docs/studio/schema/registry/) * * Use this to register a `download${ServiceName}ApolloSchemaFromRegistry` task */ interface Registry { /** * The Apollo key * * See https://www.apollographql.com/docs/studio/api-keys/ for how to get an API key */ val key: Property<String> /** * The graph you want to download the schema from */ val graph: Property<String> /** * The variant you want to download the schema from */ val graphVariant: Property<String> /** * The file where to download the schema. * * Uses the schema from the service by default */ val schemaFile: RegularFileProperty }
apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo3/gradle/api/Registry.kt
2290250207
/* * 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.gradle.service.resolve import com.intellij.patterns.ElementPattern import com.intellij.patterns.PsiJavaPatterns.psiElement import com.intellij.patterns.StandardPatterns.or import com.intellij.psi.PsiElement import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.util.ProcessingContext import groovy.lang.Closure import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.* import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.patterns.groovyClosure import org.jetbrains.plugins.groovy.lang.psi.patterns.psiMethod import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DelegatesToInfo /** * @author Vladislav.Soroka * @since 11/10/2016 */ class GradleJavaContributor : GradleMethodContextContributor { companion object { val sourceSetsClosure = groovyClosure().inMethod(psiMethod(GRADLE_API_JAVA_PLUGIN_CONVENTION, "sourceSets")) val sourceSetReference = object : ElementPattern<PsiElement> { override fun getCondition() = null override fun accepts(o: Any?) = false override fun accepts(o: Any?, context: ProcessingContext): Boolean { return o is GrExpression && o.type?.equalsToText(GRADLE_API_SOURCE_SET) ?: false } } val sourceDirectorySetClosure = psiElement().andOr( groovyClosure().inMethod(or(psiMethod(GRADLE_API_SOURCE_SET, "java"), psiMethod(GRADLE_API_SOURCE_SET, "resources")))) } override fun getDelegatesToInfo(closure: GrClosableBlock): DelegatesToInfo? { if (sourceSetsClosure.accepts(closure)) { return DelegatesToInfo(TypesUtil.createType(GRADLE_API_SOURCE_SET_CONTAINER, closure), Closure.DELEGATE_FIRST) } if (sourceDirectorySetClosure.accepts(closure)) { return DelegatesToInfo(TypesUtil.createType(GRADLE_API_SOURCE_DIRECTORY_SET, closure), Closure.DELEGATE_FIRST) } if (psiElement().withParent( psiElement().withFirstChild(sourceSetReference)).accepts(closure)) { return DelegatesToInfo(TypesUtil.createType(GRADLE_API_SOURCE_SET, closure), Closure.DELEGATE_FIRST) } return null } override fun process(methodCallInfo: List<String>, processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { val psiManager = GroovyPsiManager.getInstance(place.project) if (!GradleResolverUtil.processDeclarations(psiManager, processor, state, place, GRADLE_API_BASE_PLUGIN_CONVENTION, GRADLE_API_JAVA_PLUGIN_CONVENTION, GRADLE_API_APPLICATION_PLUGIN_CONVENTION, GRADLE_API_WAR_CONVENTION)) { return false } return true } }
plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleJavaContributor.kt
2748770912
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.dfa import com.intellij.codeInsight.PsiEquivalenceUtil import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.dataFlow.interpreter.RunnerResult import com.intellij.codeInspection.dataFlow.interpreter.StandardDataFlowInterpreter import com.intellij.codeInspection.dataFlow.jvm.JvmDfaMemoryStateImpl import com.intellij.codeInspection.dataFlow.lang.DfaAnchor import com.intellij.codeInspection.dataFlow.lang.DfaListener import com.intellij.codeInspection.dataFlow.lang.UnsatisfiedConditionProblem import com.intellij.codeInspection.dataFlow.lang.ir.DataFlowIRProvider import com.intellij.codeInspection.dataFlow.lang.ir.DfaInstructionState import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState import com.intellij.codeInspection.dataFlow.types.DfType import com.intellij.codeInspection.dataFlow.types.DfTypes import com.intellij.codeInspection.dataFlow.value.DfaValue import com.intellij.codeInspection.dataFlow.value.DfaValueFactory import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.siblings import com.intellij.util.ThreeState import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.inspections.dfa.KotlinAnchor.* import org.jetbrains.kotlin.idea.inspections.dfa.KotlinProblem.* import org.jetbrains.kotlin.idea.intentions.loopToCallChain.isConstant import org.jetbrains.kotlin.idea.intentions.negate import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.readWriteAccess import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.isNull import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.isNothing import org.jetbrains.kotlin.types.typeUtil.isNullableNothing class KotlinConstantConditionsInspection : AbstractKotlinInspection() { private enum class ConstantValue { TRUE, FALSE, NULL, ZERO, UNKNOWN } private class KotlinDfaListener : DfaListener { val constantConditions = hashMapOf<KotlinAnchor, ConstantValue>() val problems = hashMapOf<KotlinProblem, ThreeState>() override fun beforePush(args: Array<out DfaValue>, value: DfaValue, anchor: DfaAnchor, state: DfaMemoryState) { if (anchor is KotlinAnchor) { recordExpressionValue(anchor, state, value) } } override fun onCondition(problem: UnsatisfiedConditionProblem, value: DfaValue, failed: ThreeState, state: DfaMemoryState) { if (problem is KotlinProblem) { problems.merge(problem, failed, ThreeState::merge) } } private fun recordExpressionValue(anchor: KotlinAnchor, state: DfaMemoryState, value: DfaValue) { val oldVal = constantConditions[anchor] if (oldVal == ConstantValue.UNKNOWN) return var newVal = when (val dfType = state.getDfType(value)) { DfTypes.TRUE -> ConstantValue.TRUE DfTypes.FALSE -> ConstantValue.FALSE DfTypes.NULL -> ConstantValue.NULL else -> { val constVal: Number? = dfType.getConstantOfType(Number::class.java) if (constVal != null && (constVal == 0 || constVal == 0L)) ConstantValue.ZERO else ConstantValue.UNKNOWN } } if (oldVal != null && oldVal != newVal) { newVal = ConstantValue.UNKNOWN } constantConditions[anchor] = newVal } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { // Non-JVM is not supported now if (holder.file.module?.platform?.isJvm() != true) return PsiElementVisitor.EMPTY_VISITOR return object : KtVisitorVoid() { override fun visitProperty(property: KtProperty) { if (shouldAnalyzeProperty(property)) { val initializer = property.delegateExpressionOrInitializer ?: return analyze(initializer) } } override fun visitPropertyAccessor(accessor: KtPropertyAccessor) { if (shouldAnalyzeProperty(accessor.property)) { val bodyExpression = accessor.bodyExpression ?: accessor.bodyBlockExpression ?: return analyze(bodyExpression) } } override fun visitParameter(parameter: KtParameter) { analyze(parameter.defaultValue ?: return) } private fun shouldAnalyzeProperty(property: KtProperty) = property.isTopLevel || property.parent is KtClassBody override fun visitClassInitializer(initializer: KtClassInitializer) { analyze(initializer.body ?: return) } override fun visitNamedFunction(function: KtNamedFunction) { val body = function.bodyExpression ?: function.bodyBlockExpression ?: return analyze(body) } private fun analyze(body: KtExpression) { val factory = DfaValueFactory(holder.project) processDataflowAnalysis(factory, body, holder, listOf(JvmDfaMemoryStateImpl(factory))) } } } private fun processDataflowAnalysis( factory: DfaValueFactory, body: KtExpression, holder: ProblemsHolder, states: Collection<DfaMemoryState> ) { val flow = DataFlowIRProvider.forElement(body, factory) ?: return val listener = KotlinDfaListener() val interpreter = StandardDataFlowInterpreter(flow, listener) if (interpreter.interpret(states.map { s -> DfaInstructionState(flow.getInstruction(0), s) }) != RunnerResult.OK) return reportProblems(listener, holder) for ((closure, closureStates) in interpreter.closures.entrySet()) { if (closure is KtExpression) { processDataflowAnalysis(factory, closure, holder, closureStates) } } } private fun reportProblems( listener: KotlinDfaListener, holder: ProblemsHolder ) { listener.constantConditions.forEach { (anchor, cv) -> if (cv != ConstantValue.UNKNOWN) { when (anchor) { is KotlinExpressionAnchor -> { val expr = anchor.expression if (!shouldSuppress(cv, expr)) { val key = when (cv) { ConstantValue.TRUE -> if (shouldReportAsValue(expr)) "inspection.message.value.always.true" else if (logicalChain(expr)) "inspection.message.condition.always.true.when.reached" else "inspection.message.condition.always.true" ConstantValue.FALSE -> if (shouldReportAsValue(expr)) "inspection.message.value.always.false" else if (logicalChain(expr)) "inspection.message.condition.always.false.when.reached" else "inspection.message.condition.always.false" ConstantValue.NULL -> "inspection.message.value.always.null" ConstantValue.ZERO -> "inspection.message.value.always.zero" else -> throw IllegalStateException("Unexpected constant: $cv") } val highlightType = if (shouldReportAsValue(expr)) ProblemHighlightType.WEAK_WARNING else ProblemHighlightType.GENERIC_ERROR_OR_WARNING holder.registerProblem(expr, KotlinBundle.message(key, expr.text), highlightType) } } is KotlinWhenConditionAnchor -> { val condition = anchor.condition if (!shouldSuppressWhenCondition(cv, condition)) { val message = KotlinBundle.message("inspection.message.when.condition.always.false") if (cv == ConstantValue.FALSE) { holder.registerProblem(condition, message) } else if (cv == ConstantValue.TRUE) { condition.siblings(forward = true, withSelf = false) .filterIsInstance<KtWhenCondition>() .forEach { cond -> holder.registerProblem(cond, message) } val nextEntry = condition.parent as? KtWhenEntry ?: return@forEach nextEntry.siblings(forward = true, withSelf = false) .filterIsInstance<KtWhenEntry>() .filterNot { entry -> entry.isElse } .flatMap { entry -> entry.conditions.asSequence() } .forEach { cond -> holder.registerProblem(cond, message) } } } } is KotlinForVisitedAnchor -> { val loopRange = anchor.forExpression.loopRange!! if (cv == ConstantValue.FALSE && !shouldSuppressForCondition(loopRange)) { val message = KotlinBundle.message("inspection.message.for.never.visited") holder.registerProblem(loopRange, message) } } } } } listener.problems.forEach { (problem, state) -> if (state == ThreeState.YES) { when (problem) { is KotlinArrayIndexProblem -> holder.registerProblem(problem.index, KotlinBundle.message("inspection.message.index.out.of.bounds")) is KotlinNullCheckProblem -> { val expr = problem.expr if (expr.baseExpression?.isNull() != true) { holder.registerProblem(expr.operationReference, KotlinBundle.message("inspection.message.nonnull.cast.will.always.fail")) } } is KotlinCastProblem -> { val anchor = (problem.cast as? KtBinaryExpressionWithTypeRHS)?.operationReference ?: problem.cast if (!isCompilationWarning(anchor)) { holder.registerProblem(anchor, KotlinBundle.message("inspection.message.cast.will.always.fail")) } } } } } } private fun shouldSuppressForCondition(loopRange: KtExpression): Boolean { if (loopRange is KtBinaryExpression) { val left = loopRange.left val right = loopRange.right // Reported separately by EmptyRangeInspection return left != null && right != null && left.isConstant() && right.isConstant() } return false } private fun shouldReportAsValue(expr: KtExpression) = expr is KtSimpleNameExpression || expr is KtQualifiedExpression && expr.selectorExpression is KtSimpleNameExpression private fun logicalChain(expr: KtExpression): Boolean { var context = expr var parent = context.parent while (parent is KtParenthesizedExpression) { context = parent parent = context.parent } if (parent is KtBinaryExpression && parent.right == context) { val token = parent.operationToken return token == KtTokens.ANDAND || token == KtTokens.OROR } return false } private fun shouldSuppressWhenCondition( cv: ConstantValue, condition: KtWhenCondition ): Boolean { if (cv != ConstantValue.FALSE && cv != ConstantValue.TRUE) return true if (cv == ConstantValue.TRUE && isLastCondition(condition)) return true if (condition.textLength == 0) return true return isCompilationWarning(condition) } private fun isLastCondition(condition: KtWhenCondition): Boolean { val entry = condition.parent as? KtWhenEntry ?: return false val whenExpr = entry.parent as? KtWhenExpression ?: return false if (entry.conditions.last() == condition) { val entries = whenExpr.entries val lastEntry = entries.last() if (lastEntry == entry) return true val size = entries.size // Also, do not report the always reachable entry right before 'else', // usually it's necessary for the smart-cast, or for definite assignment, and the report is just noise if (lastEntry.isElse && size > 1 && entries[size - 2] == entry) return true } return false } companion object { private fun areEquivalent(e1: KtElement, e2: KtElement): Boolean { return PsiEquivalenceUtil.areEquivalent(e1, e2, {ref1, ref2 -> ref1.element.text.equals(ref2.element.text)}, null, null, false) } private tailrec fun isOppositeCondition(candidate: KtExpression?, template: KtBinaryExpression, expression: KtExpression): Boolean { if (candidate !is KtBinaryExpression || candidate.operationToken !== KtTokens.ANDAND) return false val left = candidate.left val right = candidate.right if (left == null || right == null) return false val templateLeft = template.left val templateRight = template.right if (templateLeft == null || templateRight == null) return false if (templateRight === expression) { return areEquivalent(left, templateLeft) && areEquivalent(right.negate(false), templateRight) } if (!areEquivalent(right, templateRight)) return false if (templateLeft === expression) { return areEquivalent(left.negate(false), templateLeft) } if (templateLeft !is KtBinaryExpression || templateLeft.operationToken !== KtTokens.ANDAND) return false return isOppositeCondition(left, templateLeft, expression) } private fun hasOppositeCondition(whenExpression: KtWhenExpression, topCondition: KtExpression, expression: KtExpression): Boolean { for (entry in whenExpression.entries) { for (condition in entry.conditions) { if (condition is KtWhenConditionWithExpression) { val candidate = condition.expression if (candidate === topCondition) return false if (topCondition is KtBinaryExpression && isOppositeCondition(candidate, topCondition, expression)) return true if (candidate != null && areEquivalent(expression.negate(false), candidate)) return true } } } return false } /** * Returns true if expression is part of when condition expression that looks like * ``` * when { * a && b -> ... * a && !b -> ... * } * ``` * In this case, !b could be reported as 'always true' but such warnings are annoying */ private fun isPairingConditionInWhen(expression: KtExpression): Boolean { val parent = expression.parent if (parent is KtBinaryExpression && parent.operationToken == KtTokens.ANDAND) { var topAnd: KtBinaryExpression = parent while (true) { val nextParent = topAnd.parent if (nextParent is KtBinaryExpression && nextParent.operationToken == KtTokens.ANDAND) { topAnd = nextParent } else break } val topAndParent = topAnd.parent if (topAndParent is KtWhenConditionWithExpression) { val whenExpression = (topAndParent.parent as? KtWhenEntry)?.parent as? KtWhenExpression if (whenExpression != null && hasOppositeCondition(whenExpression, topAnd, expression)) { return true } } } if (parent is KtWhenConditionWithExpression) { val whenExpression = (parent.parent as? KtWhenEntry)?.parent as? KtWhenExpression if (whenExpression != null && hasOppositeCondition(whenExpression, expression, expression)) { return true } } return false } private fun isCompilationWarning(anchor: KtElement): Boolean { val context = anchor.analyze(BodyResolveMode.FULL) if (context.diagnostics.forElement(anchor).any { it.factory == Errors.CAST_NEVER_SUCCEEDS || it.factory == Errors.SENSELESS_COMPARISON || it.factory == Errors.SENSELESS_NULL_IN_WHEN || it.factory == Errors.USELESS_IS_CHECK || it.factory == Errors.DUPLICATE_LABEL_IN_WHEN } ) { return true } val rootElement = anchor.containingFile val suppressionCache = KotlinCacheService.getInstance(anchor.project).getSuppressionCache() return suppressionCache.isSuppressed(anchor, rootElement, "CAST_NEVER_SUCCEEDS", Severity.WARNING) || suppressionCache.isSuppressed(anchor, rootElement, "SENSELESS_COMPARISON", Severity.WARNING) || suppressionCache.isSuppressed(anchor, rootElement, "SENSELESS_NULL_IN_WHEN", Severity.WARNING) || suppressionCache.isSuppressed(anchor, rootElement, "USELESS_IS_CHECK", Severity.WARNING) || suppressionCache.isSuppressed(anchor, rootElement, "DUPLICATE_LABEL_IN_WHEN", Severity.WARNING) } private fun isCallToMethod(call: KtCallExpression, packageName: String, methodName: String): Boolean { val descriptor = call.resolveToCall()?.resultingDescriptor ?: return false if (descriptor.name.asString() != methodName) return false val packageFragment = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false return packageFragment.fqName.asString() == packageName } // Do not report x.let { true } or x.let { false } as it's pretty evident private fun isLetConstant(expr: KtExpression): Boolean { val call = (expr as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: return false if (!isCallToMethod(call, "kotlin", "let")) return false val lambda = call.lambdaArguments.singleOrNull()?.getLambdaExpression() ?: return false return lambda.bodyExpression?.statements?.singleOrNull() is KtConstantExpression } // Do not report on also, as it always returns the qualifier. If necessary, qualifier itself will be reported private fun isAlsoChain(expr: KtExpression): Boolean { val call = (expr as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: return false return isCallToMethod(call, "kotlin", "also") } private fun isAssertion(parent: PsiElement?, value: Boolean): Boolean { return when (parent) { is KtBinaryExpression -> (parent.operationToken == KtTokens.ANDAND || parent.operationToken == KtTokens.OROR) && isAssertion(parent.parent, value) is KtParenthesizedExpression -> isAssertion(parent.parent, value) is KtPrefixExpression -> parent.operationToken == KtTokens.EXCL && isAssertion(parent.parent, !value) is KtValueArgument -> { if (!value) return false val valueArgList = parent.parent as? KtValueArgumentList ?: return false val call = valueArgList.parent as? KtCallExpression ?: return false val descriptor = call.resolveToCall()?.resultingDescriptor ?: return false val name = descriptor.name.asString() if (name != "assert" && name != "require" && name != "check") return false val pkg = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false return pkg.fqName.asString() == "kotlin" } else -> false } } private fun hasWritesTo(block: PsiElement?, variable: KtProperty): Boolean { return !PsiTreeUtil.processElements(block, KtSimpleNameExpression::class.java) { ref -> val write = ref.mainReference.isReferenceTo(variable) && ref.readWriteAccess(false).isWrite !write } } private fun isUpdateChain(expression: KtExpression): Boolean { // x = x or ..., etc. if (expression !is KtSimpleNameExpression) return false val binOp = expression.parent as? KtBinaryExpression ?: return false val op = binOp.operationReference.text if (op != "or" && op != "and" && op != "xor" && op != "||" && op != "&&") return false val assignment = binOp.parent as? KtBinaryExpression ?: return false if (assignment.operationToken != KtTokens.EQ) return false val left = assignment.left if (left !is KtSimpleNameExpression || !left.textMatches(expression.text)) return false val variable = expression.mainReference.resolve() as? KtProperty ?: return false val varParent = variable.parent as? KtBlockExpression ?: return false var context: PsiElement = assignment var block = context.parent while (block is KtContainerNode || block is KtBlockExpression && block.statements.first() == context || block is KtIfExpression && block.then?.parent == context && block.`else` == null && !hasWritesTo(block.condition, variable) ) { context = block block = context.parent } if (block !== varParent) return false var curExpression = variable.nextSibling while (curExpression != context) { if (hasWritesTo(curExpression, variable)) return false curExpression = curExpression.nextSibling } return true } fun shouldSuppress(value: DfType, expression: KtExpression): Boolean { val constant = when(value) { DfTypes.NULL -> ConstantValue.NULL DfTypes.TRUE -> ConstantValue.TRUE DfTypes.FALSE -> ConstantValue.FALSE DfTypes.intValue(0), DfTypes.longValue(0) -> ConstantValue.ZERO else -> ConstantValue.UNKNOWN } return shouldSuppress(constant, expression) } private fun shouldSuppress(value: ConstantValue, expression: KtExpression): Boolean { // TODO: return x && y.let {return...} var parent = expression.parent if (parent is KtDotQualifiedExpression && parent.selectorExpression == expression) { // Will be reported for parent qualified expression return true } while (parent is KtParenthesizedExpression) { parent = parent.parent } if (expression is KtConstantExpression || // If result of initialization is constant, then the initializer will be reported expression is KtProperty || // If result of assignment is constant, then the right-hand part will be reported expression is KtBinaryExpression && expression.operationToken == KtTokens.EQ || // Negation operand: negation itself will be reported (parent as? KtPrefixExpression)?.operationToken == KtTokens.EXCL ) { return true } if (expression is KtBinaryExpression && expression.operationToken == KtTokens.ELVIS) { // Left part of Elvis is Nothing?, so the right part is always executed // Could be caused by code like return x?.let { return ... } ?: true // While inner "return" is redundant, the "always true" warning is confusing // probably separate inspection could report extra "return" if (expression.left?.getKotlinType()?.isNullableNothing() == true) { return true } } if (isAlsoChain(expression) || isLetConstant(expression) || isUpdateChain(expression)) return true when (value) { ConstantValue.TRUE -> { if (isAndOrConditionWithNothingOperand(expression, KtTokens.OROR)) return true if (isSmartCastNecessary(expression, true)) return true if (isPairingConditionInWhen(expression)) return true if (isAssertion(parent, true)) return true } ConstantValue.FALSE -> { if (isAndOrConditionWithNothingOperand(expression, KtTokens.ANDAND)) return true if (isSmartCastNecessary(expression, false)) return true if (isAssertion(parent, false)) return true } ConstantValue.ZERO -> { if (expression.readWriteAccess(false).isWrite) { // like if (x == 0) x++, warning would be somewhat annoying return true } if (expression is KtDotQualifiedExpression && expression.selectorExpression?.textMatches("ordinal") == true) { var receiver: KtExpression? = expression.receiverExpression if (receiver is KtQualifiedExpression) { receiver = receiver.selectorExpression } if (receiver is KtSimpleNameExpression && receiver.resolveMainReferenceToDescriptors() .any { desc -> desc is ClassDescriptor && desc.kind == ClassKind.ENUM_ENTRY } ) { // ordinal() call on explicit enum constant return true } } val bindingContext = expression.analyze() if (ConstantExpressionEvaluator.getConstant(expression, bindingContext) != null) return true if (expression is KtSimpleNameExpression && (parent is KtValueArgument || parent is KtContainerNode && parent.parent is KtArrayAccessExpression) ) { // zero value is passed as argument to another method or used for array access. Often, such a warning is annoying return true } } ConstantValue.NULL -> { if (parent is KtProperty && parent.typeReference == null && expression is KtSimpleNameExpression) { // initialize other variable with null to copy type, like // var x1 : X = null // var x2 = x1 -- let's suppress this return true } if (expression is KtBinaryExpressionWithTypeRHS && expression.left.isNull()) { // like (null as? X) return true } if (parent is KtBinaryExpression) { val token = parent.operationToken if ((token === KtTokens.EQEQ || token === KtTokens.EXCLEQ || token === KtTokens.EQEQEQ || token === KtTokens.EXCLEQEQEQ) && (parent.left?.isNull() == true || parent.right?.isNull() == true) ) { // like if (x == null) when 'x' is known to be null: report 'always true' instead return true } } val kotlinType = expression.getKotlinType() if (kotlinType.toDfType() == DfTypes.NULL) { // According to type system, nothing but null could be stored in such an expression (likely "Void?" type) return true } } else -> {} } if (expression is KtSimpleNameExpression) { val target = expression.mainReference.resolve() if (target is KtProperty && !target.isVar && target.initializer is KtConstantExpression) { // suppress warnings uses of boolean constant like 'val b = true' return true } } if (isCompilationWarning(expression)) { return true } return expression.isUsedAsStatement(expression.analyze(BodyResolveMode.FULL)) } // x || return y private fun isAndOrConditionWithNothingOperand(expression: KtExpression, token: KtSingleValueToken): Boolean { if (expression !is KtBinaryExpression || expression.operationToken != token) return false val type = expression.right?.getKotlinType() return type != null && type.isNothing() } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KotlinConstantConditionsInspection.kt
1200675830
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.left import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.util.NlsActions import com.intellij.openapi.util.NlsActions.ActionText import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageSearchToolWindowModel import org.jetbrains.annotations.Nls import javax.swing.JLabel class ModuleContextComboBox(viewModel: PackageSearchToolWindowModel) : ContextComboBoxBase(viewModel) { override fun createNameLabel() = JLabel("") override fun createValueLabel() = object : JLabel() { override fun getIcon() = viewModel.selectedProjectModule.value?.moduleType?.icon ?: AllIcons.General.ProjectStructure override fun getText() = viewModel.selectedProjectModule.value?.name ?: PackageSearchBundle.message("packagesearch.ui.toolwindow.allModules") } override fun createActionGroup(): ActionGroup { return DefaultActionGroup( createSelectProjectAction(), DefaultActionGroup(createSelectModuleActions()) ) } private fun createSelectProjectAction() = createSelectAction(null, PackageSearchBundle.message("packagesearch.ui.toolwindow.allModules")) private fun createSelectModuleActions(): List<AnAction> = viewModel.projectModules.value .sortedBy { it.getFullName() } .map { createSelectAction(it, it.getFullName()) } private fun createSelectAction(projectModule: ProjectModule?, @ActionText title: String) = object : AnAction(title, title, projectModule?.moduleType?.icon ?: AllIcons.General.ProjectStructure) { override fun actionPerformed(e: AnActionEvent) { viewModel.selectedProjectModule.set(projectModule) updateLabel() } } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/left/ModuleContextComboBox.kt
3633204197
package ch.difty.scipamato.publ import org.amshove.kluent.shouldBe import org.junit.jupiter.api.Test /** * Dummy test to trigger jacoco to create the test.exec file for sonar. */ internal class DummyTest { @Test fun dummyTest() { true shouldBe true } }
public/public-persistence-api/src/test/kotlin/ch/difty/scipamato/publ/DummyTest.kt
4223385811
package no.skatteetaten.aurora.boober.utils import no.skatteetaten.aurora.boober.service.UrlValidationException import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows class UrlParserTest { // Test data private val httpUrl = "http://hostname" private val httpUrlWithPort = "http://hostname:6543" private val httpUrlWithPath = "http://hostname/path/secondPath" private val httpUrlWithSlash = "http://hostname/" private val httpUrlWithQuery = "http://hostname?param1=some_arg&param2=another_arg" private val httpUrlWithPortPathSlashAndQuery = "http://hostname:6543/path/?param=some_arg" private val httpsUrl = "https://hostname" private val jdbcPostgresUrl = "jdbc:postgresql://hostname/dbname" private val jdbcPostgresUrlWithoutHostname = "jdbc:postgresql:dbname" private val jdbcPostgresUrlWithPort = "jdbc:postgresql://hostname:6543/dbname" private val jdbcPostgresUrlWithQuery = "jdbc:postgresql://hostname/dbname?param1=some_arg&param2=another_arg" private val jdbcPostgresUrlWithPortAndQuery = "jdbc:postgresql://hostname:6543/dbname?param=some_arg" private val jdbcOracleUrl = "jdbc:oracle:thin:@hostname" private val jdbcOracleUrlWithPort = "jdbc:oracle:thin:@hostname:6543" private val jdbcOracleUrlWithService = "jdbc:oracle:thin:@hostname/service" private val jdbcOracleUrlWithMode = "jdbc:oracle:thin:@hostname:mode" private val jdbcOracleUrlWithQuery = "jdbc:oracle:thin:@hostname?param1=some_arg&param2=another_arg" private val jdbcOracleUrlWithPortAndService = "jdbc:oracle:thin:@hostname:6543/service" private val jdbcOracleUrlWithPortAndMode = "jdbc:oracle:thin:@hostname:6543:mode" private val jdbcOracleUrlWithPortServiceAndMode = "jdbc:oracle:thin:@hostname:6543/service:mode" private val jdbcOracleUrlWithPortServiceModeAndQuery = "jdbc:oracle:thin:@hostname:6543/service:mode?param=arg" private val jdbcOracleUrlWithDoubleSlash = "jdbc:oracle:thin:@//hostname" private val jdbcOracleUrlWithProtocol = "jdbc:oracle:thin:@protocol://hostname" private val jdbcOracleUrlWithProtocolPortServiceModeAndQuery = "jdbc:oracle:thin:@protocol://hostname:6543/service:mode?param=arg" private val httpUrls = listOf( httpUrl, httpUrlWithPort, httpUrlWithPath, httpUrlWithSlash, httpUrlWithQuery, httpUrlWithPortPathSlashAndQuery ) private val httpsUrls = listOf(httpsUrl) private val jdbcPosgresUrls = listOf( jdbcPostgresUrl, jdbcPostgresUrlWithoutHostname, jdbcPostgresUrlWithPort, jdbcPostgresUrlWithQuery, jdbcPostgresUrlWithPortAndQuery ) private val jdbcOracleUrls = listOf( jdbcOracleUrl, jdbcOracleUrlWithPort, jdbcOracleUrlWithService, jdbcOracleUrlWithMode, jdbcOracleUrlWithQuery, jdbcOracleUrlWithPortAndService, jdbcOracleUrlWithPortAndMode, jdbcOracleUrlWithPortServiceAndMode, jdbcOracleUrlWithPortServiceModeAndQuery, jdbcOracleUrlWithDoubleSlash, jdbcOracleUrlWithProtocol, jdbcOracleUrlWithProtocolPortServiceModeAndQuery ) private val validUrls = listOf( httpUrls, httpsUrls, jdbcPosgresUrls, jdbcOracleUrls ).flatten() private val misspelledHttpUrl = "http:/hostname" private val misspelledJdbcPostgresUrl = "jdbc:postgres/hostname/dbname" private val misspelledJdbcOracleUrl = "jdbc:oracle:thing:@hostname" @Test fun `Validation works as expected`() { validUrls.forEach { with(UrlParser(it)) { assertTrue { this.isValid() } this.assertIsValid() } } listOf( misspelledHttpUrl, misspelledJdbcPostgresUrl, misspelledJdbcOracleUrl ).forEach { with(UrlParser(it)) { assertFalse(this.isValid()) assertThrows<UrlValidationException> { this.assertIsValid() } } } } @Test fun `Hostname can be extracted from url`() { validUrls.forEach { assertEquals( if (it.contains("hostname")) "hostname" else "localhost", UrlParser(it).hostName ) } } @Test fun `Port can be extracted from url`() { httpUrls.forEach { assertEquals( if (it.contains("6543")) 6543 else 80, UrlParser(it).port ) } httpsUrls.forEach { assertEquals( if (it.contains("6543")) 6543 else 443, UrlParser(it).port ) } jdbcPosgresUrls.forEach { assertEquals( if (it.contains("6543")) 6543 else 5432, UrlParser(it).port ) } jdbcOracleUrls.forEach { assertEquals( if (it.contains("6543")) 6543 else 1521, UrlParser(it).port ) } } @Test fun `Suffix can be extracted from url`() { mapOf( httpUrl to "", httpUrlWithPort to "", httpUrlWithPath to "/path/secondPath", httpUrlWithSlash to "/", httpUrlWithQuery to "?param1=some_arg&param2=another_arg", httpUrlWithPortPathSlashAndQuery to "/path/?param=some_arg", httpsUrl to "", jdbcPostgresUrl to "/dbname", jdbcPostgresUrlWithoutHostname to "/dbname", jdbcPostgresUrlWithPort to "/dbname", jdbcPostgresUrlWithQuery to "/dbname?param1=some_arg&param2=another_arg", jdbcPostgresUrlWithPortAndQuery to "/dbname?param=some_arg", jdbcOracleUrl to "", jdbcOracleUrlWithPort to "", jdbcOracleUrlWithService to "/service", jdbcOracleUrlWithMode to ":mode", jdbcOracleUrlWithQuery to "?param1=some_arg&param2=another_arg", jdbcOracleUrlWithPortAndService to "/service", jdbcOracleUrlWithPortAndMode to ":mode", jdbcOracleUrlWithPortServiceAndMode to "/service:mode", jdbcOracleUrlWithPortServiceModeAndQuery to "/service:mode?param=arg", jdbcOracleUrlWithDoubleSlash to "", jdbcOracleUrlWithProtocol to "", jdbcOracleUrlWithProtocolPortServiceModeAndQuery to "/service:mode?param=arg" ).forEach { (input, expectedOutput) -> assertEquals(expectedOutput, UrlParser(input).suffix) } } @Test fun `Generates string with default values`() { mapOf( httpUrl to "http://hostname:80", httpUrlWithPort to "http://hostname:6543", httpUrlWithPath to "http://hostname:80/path/secondPath", httpUrlWithSlash to "http://hostname:80/", httpUrlWithQuery to "http://hostname:80?param1=some_arg&param2=another_arg", httpUrlWithPortPathSlashAndQuery to "http://hostname:6543/path/?param=some_arg", httpsUrl to "https://hostname:443", jdbcPostgresUrl to "jdbc:postgresql://hostname:5432/dbname", jdbcPostgresUrlWithoutHostname to "jdbc:postgresql://localhost:5432/dbname", jdbcPostgresUrlWithPort to "jdbc:postgresql://hostname:6543/dbname", jdbcPostgresUrlWithQuery to "jdbc:postgresql://hostname:5432/dbname?param1=some_arg&param2=another_arg", jdbcPostgresUrlWithPortAndQuery to "jdbc:postgresql://hostname:6543/dbname?param=some_arg", jdbcOracleUrl to "jdbc:oracle:thin:@hostname:1521", jdbcOracleUrlWithPort to "jdbc:oracle:thin:@hostname:6543", jdbcOracleUrlWithService to "jdbc:oracle:thin:@hostname:1521/service", jdbcOracleUrlWithMode to "jdbc:oracle:thin:@hostname:1521:mode", jdbcOracleUrlWithQuery to "jdbc:oracle:thin:@hostname:1521?param1=some_arg&param2=another_arg", jdbcOracleUrlWithPortAndService to "jdbc:oracle:thin:@hostname:6543/service", jdbcOracleUrlWithPortAndMode to "jdbc:oracle:thin:@hostname:6543:mode", jdbcOracleUrlWithPortServiceAndMode to "jdbc:oracle:thin:@hostname:6543/service:mode", jdbcOracleUrlWithPortServiceModeAndQuery to "jdbc:oracle:thin:@hostname:6543/service:mode?param=arg", jdbcOracleUrlWithDoubleSlash to "jdbc:oracle:thin:@//hostname:1521", jdbcOracleUrlWithProtocol to "jdbc:oracle:thin:@protocol://hostname:1521", jdbcOracleUrlWithProtocolPortServiceModeAndQuery to "jdbc:oracle:thin:@protocol://hostname:6543/service:mode?param=arg" ).forEach { (input, expectedOutput) -> assertEquals(expectedOutput, UrlParser(input).makeString()) } } @Test fun `Generates url with modified host name`() { validUrls.forEach { assertEquals( "newName.domain", UrlParser(it).withModifiedHostName("newName.domain").hostName ) } mapOf( httpUrl to "http://newName.domain:80", httpUrlWithPort to "http://newName.domain:6543", httpUrlWithPath to "http://newName.domain:80/path/secondPath", httpUrlWithSlash to "http://newName.domain:80/", httpUrlWithQuery to "http://newName.domain:80?param1=some_arg&param2=another_arg", httpUrlWithPortPathSlashAndQuery to "http://newName.domain:6543/path/?param=some_arg", httpsUrl to "https://newName.domain:443", jdbcPostgresUrl to "jdbc:postgresql://newName.domain:5432/dbname", jdbcPostgresUrlWithoutHostname to "jdbc:postgresql://newName.domain:5432/dbname", jdbcPostgresUrlWithPort to "jdbc:postgresql://newName.domain:6543/dbname", jdbcPostgresUrlWithQuery to "jdbc:postgresql://newName.domain:5432/dbname?param1=some_arg&param2=another_arg", jdbcPostgresUrlWithPortAndQuery to "jdbc:postgresql://newName.domain:6543/dbname?param=some_arg", jdbcOracleUrl to "jdbc:oracle:thin:@newName.domain:1521", jdbcOracleUrlWithPort to "jdbc:oracle:thin:@newName.domain:6543", jdbcOracleUrlWithService to "jdbc:oracle:thin:@newName.domain:1521/service", jdbcOracleUrlWithMode to "jdbc:oracle:thin:@newName.domain:1521:mode", jdbcOracleUrlWithQuery to "jdbc:oracle:thin:@newName.domain:1521?param1=some_arg&param2=another_arg", jdbcOracleUrlWithPortAndService to "jdbc:oracle:thin:@newName.domain:6543/service", jdbcOracleUrlWithPortAndMode to "jdbc:oracle:thin:@newName.domain:6543:mode", jdbcOracleUrlWithPortServiceAndMode to "jdbc:oracle:thin:@newName.domain:6543/service:mode", jdbcOracleUrlWithPortServiceModeAndQuery to "jdbc:oracle:thin:@newName.domain:6543/service:mode?param=arg", jdbcOracleUrlWithDoubleSlash to "jdbc:oracle:thin:@//newName.domain:1521", jdbcOracleUrlWithProtocol to "jdbc:oracle:thin:@protocol://newName.domain:1521", jdbcOracleUrlWithProtocolPortServiceModeAndQuery to "jdbc:oracle:thin:@protocol://newName.domain:6543/service:mode?param=arg" ).forEach { (input, expectedOutput) -> assertEquals( expectedOutput, UrlParser(input).withModifiedHostName("newName.domain").makeString() ) } } @Test fun `Generates url with modified port`() { validUrls.forEach { assertEquals( 18000, UrlParser(it).withModifiedPort(18000).port ) } mapOf( httpUrl to "http://hostname:18000", httpUrlWithPort to "http://hostname:18000", httpUrlWithPath to "http://hostname:18000/path/secondPath", httpUrlWithSlash to "http://hostname:18000/", httpUrlWithQuery to "http://hostname:18000?param1=some_arg&param2=another_arg", httpUrlWithPortPathSlashAndQuery to "http://hostname:18000/path/?param=some_arg", httpsUrl to "https://hostname:18000", jdbcPostgresUrl to "jdbc:postgresql://hostname:18000/dbname", jdbcPostgresUrlWithoutHostname to "jdbc:postgresql://localhost:18000/dbname", jdbcPostgresUrlWithPort to "jdbc:postgresql://hostname:18000/dbname", jdbcPostgresUrlWithQuery to "jdbc:postgresql://hostname:18000/dbname?param1=some_arg&param2=another_arg", jdbcPostgresUrlWithPortAndQuery to "jdbc:postgresql://hostname:18000/dbname?param=some_arg", jdbcOracleUrl to "jdbc:oracle:thin:@hostname:18000", jdbcOracleUrlWithPort to "jdbc:oracle:thin:@hostname:18000", jdbcOracleUrlWithService to "jdbc:oracle:thin:@hostname:18000/service", jdbcOracleUrlWithMode to "jdbc:oracle:thin:@hostname:18000:mode", jdbcOracleUrlWithQuery to "jdbc:oracle:thin:@hostname:18000?param1=some_arg&param2=another_arg", jdbcOracleUrlWithPortAndService to "jdbc:oracle:thin:@hostname:18000/service", jdbcOracleUrlWithPortAndMode to "jdbc:oracle:thin:@hostname:18000:mode", jdbcOracleUrlWithPortServiceAndMode to "jdbc:oracle:thin:@hostname:18000/service:mode", jdbcOracleUrlWithPortServiceModeAndQuery to "jdbc:oracle:thin:@hostname:18000/service:mode?param=arg", jdbcOracleUrlWithDoubleSlash to "jdbc:oracle:thin:@//hostname:18000", jdbcOracleUrlWithProtocol to "jdbc:oracle:thin:@protocol://hostname:18000", jdbcOracleUrlWithProtocolPortServiceModeAndQuery to "jdbc:oracle:thin:@protocol://hostname:18000/service:mode?param=arg" ).forEach { (input, expectedOutput) -> assertEquals( expectedOutput, UrlParser(input).withModifiedPort(18000).makeString() ) } } }
src/test/kotlin/no/skatteetaten/aurora/boober/utils/UrlParserTest.kt
3345093993
package it.ncorti.emgvisualizer.ui.model data class Device(val name: String?, val address: String)
app/src/main/java/it/ncorti/emgvisualizer/ui/model/Device.kt
2029014226
/* * Copyright 2018 75py * * 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.nagopy.android.textcounter.counter interface TextCounter { fun countChars(inputText: String): Int fun countWords(inputText: String): Int fun countSentences(inputText: String): Int fun countParagraphs(inputText: String): Int fun countWhitespaces(inputText: String): Int fun String.remove(regex: Regex): String = this.replace(regex, "") fun String.count(regex: Regex): Int = this.length - remove(regex).length }
app/src/main/java/com/nagopy/android/textcounter/counter/TextCounter.kt
1686140904
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package benchmarks.akka import akka.actor.* import com.typesafe.config.* import org.openjdk.jmh.annotations.* import scala.concurrent.* import scala.concurrent.duration.* import java.util.concurrent.* const val ROUNDS = 10_000 const val STATE_SIZE = 1024 val CORES_COUNT = Runtime.getRuntime().availableProcessors() /* * Benchmarks following computation pattern: * N actors, each has independent state (coefficients), receives numbers and answers with product and * N requestors, which randomly send requests. N roundtrips over every requestor are measured * * Benchmark (dispatcher) Mode Cnt Score Error Units * StatefulActorAkkaBenchmark.multipleComputationsMultipleRequestors default-dispatcher avgt 14 72.568 ± 10.620 ms/op * StatefulActorAkkaBenchmark.multipleComputationsMultipleRequestors single-thread-dispatcher avgt 14 70.198 ± 3.594 ms/op * * StatefulActorAkkaBenchmark.multipleComputationsSingleRequestor default-dispatcher avgt 14 36.737 ± 3.589 ms/op * StatefulActorAkkaBenchmark.multipleComputationsSingleRequestor single-thread-dispatcher avgt 14 9.050 ± 0.385 ms/op * * StatefulActorAkkaBenchmark.singleComputationMultipleRequestors default-dispatcher avgt 14 446.563 ± 85.577 ms/op * StatefulActorAkkaBenchmark.singleComputationMultipleRequestors single-thread-dispatcher avgt 14 70.250 ± 3.104 ms/op * * StatefulActorAkkaBenchmark.singleComputationSingleRequestor default-dispatcher avgt 14 39.964 ± 2.343 ms/op * StatefulActorAkkaBenchmark.singleComputationSingleRequestor single-thread-dispatcher avgt 14 10.214 ± 2.152 ms/op */ //@Warmup(iterations = 7, time = 1, timeUnit = TimeUnit.SECONDS) //@Measurement(iterations = 7, time = 1, timeUnit = TimeUnit.SECONDS) //@Fork(value = 2) //@BenchmarkMode(Mode.AverageTime) //@OutputTimeUnit(TimeUnit.MILLISECONDS) //@State(Scope.Benchmark) open class StatefulActorAkkaBenchmark { lateinit var system: ActorSystem @Param("default-dispatcher", "single-thread-dispatcher") var dispatcher: String = "akka.actor.default-dispatcher" @Setup fun setup() { // TODO extract it to common AkkaBase if new benchmark will appear system = ActorSystem.create("StatefulActors", ConfigFactory.parseString(""" akka.actor.single-thread-dispatcher { type = Dispatcher executor = "thread-pool-executor" thread-pool-executor { fixed-pool-size = 1 } throughput = 1 } """.trimIndent() )) } @TearDown fun tearDown() { Await.ready(system.terminate(), Duration.Inf()) } // @Benchmark fun singleComputationSingleRequestor() { run(1, 1) } // @Benchmark fun singleComputationMultipleRequestors() { run(1, CORES_COUNT) } // @Benchmark fun multipleComputationsSingleRequestor() { run(CORES_COUNT, 1) } // @Benchmark fun multipleComputationsMultipleRequestors() { run(CORES_COUNT, CORES_COUNT) } private fun run(computationActors: Int, requestorActors: Int) { val stopLatch = CountDownLatch(requestorActors) /* * For complex setups Akka creates actors slowly, * so first start message may become dead letter (and freeze benchmark) */ val initLatch = CountDownLatch(computationActors + requestorActors) val computations = createComputationActors(initLatch, computationActors) val requestors = createRequestorActors(requestorActors, computations, initLatch, stopLatch) initLatch.await() for (requestor in requestors) { requestor.tell(1L, ActorRef.noSender()) } stopLatch.await() computations.forEach { it.tell(Stop(), ActorRef.noSender()) } } private fun createRequestorActors(requestorActors: Int, computations: List<ActorRef>, initLatch: CountDownLatch, stopLatch: CountDownLatch): List<ActorRef> { return (0 until requestorActors).map { system.actorOf(Props.create(RequestorActor::class.java, computations, initLatch, stopLatch) .withDispatcher("akka.actor.$dispatcher")) } } private fun createComputationActors(initLatch: CountDownLatch, count: Int): List<ActorRef> { return (0 until count).map { system.actorOf(Props.create( ComputationActor::class.java, LongArray(STATE_SIZE) { ThreadLocalRandom.current().nextLong(0, 100) }, initLatch) .withDispatcher("akka.actor.$dispatcher")) } } class RequestorActor(val computations: List<ActorRef>, val initLatch: CountDownLatch, val stopLatch: CountDownLatch) : UntypedAbstractActor() { private var received = 0 override fun onReceive(message: Any?) { when (message) { is Long -> { if (++received >= ROUNDS) { context.stop(self) stopLatch.countDown() } else { computations[ThreadLocalRandom.current().nextInt(0, computations.size)] .tell(ThreadLocalRandom.current().nextLong(), self) } } else -> unhandled(message) } } override fun preStart() { initLatch.countDown() } } class ComputationActor(val coefficients: LongArray, val initLatch: CountDownLatch) : UntypedAbstractActor() { override fun onReceive(message: Any?) { when (message) { is Long -> { var result = 0L for (coefficient in coefficients) { result += coefficient * message } sender.tell(result, self) } is Stop -> { context.stop(self) } else -> unhandled(message) } } override fun preStart() { initLatch.countDown() } } }
benchmarks/src/jmh/kotlin/benchmarks/akka/StatefulActorAkkaBenchmark.kt
900331363
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:JvmMultifileClass @file:JvmName("FlowKt") @file:Suppress("UNCHECKED_CAST") package kotlinx.coroutines.flow import kotlinx.coroutines.* import kotlinx.coroutines.flow.internal.* import kotlin.jvm.* import kotlinx.coroutines.flow.internal.unsafeFlow as flow import kotlinx.coroutines.flow.unsafeTransform as transform /** * Returns a flow containing only values of the original flow that match the given [predicate]. */ public inline fun <T> Flow<T>.filter(crossinline predicate: suspend (T) -> Boolean): Flow<T> = transform { value -> if (predicate(value)) return@transform emit(value) } /** * Returns a flow containing only values of the original flow that do not match the given [predicate]. */ public inline fun <T> Flow<T>.filterNot(crossinline predicate: suspend (T) -> Boolean): Flow<T> = transform { value -> if (!predicate(value)) return@transform emit(value) } /** * Returns a flow containing only values that are instances of specified type [R]. */ @Suppress("UNCHECKED_CAST") public inline fun <reified R> Flow<*>.filterIsInstance(): Flow<R> = filter { it is R } as Flow<R> /** * Returns a flow containing only values of the original flow that are not null. */ public fun <T: Any> Flow<T?>.filterNotNull(): Flow<T> = transform<T?, T> { value -> if (value != null) return@transform emit(value) } /** * Returns a flow containing the results of applying the given [transform] function to each value of the original flow. */ public inline fun <T, R> Flow<T>.map(crossinline transform: suspend (value: T) -> R): Flow<R> = transform { value -> return@transform emit(transform(value)) } /** * Returns a flow that contains only non-null results of applying the given [transform] function to each value of the original flow. */ public inline fun <T, R: Any> Flow<T>.mapNotNull(crossinline transform: suspend (value: T) -> R?): Flow<R> = transform { value -> val transformed = transform(value) ?: return@transform return@transform emit(transformed) } /** * Returns a flow that wraps each element into [IndexedValue], containing value and its index (starting from zero). */ public fun <T> Flow<T>.withIndex(): Flow<IndexedValue<T>> = flow { var index = 0 collect { value -> emit(IndexedValue(checkIndexOverflow(index++), value)) } } /** * Returns a flow that invokes the given [action] **before** each value of the upstream flow is emitted downstream. */ public fun <T> Flow<T>.onEach(action: suspend (T) -> Unit): Flow<T> = transform { value -> action(value) return@transform emit(value) } /** * Folds the given flow with [operation], emitting every intermediate result, including [initial] value. * Note that initial value should be immutable (or should not be mutated) as it is shared between different collectors. * For example: * ``` * flowOf(1, 2, 3).scan(emptyList<Int>()) { acc, value -> acc + value }.toList() * ``` * will produce `[], [1], [1, 2], [1, 2, 3]`. * * This function is an alias to [runningFold] operator. */ public fun <T, R> Flow<T>.scan(initial: R, @BuilderInference operation: suspend (accumulator: R, value: T) -> R): Flow<R> = runningFold(initial, operation) /** * Folds the given flow with [operation], emitting every intermediate result, including [initial] value. * Note that initial value should be immutable (or should not be mutated) as it is shared between different collectors. * For example: * ``` * flowOf(1, 2, 3).runningFold(emptyList<Int>()) { acc, value -> acc + value }.toList() * ``` * will produce `[], [1], [1, 2], [1, 2, 3]`. */ public fun <T, R> Flow<T>.runningFold(initial: R, @BuilderInference operation: suspend (accumulator: R, value: T) -> R): Flow<R> = flow { var accumulator: R = initial emit(accumulator) collect { value -> accumulator = operation(accumulator, value) emit(accumulator) } } /** * Reduces the given flow with [operation], emitting every intermediate result, including initial value. * The first element is taken as initial value for operation accumulator. * This operator has a sibling with initial value -- [scan]. * * For example: * ``` * flowOf(1, 2, 3, 4).runningReduce { acc, value -> acc + value }.toList() * ``` * will produce `[1, 3, 6, 10]` */ public fun <T> Flow<T>.runningReduce(operation: suspend (accumulator: T, value: T) -> T): Flow<T> = flow { var accumulator: Any? = NULL collect { value -> accumulator = if (accumulator === NULL) { value } else { operation(accumulator as T, value) } emit(accumulator as T) } }
kotlinx-coroutines-core/common/src/flow/operators/Transform.kt
3498878207
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.test.java import com.intellij.psi.PsiCodeBlock import com.intellij.psi.PsiElement import com.intellij.psi.PsiIdentifier import com.intellij.psi.PsiModifierListOwner import org.jetbrains.uast.UFile import org.jetbrains.uast.UReferenceExpression import org.jetbrains.uast.util.IndentedPrintingVisitor import org.jetbrains.uast.test.common.visitUFileAndGetResult import org.jetbrains.uast.test.env.assertEqualsToFile import org.jetbrains.uast.toUElementOfType import java.io.File abstract class AbstractJavaResolveEverythingTest : AbstractJavaUastTest() { private fun UFile.resolvableWithTargets() = object : IndentedPrintingVisitor(PsiCodeBlock::class, PsiModifierListOwner::class) { override fun render(element: PsiElement): CharSequence? = element .takeIf { it !is PsiIdentifier } // no sense to handle PsiIdentifier, see IDEA-207979 ?.toUElementOfType<UReferenceExpression>()?.let { ref -> StringBuilder().apply { val parent = ref.uastParent append(parent?.asLogString()) append(" -> ") append(ref.asLogString()) append(" -> ") append(ref.resolve()) append(": ") append(ref.resolvedName) } } }.visitUFileAndGetResult(this) override fun check(testName: String, file: UFile) { val expected = File(testDataPath, testName.substringBeforeLast('.') + ".resolved.txt") assertEqualsToFile("resolved", expected, file.resolvableWithTargets()) } }
uast/uast-tests/test/org/jetbrains/uast/test/java/AbstractJavaResolveEverythingTest.kt
1000816232
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.integration.apis import slatekit.apis.Api import slatekit.apis.Action import slatekit.apis.AuthModes import slatekit.apis.Verbs import slatekit.context.Context import slatekit.common.Sources import slatekit.requests.Request import slatekit.common.info.* @Api(area = "app", name = "info", desc = "api info about the application and host", auth = AuthModes.KEYED, roles = ["admin"], verb = Verbs.AUTO, sources = [Sources.ALL]) class InfoApi(val context: Context) { @Action(desc = "gets info about this build") fun build(): Build = context.info.build @Action(desc = "get info about the application") fun about(): About = context.info.about @Action(desc = "get info about the application") fun cmd(cmd: Request): About = context.info.about @Action(desc = "gets info about the language") fun lang(): Lang = context.info.lang @Action(desc = "gets info about the folders") fun dirs(): Folders = context.dirs ?: Folders.none }
src/lib/kotlin/slatekit-integration/src/main/kotlin/slatekit/integration/apis/InfoApi.kt
3713452883
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.search import org.jetbrains.plugins.github.api.data.GithubIssueState import org.jetbrains.plugins.github.api.data.request.search.GithubIssueSearchSort import org.jetbrains.plugins.github.api.util.GithubApiSearchQueryBuilder import java.text.ParseException import java.text.SimpleDateFormat internal class GithubPullRequestSearchQuery(private val terms: List<Term<*>>) { fun buildApiSearchQuery(searchQueryBuilder: GithubApiSearchQueryBuilder) { for (term in terms) { when (term) { is Term.QueryPart -> { searchQueryBuilder.query(term.apiValue) } is Term.Qualifier -> { searchQueryBuilder.qualifier(term.apiName, term.apiValue) } } } } fun isEmpty() = terms.isEmpty() override fun toString(): String { val builder = StringBuilder() for (term in terms) { builder.append(term.toString()) if (builder.isNotEmpty()) builder.append(" ") } return builder.toString() } companion object { private val DATE_FORMAT = SimpleDateFormat("yyyy-MM-dd") fun parseFromString(string: String): GithubPullRequestSearchQuery { val result = mutableListOf<Term<*>>() val terms = string.split(' ') for (term in terms) { if (term.isEmpty()) continue val colonIdx = term.indexOf(':') if (colonIdx < 0) { result.add(Term.QueryPart(term)) } else { try { result.add(QualifierName.valueOf(term.substring(0, colonIdx)).createTerm(term.substring(colonIdx + 1))) } catch (e: IllegalArgumentException) { result.add(Term.QueryPart(term)) } } } return GithubPullRequestSearchQuery(result) } } @Suppress("EnumEntryName") enum class QualifierName(val apiName: String) { state("state") { override fun createTerm(value: String) = Term.Qualifier.Enum.from<GithubIssueState>(this, value) }, assignee("assignee") { override fun createTerm(value: String) = Term.Qualifier.Simple(this, value) }, author("author") { override fun createTerm(value: String) = Term.Qualifier.Simple(this, value) }, after("created") { override fun createTerm(value: String) = Term.Qualifier.Date.After.from(this, value) }, before("created") { override fun createTerm(value: String) = Term.Qualifier.Date.Before.from(this, value) }, sortBy("sort") { override fun createTerm(value: String) = Term.Qualifier.Enum.from<GithubIssueSearchSort>(this, value) }; abstract fun createTerm(value: String): Term<*> } /** * Part of search query (search term) */ sealed class Term<T : Any>(protected val value: T) { abstract val apiValue: String? class QueryPart(value: String) : Term<String>(value) { override val apiValue = this.value override fun toString(): String = value } sealed class Qualifier<T : Any>(protected val name: QualifierName, value: T) : Term<T>(value) { val apiName: String = name.apiName override fun toString(): String = "$name:$value" class Simple(name: QualifierName, value: String) : Qualifier<String>(name, value) { override val apiValue = this.value } class Enum<T : kotlin.Enum<T>>(name: QualifierName, value: T) : Qualifier<kotlin.Enum<T>>(name, value) { override val apiValue = this.value.name companion object { inline fun <reified T : kotlin.Enum<T>> from(name: QualifierName, value: String): Term<*> { return try { Enum(name, enumValueOf<T>(value)) } catch (e: IllegalArgumentException) { Simple(name, value) } } } } sealed class Date(name: QualifierName, value: java.util.Date) : Qualifier<java.util.Date>(name, value) { protected fun formatDate(): String = DATE_FORMAT.format(this.value) override fun toString(): String = "$name:${formatDate()}" class Before(name: QualifierName, value: java.util.Date) : Date(name, value) { override val apiValue = "<${formatDate()}" companion object { fun from(name: QualifierName, value: String): Term<*> { val date = try { DATE_FORMAT.parse(value) } catch (e: ParseException) { return Simple(name, value) } return Before(name, date) } } } class After(name: QualifierName, value: java.util.Date) : Date(name, value) { override val apiValue = ">${formatDate()}" companion object { fun from(name: QualifierName, value: String): Term<*> { return try { After(name, DATE_FORMAT.parse(value)) } catch (e: ParseException) { Simple(name, value) } } } } } } } }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/search/GithubPullRequestSearchQuery.kt
2501606399
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api import com.intellij.openapi.util.io.StreamUtil import com.intellij.util.ThrowableConvertor import org.jetbrains.plugins.github.api.GithubApiRequest.* import org.jetbrains.plugins.github.api.data.* import org.jetbrains.plugins.github.api.data.request.* import org.jetbrains.plugins.github.api.util.GithubApiPagesLoader import org.jetbrains.plugins.github.api.util.GithubApiSearchQueryBuilder import org.jetbrains.plugins.github.api.util.GithubApiUrlQueryBuilder import java.awt.Image /** * Collection of factory methods for API requests used in plugin * TODO: improve url building (DSL?) */ object GithubApiRequests { object CurrentUser : Entity("/user") { @JvmStatic fun get(server: GithubServerPath) = get(getUrl(server, urlSuffix)) @JvmStatic fun get(url: String) = Get.json<GithubAuthenticatedUser>(url).withOperationName("get profile information") @JvmStatic fun getAvatar(url: String) = object : Get<Image>(url) { override fun extractResult(response: GithubApiResponse): Image { return response.handleBody(ThrowableConvertor { GithubApiContentHelper.loadImage(it) }) } }.withOperationName("get profile avatar") object Repos : Entity("/repos") { @JvmOverloads @JvmStatic fun pages(server: GithubServerPath, type: Type = Type.DEFAULT, visibility: Visibility = Visibility.DEFAULT, affiliation: Affiliation = Affiliation.DEFAULT, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, type, visibility, affiliation, pagination), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, type: Type = Type.DEFAULT, visibility: Visibility = Visibility.DEFAULT, affiliation: Affiliation = Affiliation.DEFAULT, pagination: GithubRequestPagination? = null): GithubApiRequest<GithubResponsePage<GithubRepo>> { if (type != Type.DEFAULT && (visibility != Visibility.DEFAULT || affiliation != Affiliation.DEFAULT)) { throw IllegalArgumentException("Param 'type' should not be used together with 'visibility' or 'affiliation'") } return get(getUrl(server, CurrentUser.urlSuffix, urlSuffix, getQuery(type.toString(), visibility.toString(), affiliation.toString(), pagination?.toString().orEmpty()))) } @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get user repositories") @JvmStatic fun create(server: GithubServerPath, name: String, description: String, private: Boolean, autoInit: Boolean? = null) = Post.json<GithubRepo>(getUrl(server, CurrentUser.urlSuffix, urlSuffix), GithubRepoRequest(name, description, private, autoInit)) .withOperationName("create user repository") } object Orgs : Entity("/orgs") { @JvmOverloads @JvmStatic fun pages(server: GithubServerPath, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, pagination), ::get) fun get(server: GithubServerPath, pagination: GithubRequestPagination? = null) = get(getUrl(server, CurrentUser.urlSuffix, urlSuffix, getQuery(pagination?.toString().orEmpty()))) fun get(url: String) = Get.jsonPage<GithubOrg>(url).withOperationName("get user organizations") } object RepoSubs : Entity("/subscriptions") { @JvmStatic fun pages(server: GithubServerPath) = GithubApiPagesLoader.Request(get(server), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, pagination: GithubRequestPagination? = null) = get(getUrl(server, CurrentUser.urlSuffix, urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get repository subscriptions") } } object Organisations : Entity("/orgs") { object Repos : Entity("/repos") { @JvmStatic fun pages(server: GithubServerPath, organisation: String, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, organisation, pagination), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, organisation: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Organisations.urlSuffix, "/", organisation, urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get organisation repositories") @JvmStatic fun create(server: GithubServerPath, organisation: String, name: String, description: String, private: Boolean) = Post.json<GithubRepo>(getUrl(server, Organisations.urlSuffix, "/", organisation, urlSuffix), GithubRepoRequest(name, description, private, null)) .withOperationName("create organisation repository") } } object Repos : Entity("/repos") { @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String) = Get.Optional.json<GithubRepoDetailed>(getUrl(server, urlSuffix, "/$username/$repoName")) .withOperationName("get information for repository $username/$repoName") @JvmStatic fun delete(server: GithubServerPath, username: String, repoName: String) = delete(getUrl(server, urlSuffix, "/$username/$repoName")).withOperationName("delete repository $username/$repoName") @JvmStatic fun delete(url: String) = Delete.json<Unit>(url).withOperationName("delete repository at $url") object Branches : Entity("/branches") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubBranch>(url).withOperationName("get branches") } object Commits : Entity("/commits") { @JvmStatic fun getDiff(repository: GHRepositoryCoordinates, ref: String) = object : Get<String>(getUrl(repository, urlSuffix, "/$ref"), GithubApiContentHelper.V3_DIFF_JSON_MIME_TYPE) { override fun extractResult(response: GithubApiResponse): String { return response.handleBody(ThrowableConvertor { StreamUtil.readText(it, Charsets.UTF_8) }) } }.withOperationName("get diff for ref") @JvmStatic fun getDiff(repository: GHRepositoryCoordinates, refA: String, refB: String) = object : Get<String>(getUrl(repository, "/compare/$refA...$refB"), GithubApiContentHelper.V3_DIFF_JSON_MIME_TYPE) { override fun extractResult(response: GithubApiResponse): String { return response.handleBody(ThrowableConvertor { StreamUtil.readText(it, Charsets.UTF_8) }) } }.withOperationName("get diff between refs") } object Forks : Entity("/forks") { @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String) = Post.json<GithubRepo>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix), Any()) .withOperationName("fork repository $username/$repoName for cuurent user") @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get forks") } object Assignees : Entity("/assignees") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubUser>(url).withOperationName("get assignees") } object Labels : Entity("/labels") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubIssueLabel>(url).withOperationName("get assignees") } object Collaborators : Entity("/collaborators") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubUserWithPermissions>(url).withOperationName("get collaborators") @JvmStatic fun add(server: GithubServerPath, username: String, repoName: String, collaborator: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", collaborator)) } object Issues : Entity("/issues") { @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String, title: String, body: String? = null, milestone: Long? = null, labels: List<String>? = null, assignees: List<String>? = null) = Post.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix), GithubCreateIssueRequest(title, body, milestone, labels, assignees)) @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String, state: String? = null, assignee: String? = null) = GithubApiPagesLoader.Request(get(server, username, repoName, state, assignee), ::get) @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, state: String? = null, assignee: String? = null, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param("state", state); param("assignee", assignee); param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubIssue>(url).withOperationName("get issues in repository") @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, id: String) = Get.Optional.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", id)) @JvmStatic fun updateState(server: GithubServerPath, username: String, repoName: String, id: String, open: Boolean) = Patch.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", id), GithubChangeIssueStateRequest(if (open) "open" else "closed")) @JvmStatic fun updateAssignees(server: GithubServerPath, username: String, repoName: String, id: String, assignees: Collection<String>) = Patch.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", id), GithubAssigneesCollectionRequest(assignees)) object Comments : Entity("/comments") { @JvmStatic fun create(repository: GHRepositoryCoordinates, issueId: Long, body: String) = create(repository.serverPath, repository.repositoryPath.owner, repository.repositoryPath.repository, issueId.toString(), body) @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String, issueId: String, body: String) = Post.json<GithubIssueCommentWithHtml>( getUrl(server, Repos.urlSuffix, "/$username/$repoName", Issues.urlSuffix, "/", issueId, urlSuffix), GithubCreateIssueCommentRequest(body), GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE) @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String, issueId: String) = GithubApiPagesLoader.Request(get(server, username, repoName, issueId), ::get) @JvmStatic fun pages(url: String) = GithubApiPagesLoader.Request(get(url), ::get) @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, issueId: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", Issues.urlSuffix, "/", issueId, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubIssueCommentWithHtml>(url, GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE) .withOperationName("get comments for issue") } object Labels : Entity("/labels") { @JvmStatic fun replace(server: GithubServerPath, username: String, repoName: String, issueId: String, labels: Collection<String>) = Put.jsonList<GithubIssueLabel>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", Issues.urlSuffix, "/", issueId, urlSuffix), GithubLabelsCollectionRequest(labels)) } } object PullRequests : Entity("/pulls") { @JvmStatic fun getDiff(repository: GHRepositoryCoordinates, number: Long) = object : Get<String>(getUrl(repository, urlSuffix, "/$number"), GithubApiContentHelper.V3_DIFF_JSON_MIME_TYPE) { override fun extractResult(response: GithubApiResponse): String { return response.handleBody(ThrowableConvertor { StreamUtil.readText(it, Charsets.UTF_8) }) } }.withOperationName("get pull request diff file") @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String, title: String, description: String, head: String, base: String) = Post.json<GithubPullRequestDetailed>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix), GithubPullRequestRequest(title, description, head, base)) .withOperationName("create pull request in $username/$repoName") @JvmStatic fun update(serverPath: GithubServerPath, username: String, repoName: String, number: Long, title: String? = null, body: String? = null, state: GithubIssueState? = null, base: String? = null, maintainerCanModify: Boolean? = null) = Patch.json<GithubPullRequestDetailed>(getUrl(serverPath, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/$number"), GithubPullUpdateRequest(title, body, state, base, maintainerCanModify)) .withOperationName("update pull request $number") @JvmStatic fun update(url: String, title: String? = null, body: String? = null, state: GithubIssueState? = null, base: String? = null, maintainerCanModify: Boolean? = null) = Patch.json<GithubPullRequestDetailed>(url, GithubPullUpdateRequest(title, body, state, base, maintainerCanModify)) .withOperationName("update pull request") @JvmStatic fun merge(server: GithubServerPath, repoPath: GHRepositoryPath, number: Long, commitSubject: String, commitBody: String, headSha: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, "/$number", "/merge"), GithubPullRequestMergeRequest(commitSubject, commitBody, headSha, GithubPullRequestMergeMethod.merge)) .withOperationName("merge pull request ${number}") @JvmStatic fun squashMerge(server: GithubServerPath, repoPath: GHRepositoryPath, number: Long, commitSubject: String, commitBody: String, headSha: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, "/$number", "/merge"), GithubPullRequestMergeRequest(commitSubject, commitBody, headSha, GithubPullRequestMergeMethod.squash)) .withOperationName("squash and merge pull request ${number}") @JvmStatic fun rebaseMerge(server: GithubServerPath, repoPath: GHRepositoryPath, number: Long, headSha: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, "/$number", "/merge"), GithubPullRequestMergeRebaseRequest(headSha)) .withOperationName("rebase and merge pull request ${number}") @JvmStatic fun getListETag(server: GithubServerPath, repoPath: GHRepositoryPath) = object : Get<String?>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(GithubRequestPagination(pageSize = 1)) })) { override fun extractResult(response: GithubApiResponse) = response.findHeader("ETag") }.withOperationName("get pull request list ETag") object Reviewers : Entity("/requested_reviewers") { @JvmStatic fun add(server: GithubServerPath, username: String, repoName: String, number: Long, reviewers: Collection<String>, teamReviewers: List<String>) = Post.json<Unit>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", PullRequests.urlSuffix, "/$number", urlSuffix), GithubReviewersCollectionRequest(reviewers, teamReviewers)) @JvmStatic fun remove(server: GithubServerPath, username: String, repoName: String, number: Long, reviewers: Collection<String>, teamReviewers: List<String>) = Delete.json<Unit>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", PullRequests.urlSuffix, "/$number", urlSuffix), GithubReviewersCollectionRequest(reviewers, teamReviewers)) } object Commits : Entity("/commits") { @JvmStatic fun pages(repository: GHRepositoryCoordinates, number: Long) = GithubApiPagesLoader.Request(get(repository, number), ::get) @JvmStatic fun pages(url: String) = GithubApiPagesLoader.Request(get(url), ::get) @JvmStatic fun get(repository: GHRepositoryCoordinates, number: Long, pagination: GithubRequestPagination? = null) = get(getUrl(repository, PullRequests.urlSuffix, "/$number", urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubCommit>(url) .withOperationName("get commits for pull request") } object Comments : Entity("/comments") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String, number: Long) = GithubApiPagesLoader.Request(get(server, username, repoName, number), ::get) @JvmStatic fun pages(url: String) = GithubApiPagesLoader.Request(get(url), ::get) @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, number: Long, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", PullRequests.urlSuffix, "/$number", urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubPullRequestCommentWithHtml>(url, GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE) .withOperationName("get comments for pull request") @JvmStatic fun createReply(repository: GHRepositoryCoordinates, pullRequest: Long, commentId: Long, body: String) = Post.json<GithubPullRequestCommentWithHtml>( getUrl(repository, PullRequests.urlSuffix, "/$pullRequest", "/comments/$commentId/replies"), mapOf("body" to body), GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE).withOperationName("reply to pull request review comment") @JvmStatic fun create(repository: GHRepositoryCoordinates, pullRequest: Long, commitSha: String, filePath: String, diffLine: Int, body: String) = Post.json<GithubPullRequestCommentWithHtml>( getUrl(repository, PullRequests.urlSuffix, "/$pullRequest", "/comments"), mapOf("body" to body, "commit_id" to commitSha, "path" to filePath, "position" to diffLine), GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE).withOperationName("create pull request review comment") } } } object Gists : Entity("/gists") { @JvmStatic fun create(server: GithubServerPath, contents: List<GithubGistRequest.FileContent>, description: String, public: Boolean) = Post.json<GithubGist>(getUrl(server, urlSuffix), GithubGistRequest(contents, description, public)) .withOperationName("create gist") @JvmStatic fun get(server: GithubServerPath, id: String) = Get.Optional.json<GithubGist>(getUrl(server, urlSuffix, "/$id")) .withOperationName("get gist $id") @JvmStatic fun delete(server: GithubServerPath, id: String) = Delete.json<Unit>(getUrl(server, urlSuffix, "/$id")) .withOperationName("delete gist $id") } object Search : Entity("/search") { object Issues : Entity("/issues") { @JvmStatic fun pages(server: GithubServerPath, repoPath: GHRepositoryPath?, state: String?, assignee: String?, query: String?) = GithubApiPagesLoader.Request(get(server, repoPath, state, assignee, query), ::get) @JvmStatic fun get(server: GithubServerPath, repoPath: GHRepositoryPath?, state: String?, assignee: String?, query: String?, pagination: GithubRequestPagination? = null) = get(getUrl(server, Search.urlSuffix, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param("q", GithubApiSearchQueryBuilder.searchQuery { qualifier("repo", repoPath?.toString().orEmpty()) qualifier("state", state) qualifier("assignee", assignee) query(query) }) param(pagination) })) @JvmStatic fun get(server: GithubServerPath, query: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Search.urlSuffix, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param("q", query) param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonSearchPage<GithubSearchedIssue>(url).withOperationName("search issues in repository") } } object Auth : Entity("/authorizations") { @JvmStatic fun create(server: GithubServerPath, scopes: List<String>, note: String) = Post.json<GithubAuthorization>(getUrl(server, urlSuffix), GithubAuthorizationCreateRequest(scopes, note, null)) .withOperationName("create authorization $note") @JvmStatic fun get(server: GithubServerPath, pagination: GithubRequestPagination? = null) = get(getUrl(server, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubAuthorization>(url) .withOperationName("get authorizations") @JvmStatic fun pages(server: GithubServerPath, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, pagination), ::get) } abstract class Entity(val urlSuffix: String) private fun getUrl(server: GithubServerPath, suffix: String) = server.toApiUrl() + suffix private fun getUrl(repository: GHRepositoryCoordinates, vararg suffixes: String) = getUrl(repository.serverPath, Repos.urlSuffix, "/", repository.repositoryPath.toString(), *suffixes) fun getUrl(server: GithubServerPath, vararg suffixes: String) = StringBuilder(server.toApiUrl()).append(*suffixes).toString() private fun getQuery(vararg queryParts: String): String { val builder = StringBuilder() for (part in queryParts) { if (part.isEmpty()) continue if (builder.isEmpty()) builder.append("?") else builder.append("&") builder.append(part) } return builder.toString() } }
plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequests.kt
3096175970
/* * Copyright 2020 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.uamp import android.net.Uri import android.support.v4.media.MediaBrowserCompat import androidx.recyclerview.widget.DiffUtil import android.support.v4.media.MediaBrowserCompat.MediaItem import com.example.android.uamp.viewmodels.MediaItemFragmentViewModel /** * Data class to encapsulate properties of a [MediaItem]. * * If an item is [browsable] it means that it has a list of child media items that * can be retrieved by passing the mediaId to [MediaBrowserCompat.subscribe]. * * Objects of this class are built from [MediaItem]s in * [MediaItemFragmentViewModel.subscriptionCallback]. */ data class MediaItemData( val mediaId: String, val title: String, val subtitle: String, val albumArtUri: Uri, val browsable: Boolean, var playbackRes: Int) { companion object { /** * Indicates [playbackRes] has changed. */ const val PLAYBACK_RES_CHANGED = 1 /** * [DiffUtil.ItemCallback] for a [MediaItemData]. * * Since all [MediaItemData]s have a unique ID, it's easiest to check if two * items are the same by simply comparing that ID. * * To check if the contents are the same, we use the same ID, but it may be the * case that it's only the play state itself which has changed (from playing to * paused, or perhaps a different item is the active item now). In this case * we check both the ID and the playback resource. * * To calculate the payload, we use the simplest method possible: * - Since the title, subtitle, and albumArtUri are constant (with respect to mediaId), * there's no reason to check if they've changed. If the mediaId is the same, none of * those properties have changed. * - If the playback resource (playbackRes) has changed to reflect the change in playback * state, that's all that needs to be updated. We return [PLAYBACK_RES_CHANGED] as * the payload in this case. * - If something else changed, then refresh the full item for simplicity. */ val diffCallback = object : DiffUtil.ItemCallback<MediaItemData>() { override fun areItemsTheSame(oldItem: MediaItemData, newItem: MediaItemData): Boolean = oldItem.mediaId == newItem.mediaId override fun areContentsTheSame(oldItem: MediaItemData, newItem: MediaItemData) = oldItem.mediaId == newItem.mediaId && oldItem.playbackRes == newItem.playbackRes override fun getChangePayload(oldItem: MediaItemData, newItem: MediaItemData) = if (oldItem.playbackRes != newItem.playbackRes) { PLAYBACK_RES_CHANGED } else null } } }
app/src/main/java/com/example/android/uamp/MediaItemData.kt
3787472529
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.stats.completion.events import com.intellij.stats.completion.Action import com.intellij.stats.completion.LogEventVisitor class CustomMessageEvent(userId: String, sessionId: String, @JvmField var text: String, bucket: String, timestamp: Long) : LogEvent(userId, sessionId, Action.CUSTOM, bucket, timestamp) { override fun accept(visitor: LogEventVisitor) { visitor.visit(this) } }
plugins/stats-collector/log-events/src/com/intellij/stats/completion/events/CustomMessageEvent.kt
2735408625
fun foo(x: Any) = when (x) { 0, 1 -> "bit" else -> "something" } fun box(): String { if (foo(0) != "bit") return "Fail 0" if (foo(1) != "bit") return "Fail 1" if (foo(2) != "something") return "Fail 2" return "OK" }
backend.native/tests/external/codegen/box/when/multipleEntries.kt
4250845843
package com.alibaba.demo.coroutine import io.kotest.core.spec.style.AnnotationSpec import kotlinx.coroutines.* import mu.KotlinLogging import org.junit.Assert.* class CoroutineThreadContextElementTest : AnnotationSpec() { private val logger = KotlinLogging.logger {} @Test fun threadContextElement_passByValue(): Unit = runBlocking { val mainValue = "main-${System.currentTimeMillis()}" val launchValue = "launch-${System.currentTimeMillis()}" val testThread = Thread.currentThread() // String ThreadLocal, String is immutable value, can only be passed by value val threadLocal = ThreadLocal<String?>() threadLocal.set(mainValue) logger.info { "test thread - thread local value: ${threadLocal.get()}" } val job = launch(Dispatchers.Default + threadLocal.asContextElement(value = launchValue)) { logger.info { "launch thread - launch start, thread local value: ${threadLocal.get()}" } assertEquals(launchValue, threadLocal.get()) assertNotEquals(testThread, Thread.currentThread()) delay(5) logger.info { "launch thread - after delay, thread local value: ${threadLocal.get()}" } assertEquals(launchValue, threadLocal.get()) assertNotEquals(testThread, Thread.currentThread()) val reset = "job-reset-${threadLocal.get()}" threadLocal.set(reset) assertEquals(reset, threadLocal.get()) delay(5) logger.info { "launch thread - after delay set reset, thread local value: ${threadLocal.get()}" } // !!! After suspended delay function, reset ThreadLocal value is lost !!! // assertEquals(reset, threadLocal.get()) assertEquals(launchValue, threadLocal.get()) assertNotEquals(testThread, Thread.currentThread()) } job.join() logger.info { "test thread - after launch, thread local value: ${threadLocal.get()}" } assertEquals(mainValue, threadLocal.get()) } @Test fun threadContextElement_passByReference(): Unit = runBlocking { data class Reference(var data: Int = 42) val mainValue = Reference() val launchValue = Reference(4242) val testThread = Thread.currentThread() // Reference ThreadLocal, mutable value, pass by reference val threadLocal = ThreadLocal<Reference>() // declare thread-local variable threadLocal.set(mainValue) logger.info { "test thread - thread local value: ${threadLocal.get()}" } val job = launch(Dispatchers.Default + threadLocal.asContextElement(value = launchValue)) { logger.info { "launch thread - launch start, thread local value: ${threadLocal.get()}" } assertEquals(launchValue, threadLocal.get()) assertNotEquals(testThread, Thread.currentThread()) delay(5) logger.info { "launch thread - after delay, thread local value: ${threadLocal.get()}" } assertEquals(launchValue, threadLocal.get()) assertNotEquals(testThread, Thread.currentThread()) val reset = -42 threadLocal.get().data = reset delay(5) logger.info { "launch thread - after delay set reset, thread local value: ${threadLocal.get()}" } assertEquals(Reference(reset), threadLocal.get()) assertNotEquals(testThread, Thread.currentThread()) } job.join() logger.info { "test thread - after launch in test thread, thread local value: ${threadLocal.get()}" } assertEquals(mainValue, threadLocal.get()) } @Test fun twoThreadContextElement(): Unit = runBlocking { val mainValue = "main-a-${System.currentTimeMillis()}" val testThread = Thread.currentThread() val anotherMainValue = "main-another-${System.currentTimeMillis()}" val threadLocal = ThreadLocal<String?>() // declare thread-local variable val anotherThreadLocal = ThreadLocal<String?>() // declare thread-local variable threadLocal.set(mainValue) anotherThreadLocal.set(anotherMainValue) logger.info { "test thread - thread local value: ${threadLocal.get()} | ${anotherThreadLocal.get()}" } val launch1Value = "aLaunch1" launch(Dispatchers.Default + threadLocal.asContextElement(value = launch1Value)) { assertEquals(launch1Value, threadLocal.get()) assertNull(anotherThreadLocal.get()) assertNotEquals(testThread, Thread.currentThread()) delay(5) logger.info { "launch thread - after delay, thread local value: ${threadLocal.get()} | ${anotherThreadLocal.get()}" } assertEquals(launch1Value, threadLocal.get()) assertNull(anotherThreadLocal.get()) assertNotEquals(testThread, Thread.currentThread()) val resetA = "job-reset-${threadLocal.get()}" threadLocal.set(resetA) val resetAnother = "job-reset-${anotherThreadLocal.get()}" anotherThreadLocal.set(resetAnother) logger.info { "launch thread - before delay set reset, thread local value: ${threadLocal.get()} | ${anotherThreadLocal.get()}" } delay(5) logger.info { "launch thread - after delay set reset, thread local value: ${threadLocal.get()} | ${anotherThreadLocal.get()}" } // !!! After suspended delay function, reset ThreadLocal value is lost !!! // assertEquals(resetA, threadLocal.get()) assertEquals(launch1Value, threadLocal.get()) // !!! After suspended delay, ThreadLocal without ThreadContextElement is not clear !!! assertEquals(resetAnother, anotherThreadLocal.get()) assertNotEquals(testThread, Thread.currentThread()) }.join() logger.info { "test thread - after launch1, thread local value: ${threadLocal.get()} | ${anotherThreadLocal.get()}" } assertEquals(mainValue, threadLocal.get()) assertEquals(anotherMainValue, anotherThreadLocal.get()) val launch2Value = "aLaunch2" val anotherLaunch2Value = "anotherLaunch2" launch( Dispatchers.Default + threadLocal.asContextElement(value = launch2Value) + anotherThreadLocal.asContextElement( value = anotherLaunch2Value ) ) { logger.info { "launch thread - launch start, thread local value: ${threadLocal.get()} | ${anotherThreadLocal.get()}" } assertEquals(launch2Value, threadLocal.get()) assertEquals(anotherLaunch2Value, anotherThreadLocal.get()) assertNotEquals(testThread, Thread.currentThread()) delay(5) logger.info { "launch thread - after delay, thread local value: ${threadLocal.get()} | ${anotherThreadLocal.get()}" } assertEquals(launch2Value, threadLocal.get()) assertEquals(anotherLaunch2Value, anotherThreadLocal.get()) assertNotEquals(testThread, Thread.currentThread()) val resetA = "job-reset-${threadLocal.get()}" threadLocal.set(resetA) val resetAnother = "job-reset-${anotherThreadLocal.get()}" anotherThreadLocal.set(resetAnother) logger.info { "launch thread - before delay set reset, thread local value: ${threadLocal.get()} | ${anotherThreadLocal.get()}" } delay(5) logger.info { "launch thread - after delay set reset, thread local value: ${threadLocal.get()} | ${anotherThreadLocal.get()}" } // !!! After suspended delay function, reset ThreadLocal value is lost !!! // assertEquals(resetA, threadLocal.get()) // assertEquals(resetAnother, anotherThreadLocal.get()) assertEquals(launch2Value, threadLocal.get()) assertEquals(anotherLaunch2Value, anotherThreadLocal.get()) assertNotEquals(testThread, Thread.currentThread()) }.join() logger.info { "test thread - after launch2, thread local value: ${threadLocal.get()} | ${anotherThreadLocal.get()}" } assertEquals(mainValue, threadLocal.get()) assertEquals(anotherMainValue, anotherThreadLocal.get()) } }
ttl2-compatible/src/test/java/com/alibaba/demo/coroutine/CoroutineThreadContextElementTest.kt
4127449153
package vkm.vkm import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.graphics.Point import android.os.Bundle import android.os.Environment import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import vkm.vkm.utils.HttpUtils import vkm.vkm.utils.Proxy import vkm.vkm.utils.Swiper import vkm.vkm.utils.db.Db import vkm.vkm.utils.log import java.io.File import kotlin.coroutines.Continuation import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class MainActivity : AppCompatActivity() { companion object { private const val EXTERNAL_STORAGE_WRITE_PERMISSION = 1 } private var initialized = false private var permissionContinuation: Continuation<IntArray>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // asking for writing permissions val permissionCheck = ContextCompat.checkSelfPermission(applicationContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) GlobalScope.launch(Dispatchers.Main) { "starting permissions".log() if (permissionCheck != PackageManager.PERMISSION_GRANTED) { suspendCoroutine<IntArray> { permissionContinuation = it requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), EXTERNAL_STORAGE_WRITE_PERMISSION) }.takeIf { it.isEmpty() || it[0] != PackageManager.PERMISSION_GRANTED }?.let { finish() return@launch } } permissionContinuation = null "permissions received".log() initialize() startActivity(Intent(applicationContext, PagerActivity::class.java)) finish() } } private fun initialize() { val point = Point() windowManager.defaultDisplay.getSize(point) Swiper.SWIPE_DISTANCE_MIN = Math.max(point.x / 3, 200) loadProxy() DownloadManager.initialize(Db.instance(applicationContext).tracksDao()) initialized = true } private fun loadProxy() { val destinationDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).resolve("vkm") destinationDir.mkdirs() val file = File(destinationDir, "proxy.txt") if (file.exists()) { val proxyData = file.readLines()[0].split(":") HttpUtils.currentProxy = Proxy(host = proxyData[0], port = proxyData[1].toInt(), speed = 0, type = "") } } private fun saveProxy() { val currentProxy = HttpUtils.currentProxy ?: return val destinationDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).resolve("vkm") destinationDir.mkdirs() File(destinationDir, "proxy.txt").writeText("${currentProxy.host}:${currentProxy.port}") } override fun onPause() { super.onPause() if (initialized) { DownloadManager.stopDownload() } saveProxy() } override fun onStop() { super.onStop() if (initialized) { DownloadManager.stopDownload() } saveProxy() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { if (EXTERNAL_STORAGE_WRITE_PERMISSION == requestCode) { permissionContinuation?.resume(grantResults) } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } }
app/src/main/java/vkm/vkm/MainActivity.kt
77438429
package com.mbcdev.folkets import android.content.Context import android.view.View import android.widget.ImageView import android.widget.TextView import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Test import org.mockito.ArgumentCaptor import org.mockito.Mock import org.mockito.Mockito.* import org.mockito.MockitoAnnotations /** * Tests for [WordsRecyclerAdapter] * * Created by barry on 04/08/2017. */ class WordsRecyclerAdapterTests { @Mock private lateinit var wordList: List<Word> @Mock private lateinit var presenter: MainMvp.Presenter private lateinit var adapter: WordsRecyclerAdapter @Before fun setup() { MockitoAnnotations.initMocks(this) adapter = WordsRecyclerAdapter(wordList, presenter) } @Test fun `constructor does not invoke any list methods`() { WordsRecyclerAdapter(wordList, presenter) verifyZeroInteractions(wordList) } @Test fun `constructor does not invoke any presenter methods`() { WordsRecyclerAdapter(wordList, presenter) verifyZeroInteractions(presenter) } @Test fun `adapter size is the size of the word list`() { `when`(wordList.size).thenReturn(42) assertThat(adapter.itemCount).isEqualTo(42) } @Test fun `onBindViewHolder can handle null view holders`() { val word = mock(Word::class.java) `when`(wordList[0]).thenReturn(word) adapter.onBindViewHolder(null, 0) } @Test fun `onBindViewHolder can handle null words`() { val viewHolder = mock(WordsRecyclerAdapter.ViewHolder::class.java) `when`(wordList[0]).thenReturn(null) adapter.onBindViewHolder(viewHolder, 0) } @Test fun `viewHolder has the expected views`() { val view = getMockedView() val viewHolder = WordsRecyclerAdapter.ViewHolder(view) verify(view).findViewById<TextView>(eq(R.id.recycler_view_word)) verify(view).findViewById<TextView>(eq(R.id.recycler_view_type)) verify(view).findViewById<TextView>(eq(R.id.recycler_view_translation)) verify(view).findViewById<ImageView>(eq(R.id.recycler_view_tts)) verifyNoMoreInteractions(view) assertThat(viewHolder.wordTextView).isNotNull() assertThat(viewHolder.wordTypeTextView).isNotNull() assertThat(viewHolder.translationTextView).isNotNull() assertThat(viewHolder.ttsImageView).isNotNull() assertThat(viewHolder.holderView).isNotNull() assertThat(viewHolder.holderView.context).isNotNull() } @Test fun `wordTextView gets called with the correct text`() { val view = getMockedView() val viewHolder = WordsRecyclerAdapter.ViewHolder(view) val word = getMockedWord() `when`(wordList[0]).thenReturn(word) adapter.onBindViewHolder(viewHolder, 0) verify(viewHolder.wordTextView).text = "Glass" } @Test fun `wordTextView has correct flag drawable`() { val view = getMockedView() val viewHolder = WordsRecyclerAdapter.ViewHolder(view) val word = getMockedWord() `when`(wordList[0]).thenReturn(word) adapter.onBindViewHolder(viewHolder, 0) verify(viewHolder.wordTextView) .setCompoundDrawablesWithIntrinsicBounds(R.drawable.flag_sv, 0, 0, 0) } @Test fun `wordTypeTextView gets called with the correct text`() { val view = getMockedView() val viewHolder = WordsRecyclerAdapter.ViewHolder(view) val word = getMockedWord() `when`(wordList[0]).thenReturn(word) adapter.onBindViewHolder(viewHolder, 0) verify(viewHolder.wordTypeTextView).text = "Mocked noun" } @Test fun `translationTextView gets is gone from view when there are no translations`() { val view = getMockedView() val viewHolder = WordsRecyclerAdapter.ViewHolder(view) val word = getMockedWord() val wordsWithComments = mock(WordsWithComments::class.java) `when`(wordsWithComments.wordsFormattedForDisplay).thenReturn("") `when`(word.translations).thenReturn(wordsWithComments) `when`(wordList[0]).thenReturn(word) adapter.onBindViewHolder(viewHolder, 0) verify(viewHolder.translationTextView).visibility = View.GONE } @Test fun `translationTextView gets is shown when there are translations`() { val view = getMockedView() val viewHolder = WordsRecyclerAdapter.ViewHolder(view) val word = getMockedWord() val wordsWithComments = mock(WordsWithComments::class.java) `when`(wordsWithComments.wordsFormattedForDisplay).thenReturn("Plumbus") `when`(word.translations).thenReturn(wordsWithComments) `when`(wordList[0]).thenReturn(word) adapter.onBindViewHolder(viewHolder, 0) verify(viewHolder.translationTextView).visibility = View.VISIBLE verify(viewHolder.translationTextView).text = "Plumbus" } @Test fun `holder root view onClickListener calls presenter to select a word`() { val view = getMockedView() val viewHolder = WordsRecyclerAdapter.ViewHolder(view) val word = getMockedWord() `when`(wordList[0]).thenReturn(word) adapter.onBindViewHolder(viewHolder, 0) val clickCaptor = ArgumentCaptor.forClass(View.OnClickListener::class.java) verify(viewHolder.holderView).setOnClickListener(clickCaptor.capture()) val clickListener = clickCaptor.value assertThat(clickListener).isNotNull() clickListener.onClick(view) verify(presenter).onWordSelected(word) } @Test fun `tts view onClickListener calls presenter to speak a word`() { val view = getMockedView() val viewHolder = WordsRecyclerAdapter.ViewHolder(view) val word = getMockedWord() `when`(wordList[0]).thenReturn(word) adapter.onBindViewHolder(viewHolder, 0) val clickCaptor = ArgumentCaptor.forClass(View.OnClickListener::class.java) verify(viewHolder.ttsImageView).setOnClickListener(clickCaptor.capture()) val clickListener = clickCaptor.value assertThat(clickListener).isNotNull() clickListener.onClick(view) verify(presenter).onTtsRequested(word) } private fun getMockedWord(): Word { val word = mock(Word::class.java) `when`(word.word).thenReturn("Glass") `when`(word.flag).thenReturn(R.drawable.flag_sv) `when`(word.wordTypes).thenReturn(listOf(WordType.NOUN)) val wordWithComments = mock(WordsWithComments::class.java) `when`(word.translations).thenReturn(wordWithComments) return word } private fun getMockedView(): View { val view = mock(View::class.java) val context = mock(Context::class.java) val wordTextView = mock(TextView::class.java) val wordTypeTextView = mock(TextView::class.java) val translationTextView = mock(TextView::class.java) val ttsImageView = mock(ImageView::class.java) `when`(context.getString(R.string.word_type_noun)).thenReturn("Mocked noun") `when`(view.context).thenReturn(context) `when`(view.findViewById<TextView>(R.id.recycler_view_word)).thenReturn(wordTextView) `when`(view.findViewById<TextView>(R.id.recycler_view_type)).thenReturn(wordTypeTextView) `when`(view.findViewById<TextView>(R.id.recycler_view_translation)) .thenReturn(translationTextView) `when`(view.findViewById<ImageView>(R.id.recycler_view_tts)).thenReturn(ttsImageView) return view } }
app/src/test/kotlin/com/mbcdev/folkets/WordsRecyclerAdapterTests.kt
4091312859
/* * 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 import com.intellij.psi.PsiElement import com.intellij.psi.ResolveResult import org.jetbrains.annotations.ApiStatus interface UResolvable { /** * Resolve the reference. * Note that the reference is *always* resolved to an unwrapped [PsiElement], never to a [UElement]. * * @return the resolved element, or null if the reference couldn't be resolved. */ fun resolve(): PsiElement? } interface UMultiResolvable { /** * Returns multiple elements where the reference could be resolved. * It could happen if there is an ambiguity in code: it is incomplete or resolve target cannot be statically determined * * @see [com.intellij.psi.PsiPolyVariantReference] as a similar entity for plain PSI */ fun multiResolve(): Iterable<ResolveResult> } fun UResolvable.resolveToUElement(): UElement? = resolve().toUElement()
uast/uast-common/src/org/jetbrains/uast/baseElements/UResolvable.kt
817858337
interface <lineMarker>A</lineMarker> { fun <lineMarker>a</lineMarker>(){ } } class B : A { override fun <lineMarker>a</lineMarker>(){ } }
plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/overrideImplement/Trait.kt
468971738
// "Add remaining branches" "true" // ERROR: Unresolved reference: TODO // ERROR: Unresolved reference: TODO // ERROR: Unresolved reference: TODO sealed class Variant { object Singleton : Variant() class Something(val x: Int) : Variant() object Another : Variant() } fun test(v: Variant?) = wh<caret>en(v) { Variant.Singleton -> "s" }
plugins/kotlin/idea/tests/testData/quickfix/when/addRemainingBranchesSealed.kt
3385271357
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.contentRange import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.types.typeUtil.supertypes @Suppress("DEPRECATION") class ConvertTryFinallyToUseCallInspection : IntentionBasedInspection<KtTryExpression>( ConvertTryFinallyToUseCallIntention::class, problemText = KotlinBundle.message("convert.try.finally.to.use.before.text") ) { override fun inspectionTarget(element: KtTryExpression) = element.tryKeyword ?: element.tryBlock } class ConvertTryFinallyToUseCallIntention : SelfTargetingRangeIntention<KtTryExpression>( KtTryExpression::class.java, KotlinBundle.lazyMessage("convert.try.finally.to.use") ) { override fun applyTo(element: KtTryExpression, editor: Editor?) { val finallySection = element.finallyBlock ?: return val finallyExpression = finallySection.finalExpression.statements.single() val finallyExpressionReceiver = (finallyExpression as? KtQualifiedExpression)?.receiverExpression val resourceReference = finallyExpressionReceiver as? KtNameReferenceExpression val resourceName = resourceReference?.getReferencedNameAsName() val factory = KtPsiFactory(element) val useCallExpression = factory.buildExpression { if (resourceName != null) { appendName(resourceName) appendFixedText(".") } else if (finallyExpressionReceiver is KtThisExpression) { appendFixedText(finallyExpressionReceiver.text) appendFixedText(".") } appendFixedText("use {") if (resourceName != null) { appendName(resourceName) appendFixedText("->") } appendFixedText("\n") appendChildRange(element.tryBlock.contentRange()) appendFixedText("\n}") } val call = when (val result = element.replace(useCallExpression) as KtExpression) { is KtQualifiedExpression -> result.selectorExpression as? KtCallExpression ?: return is KtCallExpression -> result else -> return } val lambda = call.lambdaArguments.firstOrNull() ?: return val lambdaParameter = lambda.getLambdaExpression()?.valueParameters?.firstOrNull() ?: return editor?.selectionModel?.setSelection(lambdaParameter.startOffset, lambdaParameter.endOffset) } override fun applicabilityRange(element: KtTryExpression): TextRange? { // Single statement in finally, no catch blocks val finallySection = element.finallyBlock ?: return null val finallyExpression = finallySection.finalExpression.statements.singleOrNull() ?: return null if (element.catchClauses.isNotEmpty()) return null val context = element.analyze() val resolvedCall = finallyExpression.getResolvedCall(context) ?: return null if (resolvedCall.candidateDescriptor.name.asString() != "close") return null if (resolvedCall.extensionReceiver != null) return null val receiver = resolvedCall.dispatchReceiver ?: return null if (receiver.type.supertypes().all { it.constructor.declarationDescriptor?.fqNameSafe?.asString().let { s -> s != "java.io.Closeable" && s != "java.lang.AutoCloseable" } }) return null when (receiver) { is ExpressionReceiver -> { val expression = receiver.expression if (expression !is KtThisExpression) { val resourceReference = expression as? KtReferenceExpression ?: return null val resourceDescriptor = context[BindingContext.REFERENCE_TARGET, resourceReference] as? VariableDescriptor ?: return null if (resourceDescriptor.isVar) return null } } is ImplicitReceiver -> { } else -> return null } return TextRange(element.startOffset, element.tryBlock.lBrace?.endOffset ?: element.endOffset) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertTryFinallyToUseCallIntention.kt
713829509
annotation class A(vararg val s: String, val i: Int, val j: Int) @A(<caret>s = ["foo", "bar"], i = 1, j = 2) class C
plugins/kotlin/idea/tests/testData/intentions/removeAllArgumentNames/collectionLiteralIsNotLast.kt
3209357078
// WITH_STDLIB fun test() { val pair: Pair<List<Int>, List<Int>> = listOf(1 to 2, 3 to 4).<caret>filter { it.first > 1 }.filter { it.second > 2 }.unzip() }
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination/unzip.kt
3567809139
// "Replace with 'new'" "true" // WITH_STDLIB class A { @Deprecated("msg", ReplaceWith("new")) var old get() = new set(value) { new = value } var new = "" } fun foo() { val a = A() a.<caret>old += "foo" }
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/propertyModification.kt
2577914860
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.projectWizard import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.ide.wizard.NewProjectWizardLanguageStep import com.intellij.internal.statistic.StructuredIdeActivity import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.* import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.project.Project import java.lang.Integer.min class NewProjectWizardCollector : CounterUsagesCollector() { override fun getGroup() = GROUP companion object { private val GROUP = EventLogGroup("new.project.wizard.interactions", 2) private val sessionIdField = EventFields.Int("wizard_session_id") private val screenNumField = IntEventField("screen") private val typedCharsField = IntEventField("typed_chars") private val hitsField = IntEventField("hits") private val generatorTypeField = ClassEventField("generator") private val languageField = EventFields.String("language", NewProjectWizardLanguageStep.allLanguages.keys.toList()) private val gitField = EventFields.Boolean("git") private val isSucceededField = EventFields.Boolean("project_created") private val inputMaskField = EventFields.Long("input_mask") //events private val activity = GROUP.registerIdeActivity("new_project_wizard", finishEventAdditionalFields = arrayOf(isSucceededField)) private val open = GROUP.registerEvent("wizard.dialog.open", sessionIdField) private val screen = GROUP.registerEvent("screen", sessionIdField, screenNumField) private val next = GROUP.registerEvent("navigate.next", sessionIdField, inputMaskField) private val prev = GROUP.registerEvent("navigate.prev", sessionIdField, inputMaskField) private val projectCreated = GROUP.registerEvent("project.created", sessionIdField) private val search = GROUP.registerEvent("search", sessionIdField, typedCharsField, hitsField) private val generator = GROUP.registerEvent("search", sessionIdField, generatorTypeField) private val location = GROUP.registerEvent("project.location.changed", sessionIdField, generatorTypeField) private val name = GROUP.registerEvent("project.name.changed", sessionIdField, generatorTypeField) private val languageSelected = GROUP.registerEvent("select.language", sessionIdField, languageField) private val gitChanged = GROUP.registerEvent("git.changed", sessionIdField) private val templateSelected = GROUP.registerEvent("select.custom.template", sessionIdField) private val helpNavigation = GROUP.registerEvent("navigate.help", sessionIdField) //finish events private val gitFinish = GROUP.registerEvent("create.git.repo", sessionIdField, gitField) private val generatorFinished = GROUP.registerEvent("generator.finished", sessionIdField, generatorTypeField) private val languageFinished = GROUP.registerEvent("language.finished", sessionIdField, languageField) //logs @JvmStatic fun logStarted(project: Project?) = activity.started(project) @JvmStatic fun logScreen(context: WizardContext, screenNumber: Int) = screen.log(context.project, context.sessionId.id, screenNumber) @JvmStatic fun logOpen(context: WizardContext) = open.log(context.project, context.sessionId.id) @JvmStatic fun logSearchChanged(context: WizardContext, chars: Int, results: Int) = search.log(context.project, context.sessionId.id, min(chars, 10), results) @JvmStatic fun logLocationChanged(context: WizardContext, generator: Class<*>) = location.log(context.project, context.sessionId.id, generator) @JvmStatic fun logNameChanged(context: WizardContext, generator: Class<*>) = name.log(context.project, context.sessionId.id, generator) @JvmStatic fun logLanguageChanged(context: WizardContext, language: String) = languageSelected.log(context.project, context.sessionId.id, language) @JvmStatic fun logGitChanged(context: WizardContext) = gitChanged.log(context.project, context.sessionId.id) @JvmStatic fun logGeneratorSelected(context: WizardContext, title: Class<*>) = generator.log(context.project, context.sessionId.id, title) @JvmStatic fun logCustomTemplateSelected(context: WizardContext) = templateSelected.log(context.project, context.sessionId.id) @JvmStatic fun logNext(context: WizardContext, inputMask: Long = -1) = next.log(context.project, context.sessionId.id, inputMask) @JvmStatic fun logPrev(context: WizardContext, inputMask: Long = -1) = prev.log(context.project, context.sessionId.id, inputMask) @JvmStatic fun logHelpNavigation(context: WizardContext) = helpNavigation.log(context.project, context.sessionId.id) //finish @JvmStatic fun logFinished(activity: StructuredIdeActivity, success: Boolean) = activity.finished { listOf(isSucceededField with success)} @JvmStatic fun logProjectCreated(project: Project?, context: WizardContext) = projectCreated.log(project, context.sessionId.id) @JvmStatic fun logLanguageFinished(context: WizardContext, language: String) = languageFinished.log(context.project, context.sessionId.id, language) @JvmStatic fun logGitFinished(context: WizardContext, git: Boolean) = gitFinish.log(context.project, context.sessionId.id, git) @JvmStatic fun logGeneratorFinished(context: WizardContext, generator: Class<*>) = generatorFinished.log(context.project, context.sessionId.id, generator) } open class BuildSystemCollector(buildSystemList: List<String>) { private val buildSystemField = BuildSystemField(buildSystemList) private val buildSystem = GROUP.registerEvent("select.build.system", sessionIdField, buildSystemField) private class BuildSystemField(buildSystemList: List<String>) : StringEventField("build_system") { override val validationRule: List<String> = buildSystemList } fun logBuildSystemChanged(context: WizardContext, name: String) = buildSystem.log(context.project, context.sessionId.id, name) } }
platform/platform-impl/src/com/intellij/ide/projectWizard/NewProjectWizardCollector.kt
911781146
/* * Copyright 1999-2017 Alibaba Group. * * 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.alibaba.smartfox.eclipse.ui import com.alibaba.smartfox.eclipse.pmd.RulePriority import com.alibaba.smartfox.eclipse.util.MarkerUtil import org.eclipse.core.resources.IFile import org.eclipse.core.resources.IMarker /** * * * @author caikang * @date 2017/06/13 */ object InspectionResults { private val fileViolations = linkedMapOf<IFile, List<MarkerViolation>>() var contentDescription = "" val errors: List<LevelViolations> get() { val result = toLevelViolationList(fileViolations.values.flatten()) contentDescription = getContentDescription(result) return result } lateinit var view: InspectionResultView fun clear() { fileViolations.forEach { MarkerUtil.removeAllMarkers(it.key) } fileViolations.clear() // update contentDescription errors } private fun toLevelViolationList(markers: Collection<MarkerViolation>): List<LevelViolations> { return markers.groupBy { it.violation.rule.priority.priority }.mapValues { it.value.groupBy { it.violation.rule.name }.mapValues { it.value.groupBy { it.marker.resource as IFile }.map { FileMarkers(it.key, it.value) } }.map { RuleViolations(it.key, it.value) } }.toSortedMap().map { val level = RulePriority.valueOf(it.key).title LevelViolations(level, it.value) } } fun updateFileViolations(file: IFile, markers: List<MarkerViolation>) { if (markers.isEmpty()) { fileViolations.remove(file) } else { fileViolations[file] = markers } view.refreshView(this) } fun removeMarker(marker: IMarker) { val file = marker.resource as IFile val list = fileViolations[file] ?: return val result = list.filter { it.marker != marker } fileViolations[file] = result marker.delete() view.refreshView(this) } fun getContentDescription(errors: List<LevelViolations>): String { val map = errors.associateBy { it.level } return "${map[RulePriority.Blocker.title]?.count ?: 0} Blockers," + "${map[RulePriority.Critical.title]?.count ?: 0} Criticals," + "${map[RulePriority.Major.title]?.count ?: 0} Majors" } }
eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResults.kt
3254980795
package technology.mainthread.apps.gatekeeper.data const val PARTICLE_AUTH = "particle_auth" const val PARTICLE_DEVICE = "particle_device" const val APP_VERSION = "app_version"
mobile/src/main/java/technology/mainthread/apps/gatekeeper/data/RemoteConfigKeys.kt
682776749
package ftl.ios.xctest import com.google.common.truth.Truth.assertThat import flank.common.isWindows import ftl.ios.xctest.common.parseToNSDictionary import org.junit.Assume.assumeFalse import org.junit.Test import java.io.File class FindXcTestNamesV1KtTest { @Test fun findTestNames() { assumeFalse(isWindows) // given val xctestrun = File(swiftXcTestRunV1) // when val names = findXcTestNamesV1( xcTestRoot = xctestrun.parent + "/", xcTestNsDictionary = parseToNSDictionary(xctestrun) ) .flatMap { it.value } .sorted() // then assertThat(swiftTestsV1).isEqualTo(names) } }
test_runner/src/test/kotlin/ftl/ios/xctest/FindXcTestNamesV1KtTest.kt
3001584650
package uy.kohesive.iac.model.aws.contexts import com.amazonaws.services.pinpoint.AmazonPinpoint import com.amazonaws.services.pinpoint.model.* import uy.kohesive.iac.model.aws.IacContext import uy.kohesive.iac.model.aws.KohesiveIdentifiable import uy.kohesive.iac.model.aws.utils.DslScope interface PinpointIdentifiable : KohesiveIdentifiable { } interface PinpointEnabled : PinpointIdentifiable { val pinpointClient: AmazonPinpoint val pinpointContext: PinpointContext fun <T> withPinpointContext(init: PinpointContext.(AmazonPinpoint) -> T): T = pinpointContext.init(pinpointClient) } open class BasePinpointContext(protected val context: IacContext) : PinpointEnabled by context { } @DslScope class PinpointContext(context: IacContext) : BasePinpointContext(context) { }
model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/contexts/Pinpoint.kt
1902409405
package com.kickstarter.viewmodels import com.kickstarter.libs.ActivityViewModel import com.kickstarter.libs.Environment import com.kickstarter.libs.rx.transformers.Transformers.errors import com.kickstarter.libs.rx.transformers.Transformers.values import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.models.Category import com.kickstarter.services.DiscoveryParams import com.kickstarter.ui.IntentKey import com.kickstarter.ui.activities.EditorialActivity import com.kickstarter.ui.data.Editorial import rx.Notification import rx.Observable import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject interface EditorialViewModel { interface Inputs { /** Call when the user clicks the retry container. */ fun retryContainerClicked() } interface Outputs { /** Emits the @StringRes ID of the description of the [Editorial]. */ fun description(): Observable<Int> /** Emits the [DiscoveryParams] for the tag of the [Editorial]. */ fun discoveryParams(): Observable<DiscoveryParams> /** Emits the @DrawableRes of the graphic of the [Editorial]. */ fun graphic(): Observable<Int> /** Emits when we should refresh the [com.kickstarter.ui.fragments.DiscoveryFragment]. */ fun refreshDiscoveryFragment(): Observable<Void> /** Emits a [Boolean] determining if the retry container should be visible. */ fun retryContainerIsGone(): Observable<Boolean> /** Emits a list of root [Category]s. */ fun rootCategories(): Observable<List<Category>> /** Emits the @StringRes ID of the title of the [Editorial]. */ fun title(): Observable<Int> } class ViewModel(val environment: Environment) : ActivityViewModel<EditorialActivity>(environment), Inputs, Outputs { private val retryContainerClicked: PublishSubject<Void> = PublishSubject.create() private val description: BehaviorSubject<Int> = BehaviorSubject.create() private val discoveryParams: BehaviorSubject<DiscoveryParams> = BehaviorSubject.create() private val graphic: BehaviorSubject<Int> = BehaviorSubject.create() private val refreshDiscoveryFragment: PublishSubject<Void> = PublishSubject.create() private val retryContainerIsGone: BehaviorSubject<Boolean> = BehaviorSubject.create() private val rootCategories: BehaviorSubject<List<Category>> = BehaviorSubject.create() private val title: BehaviorSubject<Int> = BehaviorSubject.create() private val apolloClient = requireNotNull(environment.apolloClient()) val inputs: Inputs = this val outputs: Outputs = this init { val editorial = intent() .map { it.getSerializableExtra(IntentKey.EDITORIAL) } .filter { ObjectUtils.isNotNull(it) } .ofType(Editorial::class.java) val categoriesNotification = Observable.merge(fetchCategories(), this.retryContainerClicked.switchMap { fetchCategories() }) categoriesNotification .compose(values()) .map { it.filter { category -> category.isRoot } } .map { it.sorted() } .compose(bindToLifecycle()) .subscribe { this.rootCategories.onNext(it) } categoriesNotification .compose(errors()) .compose(bindToLifecycle()) .subscribe { this.retryContainerIsGone.onNext(false) } editorial .map { it.tagId } .map { DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).tagId(it).build() } .compose(bindToLifecycle()) .subscribe(this.discoveryParams) editorial .map { it.graphic } .compose(bindToLifecycle()) .subscribe(this.graphic) editorial .map { it.title } .compose(bindToLifecycle()) .subscribe(this.title) editorial .map { it.description } .compose(bindToLifecycle()) .subscribe(this.description) this.retryContainerClicked .compose(bindToLifecycle()) .subscribe(this.refreshDiscoveryFragment) } private fun fetchCategories(): Observable<Notification<List<Category>>>? { return this.apolloClient.fetchCategories() .doOnSubscribe { this.retryContainerIsGone.onNext(true) } .materialize() .share() } override fun retryContainerClicked() = this.retryContainerClicked.onNext(null) override fun description(): Observable<Int> = this.description override fun discoveryParams(): Observable<DiscoveryParams> = this.discoveryParams override fun graphic(): Observable<Int> = this.graphic override fun refreshDiscoveryFragment(): Observable<Void> = this.refreshDiscoveryFragment override fun retryContainerIsGone(): Observable<Boolean> = this.retryContainerIsGone override fun rootCategories(): Observable<List<Category>> = this.rootCategories override fun title(): Observable<Int> = this.title } }
app/src/main/java/com/kickstarter/viewmodels/EditorialViewModel.kt
2901254436
package eu.corvus.essentials.core import android.app.Activity import android.app.Application import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Looper import org.jetbrains.anko.AnkoLogger import timber.log.Timber import java.util.concurrent.Executors /** * Created by Vlad Cazacu on 10/4/2016. */ abstract class BaseApplication : Application(), Application.ActivityLifecycleCallbacks, AnkoLogger { val activityStack = mutableMapOf<Class<out Activity>, ActivityInfo>() var topActivity: Activity? = null override fun onCreate() { super.onCreate() appContext = this threads = provideThreads() registerActivityLifecycleCallbacks(this) Dispatcher.initialize(this) Preferences.initialize(this) configureTimber() initialize() } private fun provideThreads(): Threads { val execService = Executors.newFixedThreadPool(getNumberOfCores()) val scheduleService = Executors.newScheduledThreadPool(getNumberOfCores()) return Threads(execService, scheduleService, Handler(Looper.getMainLooper())) } /** * Override this in production! */ fun configureTimber() { Timber.plant(Timber.DebugTree()) } abstract fun initialize() // initialize override fun onActivityStarted(activity: Activity) { } override fun onActivityPaused(activity: Activity) { changeState(activity, ActivityState.Paused) } override fun onActivityResumed(activity: Activity) { changeState(activity, ActivityState.Active) } override fun onActivityStopped(activity: Activity) { changeState(activity, ActivityState.Stopped) } override fun onActivityCreated(activity: Activity, bundle: Bundle?) { changeState(activity, ActivityState.Created) } override fun onActivityDestroyed(activity: Activity) { changeState(activity, ActivityState.Destroyed) if(activityStack.isEmpty()) { MemoryStorage.onNoActivity() } } override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle?) = Unit private fun changeState(activity: Activity, activityState: ActivityState) { val activityInfo = when(activityState) { ActivityState.Created -> { val activityInfo = ActivityInfo(activity.javaClass, activity, activityState) activityStack.put(activity.javaClass, activityInfo) topActivity = activity activityInfo } ActivityState.Destroyed -> activityStack.remove(activity.javaClass) else -> activityStack[activity.javaClass] } activityInfo ?: return activityInfo.activityState = activityState if(activityState == ActivityState.Active) topActivity = activity if(currentActivity() == null) Dispatcher.sendBroadcast(Intent(AppBackground)) else Dispatcher.sendBroadcast(Intent(AppForeground)) } fun currentActivity(): Activity? { var currentActivity: Activity? = null activityStack.forEach { val value = it.value if (value.activityState == ActivityState.Active) currentActivity = value.activity } return currentActivity } fun clearTop() { activityStack.clear() } enum class ActivityState { Active, Paused, Stopped, Created, Destroyed } data class ActivityInfo(val type: Class<out Activity>, var activity: Activity, var activityState: ActivityState) override fun onTerminate() { super.onTerminate() threads.terminate() } }
app/src/main/java/eu/corvus/essentials/core/BaseApplication.kt
3862208252
/* * Copyright (c) 2017. Rei Matsushita * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package me.rei_m.hbfavmaterial.presentation.widget.fragment interface MainPageFragment { val pageIndex: Int val pageTitle: String }
app/src/main/kotlin/me/rei_m/hbfavmaterial/presentation/widget/fragment/MainPageFragment.kt
1093729276
val a = """ | blah blah blah | blah blah blah | blah blah blah<caret> """ //----- val a = """ | blah blah blah | blah blah blah | blah blah blah | <caret> """
plugins/kotlin/idea/tests/testData/editor/enterHandler/multilineString/withTabs/tabs2/enterMLSimpleMargin.kt
1798783393
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.util.registry import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.editor.impl.TabCharacterPaintMode import com.intellij.openapi.options.advanced.AdvancedSettingBean import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity class RegistryToAdvancedSettingsMigration : StartupActivity.DumbAware { override fun runActivity(project: Project) { val propertyName = "registry.to.advanced.settings.migration.build" val lastMigratedVersion = PropertiesComponent.getInstance().getValue(propertyName) val currentVersion = ApplicationInfo.getInstance().build.asString() if (currentVersion != lastMigratedVersion) { val userProperties = Registry.getInstance().userProperties for (setting in AdvancedSettingBean.EP_NAME.extensions) { if (setting.id == "editor.tab.painting") { migrateEditorTabPainting(userProperties, setting) continue } if (setting.id == "vcs.process.ignored") { migrateVcsIgnoreProcessing(userProperties, setting) continue } val userProperty = userProperties[setting.id] ?: continue try { AdvancedSettings.getInstance().setSetting(setting.id, setting.valueFromString(userProperty), setting.type()) userProperties.remove(setting.id) } catch (e: IllegalArgumentException) { continue } } PropertiesComponent.getInstance().setValue(propertyName, currentVersion) } } private fun migrateEditorTabPainting(userProperties: MutableMap<String, String>, setting: AdvancedSettingBean) { val mode = if (userProperties["editor.old.tab.painting"] == "true") { userProperties.remove("editor.old.tab.painting") TabCharacterPaintMode.LONG_ARROW } else if (userProperties["editor.arrow.tab.painting"] == "true") { userProperties.remove("editor.arrow.tab.painting") TabCharacterPaintMode.ARROW } else { return } AdvancedSettings.getInstance().setSetting(setting.id, mode, setting.type()) } private fun migrateVcsIgnoreProcessing(userProperties: MutableMap<String, String>, setting: AdvancedSettingBean) { if (userProperties["git.process.ignored"] == "false") { userProperties.remove("git.process.ignored") } else if (userProperties["hg4idea.process.ignored"] == "false") { userProperties.remove("hg4idea.process.ignored") } else if (userProperties["p4.process.ignored"] == "false") { userProperties.remove("p4.process.ignored") } else { return } AdvancedSettings.getInstance().setSetting(setting.id, false, setting.type()) } }
platform/platform-impl/src/com/intellij/openapi/util/registry/RegistryToAdvancedSettingsMigration.kt
2268725659
// WITH_RUNTIME /** * Contains [kotlin.collections.Collecti<caret>on] */ class C { } // REF: (kotlin.collections).Collection
plugins/kotlin/idea/tests/testData/kdoc/resolve/QualifiedNameReference.kt
3868429743
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl.content import com.intellij.CommonBundle import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import com.intellij.ide.actions.PinActiveTabAction import com.intellij.ide.impl.DataManagerImpl import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.JBPopupMenu import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.openapi.util.* import com.intellij.openapi.wm.ex.ToolWindowEx import com.intellij.toolWindow.InternalDecoratorImpl import com.intellij.ui.ExperimentalUI.isNewUI import com.intellij.ui.MouseDragHelper import com.intellij.ui.PopupHandler import com.intellij.ui.awt.RelativePoint import com.intellij.ui.components.panels.HorizontalLayout import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.content.AlertIcon import com.intellij.ui.content.Content import com.intellij.ui.content.ContentManager import com.intellij.ui.content.impl.ContentManagerImpl import com.intellij.ui.tabs.* import com.intellij.ui.tabs.impl.JBTabsImpl import com.intellij.ui.tabs.impl.MorePopupAware import com.intellij.ui.tabs.impl.TabLabel import com.intellij.util.castSafelyTo import com.intellij.util.containers.ContainerUtil import com.intellij.util.ui.AbstractLayoutManager import com.intellij.util.ui.UIUtil import java.awt.* import java.awt.event.* import java.beans.PropertyChangeEvent import java.beans.PropertyChangeListener import java.beans.PropertyChangeSupport import javax.swing.Icon import javax.swing.JComponent import javax.swing.SwingUtilities /** * Tool window header that shows tabs and actions from its content. * * If toolwindow [Content] returns [SingleContentSupplier] as a data provider * via [SingleContentSupplier.KEY] that in case of single content view * all [JBTabs] and actions are moved into this header. * * When two or more contents exist then header looks like [TabContentLayout]. */ internal class SingleContentLayout( ui: ToolWindowContentUi ) : TabContentLayout(ui) { private var isSingleContentView: Boolean = false private var tabAdapter: TabAdapter? = null private val toolbars = mutableMapOf<ToolbarType, ActionToolbar>() private var wrapper: JComponent? = null override fun update() { super.update() tryUpdateContentView() } override fun rebuild() { super.rebuild() tryUpdateContentView() } private fun Content.getSupplier(): SingleContentSupplier? { return (component as? DataProvider)?.let(SingleContentSupplier.KEY::getData) } private fun getSingleContentOrNull(): Content? { return findTopLevelContentManager()?.contentsRecursively?.singleOrNull() } private fun findTopLevelContentManager(): ContentManagerImpl? { return InternalDecoratorImpl.findTopLevelDecorator(ui.component)?.contentManager as? ContentManagerImpl } private fun tryUpdateContentView() { val currentContent = getSingleContentOrNull() val contentSupplier = currentContent?.getSupplier() if (contentSupplier != null) { if (isSingleContentView) { updateSingleContentView(currentContent, contentSupplier) } else { initSingleContentView(currentContent, contentSupplier) } } else if (isSingleContentView) { resetSingleContentView() } val toolwindow = ui.getWindow().castSafelyTo<ToolWindowEx>() if (toolwindow != null) { val group = toolwindow.decoration?.actionGroup if (isSingleContentView) { // install extra actions if (group !is ExtendedTitleActionsGroup) { toolwindow.setAdditionalGearActions(ExtendedTitleActionsGroup( group, PinActiveTabAction(), Separator.create() )) } } else { // restore user's group if (group is ExtendedTitleActionsGroup) { toolwindow.setAdditionalGearActions(group.originActions) } } } } private fun initSingleContentView(content: Content, supplier: SingleContentSupplier) { tabAdapter = TabAdapter(content, supplier.getTabs(), tabPainter, ui).also { Disposer.register(content, it) ui.tabComponent.add(it) } assert(toolbars.isEmpty()) supplier.getToolbarActions()?.let { mainActionGroup -> toolbars[ToolbarType.MAIN] = createToolbar( supplier.getMainToolbarPlace(), mainActionGroup, content.component ) } let { val contentActions = DefaultActionGroup() contentActions.add(CloseCurrentContentAction()) contentActions.add(Separator.create()) contentActions.addAll(supplier.getContentActions()) contentActions.add(MyInvisibleAction()) toolbars[ToolbarType.CLOSE_GROUP] = createToolbar( supplier.getContentToolbarPlace(), contentActions, content.component ).apply { setReservePlaceAutoPopupIcon(false) layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY } } toolbars.forEach { (_, toolbar) -> ui.tabComponent.add(toolbar.component) } wrapper = NonOpaquePanel(HorizontalLayout(0)).also { MyRedispatchMouseEventListener { e -> // extra actions are registered in ToolWindowContentUi#initMouseListeners if (SwingUtilities.isLeftMouseButton(e)) { ui.tabComponent.parent?.let { westPanel -> westPanel.dispatchEvent(SwingUtilities.convertMouseEvent(e.component, e, westPanel)) } } }.installOn(it) MouseDragHelper.setComponentDraggable(it, true) ToolWindowContentUi.initMouseListeners(it, ui, true) ui.tabComponent.add(it) } isSingleContentView = true supplier.init(toolbars[ToolbarType.MAIN], toolbars[ToolbarType.CLOSE_GROUP]) supplier.customize(wrapper) } private fun updateSingleContentView(content: Content, supplier: SingleContentSupplier) { if (tabAdapter?.jbTabs != supplier.getTabs()) { // in case of 'reusing content' just revoke old view and create new one resetSingleContentView() initSingleContentView(content, supplier) } else { toolbars.forEach { (_, toolbar) -> toolbar.updateActionsImmediately() } supplier.customize(wrapper) ui.tabComponent.repaint() } } private fun resetSingleContentView() { val adapter = tabAdapter ?: error("Adapter must not be null") tabAdapter = null ui.tabComponent.remove(adapter) Disposer.dispose(adapter) toolbars.values.forEach { ui.tabComponent.remove(it.component) } toolbars.clear() ui.tabComponent.remove(wrapper ?: error("Wrapper must not be null")) wrapper = null isSingleContentView = false adapter.content.getSupplier()?.reset() } private fun createToolbar(place: String, group: ActionGroup, target: JComponent? = null): ActionToolbar { val toolbar = ActionManager.getInstance().createActionToolbar(place, group, true) toolbar.setTargetComponent(target) toolbar.component.isOpaque = false return toolbar } override fun isToDrawTabs(): TabsDrawMode { return if (isSingleContentView) TabsDrawMode.HIDE else super.isToDrawTabs() } override fun layout() { super.layout() if (isSingleContentView) { val component = ui.tabComponent component.bounds = component.bounds.apply { width = component.parent.width } val labelWidth = idLabel.x + idLabel.preferredSize.width var tabsWidth = tabAdapter?.preferredSize?.width ?: 0 var mainToolbarWidth = toolbars[ToolbarType.MAIN]?.component?.preferredSize?.width ?: 0 val contentToolbarWidth = toolbars[ToolbarType.CLOSE_GROUP]?.component?.preferredSize?.width ?: 0 val minTabWidth = tabAdapter?.minimumSize?.width ?: 0 val fixedWidth = labelWidth + mainToolbarWidth + contentToolbarWidth val freeWidth = component.bounds.width - fixedWidth if (freeWidth < minTabWidth) { mainToolbarWidth += freeWidth - minTabWidth } tabsWidth = maxOf(minTabWidth, minOf(freeWidth, tabsWidth)) val wrapperWidth = maxOf(0, freeWidth - tabsWidth) var x = labelWidth tabAdapter?.apply { bounds = Rectangle(x, 0, tabsWidth, component.height) x += tabsWidth } toolbars[ToolbarType.MAIN]?.component?.apply { val height = preferredSize.height bounds = Rectangle(x, (component.height - height) / 2, mainToolbarWidth, height) x += mainToolbarWidth } wrapper?.apply { bounds = Rectangle(x, 0, wrapperWidth, component.height) x += wrapperWidth } toolbars[ToolbarType.CLOSE_GROUP]?.component?.apply { val height = preferredSize.height bounds = Rectangle(x, (component.height - height) / 2, contentToolbarWidth, height) x += contentToolbarWidth } } } override fun updateIdLabel(label: BaseLabel) { super.updateIdLabel(label) if (!isSingleContentView) { label.icon = null label.toolTipText = null } else if (tabs.size == 1) { label.icon = tabs[0].content.icon val displayName = tabs[0].content.displayName label.text = createProcessName( prefix = ui.window.stripeTitle, title = displayName ) label.toolTipText = displayName } } @NlsSafe private fun createProcessName(title: String, prefix: String? = null) = prefix?.let { if (isNewUI()) it else "$it:" } ?: title private inner class TabAdapter( val content: Content, val jbTabs: JBTabs, val tabPainter: JBTabPainter, val twcui: ToolWindowContentUi ) : NonOpaquePanel(), TabsListener, PropertyChangeListener, DataProvider, MorePopupAware, Disposable { private val labels = mutableListOf<MyContentTabLabel>() private val popupToolbar: JComponent private val popupHandler = object : PopupHandler() { override fun invokePopup(comp: Component, x: Int, y: Int) = showPopup(comp, x, y) } private val closeHandler = object : MouseAdapter() { override fun mouseReleased(e: MouseEvent) { if (UIUtil.isCloseClick(e, MouseEvent.MOUSE_RELEASED)) { val tabLabel = e.component as? MyContentTabLabel if (tabLabel != null && tabLabel.content.isCloseable) { tabLabel?.closeContent() } } } } private val containerListener = object : ContainerListener { override fun componentAdded(e: ContainerEvent) = update(e) override fun componentRemoved(e: ContainerEvent) = update(e) private fun update(e: ContainerEvent) { if (e.child is TabLabel) { checkAndUpdate() } } } init { updateTabs() jbTabs.addListener(object : TabsListener { override fun selectionChanged(oldSelection: TabInfo?, newSelection: TabInfo?) = checkAndUpdate() override fun tabRemoved(tabToRemove: TabInfo) = checkAndUpdate() override fun tabsMoved() = checkAndUpdate() }, this) jbTabs.component.addContainerListener(containerListener) val tabList = ActionManager.getInstance().getAction("TabList") val tabListGroup = DefaultActionGroup(tabList, Separator.create(), MyInvisibleAction()) popupToolbar = createToolbar(ActionPlaces.TOOLWINDOW_POPUP, tabListGroup, this).apply { setReservePlaceAutoPopupIcon(false) layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY }.component layout = HorizontalTabLayoutWithHiddenControl { labels.find { it.content.info == jbTabs.selectedInfo } } add(popupToolbar, HorizontalTabLayoutWithHiddenControl.CONTROL) } private fun retrieveInfo(label: MyContentTabLabel): TabInfo { return label.content.info } private fun checkAndUpdate() { val currentContent = getSingleContentOrNull() val currentSupplier = currentContent?.getSupplier() val src = currentSupplier?.getTabs()?.tabs ?: return val dst = labels.map(::retrieveInfo) if (!ContainerUtil.equalsIdentity(src, dst)) { updateTabs() } updateSingleContentView(currentContent, currentSupplier) updateLabels(labels) revalidate() } fun updateTabs() { labels.removeAll { retrieveInfo(it).changeSupport.removePropertyChangeListener(this) remove(it) true } val supplier = getSingleContentOrNull()?.getSupplier() ?: return if (jbTabs.tabs.size > 1) { labels.addAll(jbTabs.tabs.map { info -> info.changeSupport.addPropertyChangeListener(this) MyContentTabLabel(FakeContent(supplier, info), this@SingleContentLayout).apply { addMouseListener(closeHandler) } }) labels.forEach(::add) } updateLabels(labels) } fun updateLabels(labels: List<MyContentTabLabel>) { labels.associateBy { it.content.info }.forEach(::copyValues) } override fun dispose() { labels.forEach { retrieveInfo(it).changeSupport.removePropertyChangeListener(this) } jbTabs.component.removeContainerListener(containerListener) } override fun getMinimumSize(): Dimension { if (isMinimumSizeSet) { return super.getMinimumSize() } val minWidth = if (labels.isEmpty()) 0 else popupToolbar.preferredSize.width return Dimension(minWidth, 0) } fun copyValues(from: TabInfo, to: ContentLabel) { to.icon = from.icon to.text = from.text } fun showPopup(component: Component, x: Int, y: Int) { // ViewContext.CONTENT_KEY val info = ((component as? ContentTabLabel)?.content as? FakeContent)?.info if (info == null) { logger<SingleContentLayout>().warn("Cannot resolve label popup component. Event will be ignored") return } val supplier = getSingleContentOrNull()?.getSupplier() val toShow = getPopupMenu(supplier?.getTabs()) ?: return toShow.setTargetComponent(component) JBPopupMenu.showAt(RelativePoint(component, Point(x, y)), toShow.component) } private fun getPopupMenu(tabs: JBTabs?): ActionPopupMenu? { val jbTabsImpl = tabs as? JBTabsImpl ?: return null val popup = jbTabsImpl.popupGroup ?: return null val popupPlace = jbTabsImpl.popupPlace ?: ActionPlaces.UNKNOWN val group = DefaultActionGroup() group.addAll(popup) group.addSeparator() group.addAll(jbTabsImpl.navigationActions) return ActionManager.getInstance().createActionPopupMenu(popupPlace, group) } override fun paintComponent(g: Graphics) { if (g is Graphics2D) { labels.forEach { comp -> val labelBounds = comp.bounds if (jbTabs.selectedInfo == retrieveInfo(comp)) { tabPainter.paintSelectedTab(JBTabsPosition.top, g, labelBounds, 1, null, twcui.window.isActive, comp.isHovered) } else { tabPainter.paintTab(JBTabsPosition.top, g, labelBounds, 1, null, twcui.window.isActive, comp.isHovered) } } } super.paintComponent(g) } override fun propertyChange(evt: PropertyChangeEvent) { val source = evt.source as? TabInfo ?: error("Bad event source") val label = labels.find { it.content.info == source } ?: error("Cannot find label for $source") copyValues(source, label) } private inner class MyContentTabLabel(content: FakeContent, layout: TabContentLayout) : ContentTabLabel(content, layout), DataProvider { init { addMouseListener(popupHandler) } override fun selectContent() { retrieveInfo(this).let { jbTabs.select(it, true) } } public override fun closeContent() { retrieveInfo(this).let { info -> getSingleContentOrNull()?.getSupplier()?.close(info) } } override fun getData(dataId: String): Any? { if (JBTabsEx.NAVIGATION_ACTIONS_KEY.`is`(dataId)) { return jbTabs } return DataManagerImpl.getDataProviderEx(retrieveInfo(this).component)?.getData(dataId) } override fun getContent(): FakeContent { return super.getContent() as FakeContent } } override fun getData(dataId: String): Any? { if (MorePopupAware.KEY.`is`(dataId)) { return this } return null } override fun canShowMorePopup(): Boolean { return true } override fun showMorePopup() { val contentToShow = labels .filter { it.bounds.width <= 0 } .map(MyContentTabLabel::getContent) val step = object : BaseListPopupStep<FakeContent>(null, contentToShow) { override fun onChosen(selectedValue: FakeContent, finalChoice: Boolean): PopupStep<*>? { jbTabs.select(selectedValue.info, true) return FINAL_CHOICE } override fun getIconFor(value: FakeContent) = value.icon override fun getTextFor(value: FakeContent) = value.displayName } JBPopupFactory.getInstance() .createListPopup(step) .show(RelativePoint.getSouthWestOf(popupToolbar)) } } private class ExtendedTitleActionsGroup( val originActions: ActionGroup?, vararg extendedActions: AnAction ) : DefaultActionGroup() { init { extendedActions.forEach(::add) originActions?.let(::addAll) } } private inner class CloseCurrentContentAction : DumbAwareAction(CommonBundle.messagePointer("action.close"), AllIcons.Actions.Cancel) { override fun actionPerformed(e: AnActionEvent) { val content = getSingleContentOrNull() if (content != null && content.isPinned) { content.isPinned = false } else { content?.let { it.manager?.removeContent(it, true) } } } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = getSingleContentOrNull()?.isCloseable == true if (isPinned()) { e.presentation.icon = AllIcons.General.Pin_tab e.presentation.text = IdeBundle.message("action.unpin.tab") } else { e.presentation.icon = AllIcons.Actions.Cancel e.presentation.text = CommonBundle.message("action.close") } } private fun isPinned(): Boolean { return getSingleContentOrNull()?.isPinned == true } } /** * The minimal [Content] implementation. * * Is used only to pass as an argument to support [SingleContentLayout.TabAdapter.MyContentTabLabel]. * * All unused methods throw [IllegalStateException]. */ private class FakeContent(val supplier: SingleContentSupplier, val info: TabInfo) : Content { private val pcs = PropertyChangeSupport(this) override fun addPropertyChangeListener(l: PropertyChangeListener?) { pcs.addPropertyChangeListener(l) } override fun removePropertyChangeListener(l: PropertyChangeListener?) { pcs.removePropertyChangeListener(l) } override fun isSelected(): Boolean { return supplier.getTabs().selectedInfo == info } override fun isCloseable(): Boolean { return supplier.isClosable(info) } override fun isPinned(): Boolean { return false } override fun getManager(): ContentManager? { return null } override fun getIcon(): Icon? { return info.icon } @NlsSafe override fun getDisplayName(): String { return info.text } override fun <T : Any?> getUserData(key: Key<T>): T? { error("An operation is not supported") } override fun <T : Any?> putUserData(key: Key<T>, value: T?) { error("An operation is not supported") } override fun dispose() { error("An operation is not supported") } override fun getComponent(): JComponent { error("An operation is not supported") } override fun getPreferredFocusableComponent(): JComponent? { error("An operation is not supported") } override fun setComponent(component: JComponent?) { error("An operation is not supported") } override fun setPreferredFocusableComponent(component: JComponent?) { error("An operation is not supported") } override fun setPreferredFocusedComponent(computable: Computable<out JComponent>?) { error("An operation is not supported") } override fun setIcon(icon: Icon?) { error("An operation is not supported") } override fun setDisplayName(displayName: String?) { error("An operation is not supported") } override fun setTabName(tabName: String?) { error("An operation is not supported") } override fun getTabName(): String { error("An operation is not supported") } override fun getToolwindowTitle(): String { error("An operation is not supported") } override fun setToolwindowTitle(toolwindowTitle: String?) { error("An operation is not supported") } override fun getDisposer(): Disposable? { error("An operation is not supported") } override fun setDisposer(disposer: Disposable) { error("An operation is not supported") } override fun setShouldDisposeContent(value: Boolean) { error("An operation is not supported") } override fun getDescription(): String? { error("An operation is not supported") } override fun setDescription(description: String?) { error("An operation is not supported") } override fun release() { error("An operation is not supported") } override fun isValid(): Boolean { error("An operation is not supported") } override fun setPinned(locked: Boolean) { error("An operation is not supported") } override fun setPinnable(pinnable: Boolean) { error("An operation is not supported") } override fun isPinnable(): Boolean { error("An operation is not supported") } override fun setCloseable(closeable: Boolean) { error("An operation is not supported") } override fun setActions(actions: ActionGroup?, place: String?, contextComponent: JComponent?) { error("An operation is not supported") } override fun getActions(): ActionGroup? { error("An operation is not supported") } override fun setSearchComponent(comp: JComponent?) { error("An operation is not supported") } override fun getSearchComponent(): JComponent? { error("An operation is not supported") } override fun getPlace(): String { error("An operation is not supported") } override fun getActionsContextComponent(): JComponent? { error("An operation is not supported") } override fun setAlertIcon(icon: AlertIcon?) { error("An operation is not supported") } override fun getAlertIcon(): AlertIcon? { error("An operation is not supported") } override fun fireAlert() { error("An operation is not supported") } override fun getBusyObject(): BusyObject? { error("An operation is not supported") } override fun setBusyObject(`object`: BusyObject?) { error("An operation is not supported") } override fun getSeparator(): String { error("An operation is not supported") } override fun setSeparator(separator: String?) { error("An operation is not supported") } override fun setPopupIcon(icon: Icon?) { error("An operation is not supported") } override fun getPopupIcon(): Icon? { error("An operation is not supported") } override fun setExecutionId(executionId: Long) { error("An operation is not supported") } override fun getExecutionId(): Long { error("An operation is not supported") } } private class HorizontalTabLayoutWithHiddenControl( val selected: () -> JComponent? ) : AbstractLayoutManager() { private var control: Component? = null override fun addLayoutComponent(comp: Component?, constraints: Any?) { if (constraints == CONTROL) { assert(control == null) { "Cannot add a second control component" } control = comp } super.addLayoutComponent(comp, constraints) } override fun removeLayoutComponent(comp: Component?) { if (control === comp) { control = null } super.removeLayoutComponent(comp) } override fun preferredLayoutSize(parent: Container): Dimension { return parent.components.asSequence() .filterNot { it === control } .map { it.preferredSize } .fold(Dimension()) { acc, size -> acc.apply { width += size.width height = maxOf(acc.height, size.height, parent.height) } } } override fun layoutContainer(parent: Container) { var eachX = 0 val canFitAllComponents = parent.preferredSize.width <= parent.bounds.width val children = parent.components.asSequence().filterNot { it === control } if (canFitAllComponents) { children.forEach { val dim = it.preferredSize it.bounds = Rectangle(eachX, 0, dim.width, parent.height) eachX += dim.width } control?.bounds = Rectangle(0, 0, 0, 0) } else { // copy of [TabContentLayout#layout] val toLayout = children.toMutableList() val toRemove = mutableListOf<Component>() var requiredWidth = toLayout.sumOf { it.preferredSize.width } val selected = selected() val toFitWidth = parent.bounds.width - (control?.preferredSize?.width ?: 0) while (true) { if (requiredWidth <= toFitWidth) break if (toLayout.size <= 1) break if (toLayout.first() != selected) { requiredWidth -= toLayout.first().preferredSize.width + 1 toRemove += toLayout.first() toLayout.removeFirst() } else if (toLayout.last() != selected) { requiredWidth -= toLayout.last().preferredSize.width + 1 toRemove += toLayout.last() toLayout.removeLast() } else { break } } toLayout.forEach { val prefSize = it.preferredSize it.bounds = Rectangle(eachX, 0, minOf(prefSize.width, toFitWidth), parent.height) eachX += prefSize.width } toRemove.forEach { it.bounds = Rectangle(0, 0, 0, 0) } control?.let { val controlPrefSize = it.preferredSize it.bounds = Rectangle(Point(toFitWidth, (parent.height - controlPrefSize.height) / 2), controlPrefSize) } } } companion object { const val CONTROL = "ControlComponent" } } /** * Workaround action to prevent [Separator] disappearing when [SingleContentSupplier.getContentActions] is empty. */ private class MyInvisibleAction : DumbAwareAction(), CustomComponentAction { override fun actionPerformed(e: AnActionEvent) { error("An operation is not supported") } override fun createCustomComponent(presentation: Presentation, place: String): JComponent { return NonOpaquePanel() } } private class MyRedispatchMouseEventListener( val redispatch: (MouseEvent) -> Unit ) : MouseListener, MouseMotionListener { fun installOn(component: Component) { component.addMouseListener(this) component.addMouseMotionListener(this) } override fun mouseClicked(e: MouseEvent) = redispatch(e) override fun mousePressed(e: MouseEvent) = redispatch(e) override fun mouseReleased(e: MouseEvent) = redispatch(e) override fun mouseEntered(e: MouseEvent) = redispatch(e) override fun mouseExited(e: MouseEvent) = redispatch(e) override fun mouseDragged(e: MouseEvent) = redispatch(e) override fun mouseMoved(e: MouseEvent) = redispatch(e) } private enum class ToolbarType { MAIN, CLOSE_GROUP } }
platform/platform-impl/src/com/intellij/openapi/wm/impl/content/SingleContentLayout.kt
2189022196
package com.github.kerubistan.kerub.planner.steps.storage.migrate.dead.block import com.github.kerubistan.kerub.hostUp import com.github.kerubistan.kerub.model.LvmStorageCapability import com.github.kerubistan.kerub.model.VirtualMachineStatus import com.github.kerubistan.kerub.model.VirtualStorageLink import com.github.kerubistan.kerub.model.config.HostConfiguration import com.github.kerubistan.kerub.model.dynamic.CompositeStorageDeviceDynamic import com.github.kerubistan.kerub.model.dynamic.VirtualMachineDynamic import com.github.kerubistan.kerub.model.dynamic.VirtualStorageDeviceDynamic import com.github.kerubistan.kerub.model.dynamic.VirtualStorageLvmAllocation import com.github.kerubistan.kerub.model.hardware.BlockDevice import com.github.kerubistan.kerub.model.io.BusType import com.github.kerubistan.kerub.model.io.DeviceType import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.steps.AbstractFactoryVerifications import com.github.kerubistan.kerub.testDisk import com.github.kerubistan.kerub.testHost import com.github.kerubistan.kerub.testHostCapabilities import com.github.kerubistan.kerub.testVm import io.github.kerubistan.kroki.size.GB import io.github.kerubistan.kroki.size.TB import org.junit.Test import java.util.UUID import kotlin.test.assertTrue class MigrateBlockAllocationFactoryTest : AbstractFactoryVerifications(MigrateBlockAllocationFactory) { @Test fun produce() { assertTrue("only a single host - nowhere to migrate to") { val host1cap = LvmStorageCapability( physicalVolumes = mapOf("/dev/sda" to 1.TB), size = 1.TB, volumeGroupName = "vg-1" ) val host1 = testHost.copy( address = "host-1.example.com", id = UUID.randomUUID(), capabilities = testHostCapabilities.copy( blockDevices = listOf(BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB)), storageCapabilities = listOf(host1cap) ) ) val host1dyn = hostUp(host1).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = host1cap.id, reportedFreeCapacity = 1.TB ) ) ) val sourceAllocation = VirtualStorageLvmAllocation( hostId = host1.id, vgName = host1cap.volumeGroupName, capabilityId = host1cap.id, path = "/dev/vg-1/source", actualSize = 1.GB ) MigrateBlockAllocationFactory.produce( OperationalState.fromLists( hosts = listOf(host1), hostDyns = listOf(host1dyn), vStorage = listOf(testDisk), vStorageDyns = listOf( VirtualStorageDeviceDynamic( id = testDisk.id, allocations = listOf( sourceAllocation ) ) ) )).isEmpty() } assertTrue("two servers, plenty of space, rw disk - but ut is used by a vm - let's do nothing") { val host1cap = LvmStorageCapability( physicalVolumes = mapOf("/dev/sda" to 1.TB), size = 1.TB, volumeGroupName = "vg-1" ) val host1 = testHost.copy( address = "host-1.example.com", id = UUID.randomUUID(), capabilities = testHostCapabilities.copy( blockDevices = listOf(BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB)), storageCapabilities = listOf(host1cap) ) ) val host2cap = LvmStorageCapability( physicalVolumes = mapOf("/dev/sda" to 1.TB), size = 1.TB, volumeGroupName = "vg-1" ) val host2 = testHost.copy( address = "host-2.example.com", id = UUID.randomUUID(), capabilities = testHostCapabilities.copy( blockDevices = listOf(BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB)), storageCapabilities = listOf(host2cap) ) ) val host1dyn = hostUp(host1).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = host1cap.id, reportedFreeCapacity = 1.TB ) ) ) val host2dyn = hostUp(host2).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = host2cap.id, reportedFreeCapacity = 1.TB ) ) ) val sourceAllocation = VirtualStorageLvmAllocation( hostId = host1.id, vgName = host1cap.volumeGroupName, capabilityId = host1cap.id, path = "/dev/vg-1/source", actualSize = 1.GB ) val vm = testVm.copy( virtualStorageLinks = listOf( VirtualStorageLink( virtualStorageId = testDisk.id, device = DeviceType.disk, readOnly = false, bus = BusType.sata ) ) ) MigrateBlockAllocationFactory.produce( OperationalState.fromLists( hosts = listOf(host1, host2), hostDyns = listOf(host1dyn, host2dyn), vms = listOf(vm), vmDyns = listOf( VirtualMachineDynamic( id = vm.id, status = VirtualMachineStatus.Up, memoryUsed = 1.GB, hostId = host1.id ) ), vStorage = listOf(testDisk), vStorageDyns = listOf( VirtualStorageDeviceDynamic( id = testDisk.id, allocations = listOf( sourceAllocation ) ) ) )).isEmpty() } assertTrue("two servers, rw disk - but not enough free space on the other server - let's do nothing") { val host1cap = LvmStorageCapability( physicalVolumes = mapOf("/dev/sda" to 1.TB), size = 1.TB, volumeGroupName = "vg-1" ) val host1 = testHost.copy( address = "host-1.example.com", id = UUID.randomUUID(), capabilities = testHostCapabilities.copy( blockDevices = listOf(BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB)), storageCapabilities = listOf(host1cap) ) ) val host2cap = LvmStorageCapability( physicalVolumes = mapOf("/dev/sda" to 1.TB), size = 1.TB, volumeGroupName = "vg-1" ) val host2 = testHost.copy( address = "host-2.example.com", id = UUID.randomUUID(), capabilities = testHostCapabilities.copy( blockDevices = listOf(BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB)), storageCapabilities = listOf(host2cap) ) ) val host1dyn = hostUp(host1).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = host1cap.id, reportedFreeCapacity = 1.TB ) ) ) val host2dyn = hostUp(host2).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = host2cap.id, reportedFreeCapacity = 0.TB ) ) ) val sourceAllocation = VirtualStorageLvmAllocation( hostId = host1.id, vgName = host1cap.volumeGroupName, capabilityId = host1cap.id, path = "/dev/vg-1/source", actualSize = 1.GB ) MigrateBlockAllocationFactory.produce( OperationalState.fromLists( hosts = listOf(host1, host2), hostDyns = listOf(host1dyn, host2dyn), vStorage = listOf(testDisk), vStorageDyns = listOf( VirtualStorageDeviceDynamic( id = testDisk.id, allocations = listOf( sourceAllocation ) ) ) )).isEmpty() } assertTrue("two servers, plenty of space, rw disk - let's do it") { val host1cap = LvmStorageCapability( physicalVolumes = mapOf("/dev/sda" to 1.TB), size = 1.TB, volumeGroupName = "vg-1" ) val host1 = testHost.copy( address = "host-1.example.com", id = UUID.randomUUID(), capabilities = testHostCapabilities.copy( blockDevices = listOf(BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB)), storageCapabilities = listOf(host1cap) ) ) val host2cap = LvmStorageCapability( physicalVolumes = mapOf("/dev/sda" to 1.TB), size = 1.TB, volumeGroupName = "vg-1" ) val host2 = testHost.copy( address = "host-2.example.com", id = UUID.randomUUID(), capabilities = testHostCapabilities.copy( blockDevices = listOf(BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB)), storageCapabilities = listOf(host2cap) ) ) val host1dyn = hostUp(host1).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = host1cap.id, reportedFreeCapacity = 1.TB ) ) ) val host2dyn = hostUp(host2).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = host2cap.id, reportedFreeCapacity = 1.TB ) ) ) val sourceAllocation = VirtualStorageLvmAllocation( hostId = host1.id, vgName = host1cap.volumeGroupName, capabilityId = host1cap.id, path = "/dev/vg-1/source", actualSize = 1.GB ) MigrateBlockAllocationFactory.produce( OperationalState.fromLists( hosts = listOf(host1, host2), hostDyns = listOf(host1dyn, host2dyn), hostCfgs = listOf( HostConfiguration(id = host1.id, publicKey = "host1-public-key"), HostConfiguration(id = host2.id, acceptedPublicKeys = listOf("host1-public-key")) ), vStorage = listOf(testDisk), vStorageDyns = listOf( VirtualStorageDeviceDynamic( id = testDisk.id, allocations = listOf( sourceAllocation ) ) ) )).single().let { it.sourceAllocation == sourceAllocation && it.sourceHost == host1 && it.targetHost == host2 && it.allocationStep.host == host2 && it.allocationStep.capability == host2cap && it.deAllocationStep.host == host1 && it.deAllocationStep.allocation == sourceAllocation && it.virtualStorage == testDisk } } } }
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/migrate/dead/block/MigrateBlockAllocationFactoryTest.kt
3724466002
// 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.fir.inspections.declarations import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.api.applicator.with import org.jetbrains.kotlin.idea.fir.api.AbstractHLInspection import org.jetbrains.kotlin.idea.fir.api.applicator.inputProvider import org.jetbrains.kotlin.idea.fir.api.applicator.presentation import org.jetbrains.kotlin.idea.fir.applicators.ApplicabilityRanges import org.jetbrains.kotlin.idea.fir.applicators.CallableReturnTypeUpdaterApplicator import org.jetbrains.kotlin.psi.KtNamedFunction internal class HLRedundantUnitReturnTypeInspection : AbstractHLInspection<KtNamedFunction, CallableReturnTypeUpdaterApplicator.TypeInfo>( KtNamedFunction::class ), CleanupLocalInspectionTool { override val applicabilityRange = ApplicabilityRanges.CALLABLE_RETURN_TYPE override val applicator = CallableReturnTypeUpdaterApplicator.applicator.with { isApplicableByPsi { callable -> val function = callable as? KtNamedFunction ?: return@isApplicableByPsi false function.hasBlockBody() && function.typeReference != null } familyName(KotlinBundle.lazyMessage("remove.explicit.type.specification")) actionName(KotlinBundle.lazyMessage("redundant.unit.return.type")) } override val inputProvider = inputProvider<KtNamedFunction, CallableReturnTypeUpdaterApplicator.TypeInfo> { function -> when { function.getFunctionLikeSymbol().returnType.isUnit -> CallableReturnTypeUpdaterApplicator.TypeInfo(CallableReturnTypeUpdaterApplicator.TypeInfo.UNIT) else -> null } } override val presentation = presentation<KtNamedFunction> { highlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL) } }
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/inspections/declarations/HLRedundantUnitReturnTypeInspection.kt
1739494934
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.actions import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsDataKeys import com.intellij.openapi.vcs.changes.ChangeList import com.intellij.openapi.vcs.changes.ChangeListManagerEx import com.intellij.openapi.vcs.changes.LocalChangeList import com.intellij.util.ArrayUtil import com.intellij.util.ThreeState import java.util.* class RemoveChangeListAction : AbstractChangeListAction() { private val LOG = logger<RemoveChangeListAction>() override fun update(e: AnActionEvent) { val changeListsArray = e.getData(VcsDataKeys.CHANGE_LISTS) val changeLists = changeListsArray?.asList() ?: emptyList() val enabled = canRemoveChangeLists(e.project, changeLists) updateEnabledAndVisible(e, enabled) val presentation = e.presentation presentation.text = ActionsBundle.message("action.ChangesView.RemoveChangeList.text.template", changeLists.size) val hasChanges = !ArrayUtil.isEmpty(e.getData(VcsDataKeys.CHANGES)) if (hasChanges) { val containsActiveChangelist = changeLists.any { it is LocalChangeList && it.isDefault } val changeListName = if (containsActiveChangelist) VcsBundle.message("changes.another.change.list") else VcsBundle.message("changes.default.change.list") presentation.description = ActionsBundle.message("action.ChangesView.RemoveChangeList.description.template", changeLists.size, changeListName) } else { presentation.description = null } } private fun canRemoveChangeLists(project: Project?, lists: List<ChangeList>): Boolean { if (project == null || lists.isEmpty()) return false for (changeList in lists) { if (changeList !is LocalChangeList) return false if (changeList.isReadOnly) return false } return true } override fun actionPerformed(e: AnActionEvent) { val project = e.getRequiredData(CommonDataKeys.PROJECT) val selectedLists = e.getRequiredData(VcsDataKeys.CHANGE_LISTS) @Suppress("UNCHECKED_CAST") deleteLists(project, Arrays.asList(*selectedLists) as Collection<LocalChangeList>) } private fun deleteLists(project: Project, lists: Collection<LocalChangeList>) { val manager = ChangeListManagerEx.getInstanceEx(project) val toRemove = mutableListOf<LocalChangeList>() val toAsk = mutableListOf<LocalChangeList>() for (list in lists.mapNotNull { manager.getChangeList(it.id) }) { when (ChangeListRemoveConfirmation.checkCanDeleteChangelist(project, list, explicitly = true)) { ThreeState.UNSURE -> toAsk.add(list) ThreeState.YES -> toRemove.add(list) ThreeState.NO -> { } } } val pendingLists = toAsk + toRemove val activeChangelistSelected = pendingLists.any { it.isDefault } if (activeChangelistSelected) { val remainingLists = manager.changeLists.subtract(pendingLists).toList() if (remainingLists.isEmpty()) { if (!confirmAllChangeListsRemoval(project, pendingLists, toAsk)) return var defaultList = manager.findChangeList(LocalChangeList.getDefaultName()) if (defaultList == null) { defaultList = manager.addChangeList(LocalChangeList.getDefaultName(), null) } else { manager.editComment(defaultList.name, null) manager.editChangeListData(defaultList.name, null) } manager.setDefaultChangeList(defaultList!!) toRemove.addAll(toAsk) toRemove.remove(defaultList) } else { val newDefault = askNewDefaultChangeList(project, toAsk, remainingLists) ?: return manager.setDefaultChangeList(newDefault) toRemove.addAll(toAsk) if (toRemove.remove(newDefault)) LOG.error("New default changelist should be selected among remaining") } } else { if (confirmChangeListRemoval(project, toAsk)) { toRemove.addAll(toAsk) } } toRemove.forEach { manager.removeChangeList(it.name) } } private fun confirmChangeListRemoval(project: Project, lists: List<LocalChangeList>): Boolean { val haveNoChanges = lists.all { it.changes.isEmpty() } if (haveNoChanges) return true val message = if (lists.size == 1) VcsBundle.message("changes.removechangelist.warning.text", lists.single().name) else VcsBundle.message("changes.removechangelist.multiple.warning.text", lists.size) return Messages.YES == Messages.showYesNoDialog(project, message, VcsBundle.message("changes.removechangelist.warning.title"), Messages.getQuestionIcon()) } private fun confirmAllChangeListsRemoval(project: Project, pendingLists: List<LocalChangeList>, toAsk: List<LocalChangeList>): Boolean { if (pendingLists.size == 1) return true if (toAsk.isEmpty()) return true val haveNoChanges = pendingLists.all { it.changes.isEmpty() } if (haveNoChanges) return true val message = VcsBundle.message("changes.removechangelist.all.lists.warning.text", pendingLists.size) return Messages.YES == Messages.showYesNoDialog(project, message, VcsBundle.message("changes.removechangelist.warning.title"), Messages.getQuestionIcon()) } private fun askNewDefaultChangeList(project: Project, lists: List<LocalChangeList>, remainingLists: List<LocalChangeList>): LocalChangeList? { assert(remainingLists.isNotEmpty()) val haveNoChanges = lists.all { it.changes.isEmpty() } // don't ask "Which changelist to make active" if there is only one option anyway // unless there are some changes to be moved - give user a chance to cancel deletion if (remainingLists.size == 1 && haveNoChanges) { return remainingLists.single() } else { val remainingListsNames = remainingLists.map { it.name }.toTypedArray() val message = if (haveNoChanges) VcsBundle.message("changes.remove.active.empty.prompt") else VcsBundle.message("changes.remove.active.prompt") val nameIndex = Messages.showChooseDialog(project, message, VcsBundle.message("changes.remove.active.title"), Messages.getQuestionIcon(), remainingListsNames, remainingListsNames.first()) if (nameIndex < 0) return null return remainingLists[nameIndex] } } }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/RemoveChangeListAction.kt
1748146867
/* * 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.platform import android.graphics.Outline import android.graphics.RenderNode import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.CanvasHolder import androidx.compose.ui.graphics.CompositingStrategy import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.RenderEffect /** * RenderNode on Q+ devices, where it is officially supported. */ @RequiresApi(Build.VERSION_CODES.Q) internal class RenderNodeApi29(val ownerView: AndroidComposeView) : DeviceRenderNode { private val renderNode = RenderNode("Compose") private var internalRenderEffect: RenderEffect? = null private var internalCompositingStrategy: CompositingStrategy = CompositingStrategy.Auto internal fun isUsingCompositingLayer(): Boolean = renderNode.useCompositingLayer internal fun hasOverlappingRendering(): Boolean = renderNode.hasOverlappingRendering() override val uniqueId: Long get() = renderNode.uniqueId override val left: Int get() = renderNode.left override val top: Int get() = renderNode.top override val right: Int get() = renderNode.right override val bottom: Int get() = renderNode.bottom override val width: Int get() = renderNode.width override val height: Int get() = renderNode.height override var scaleX: Float get() = renderNode.scaleX set(value) { renderNode.scaleX = value } override var scaleY: Float get() = renderNode.scaleY set(value) { renderNode.scaleY = value } override var translationX: Float get() = renderNode.translationX set(value) { renderNode.translationX = value } override var translationY: Float get() = renderNode.translationY set(value) { renderNode.translationY = value } override var elevation: Float get() = renderNode.elevation set(value) { renderNode.elevation = value } override var ambientShadowColor: Int get() = renderNode.ambientShadowColor set(value) { renderNode.ambientShadowColor = value } override var spotShadowColor: Int get() = renderNode.spotShadowColor set(value) { renderNode.spotShadowColor = value } override var rotationZ: Float get() = renderNode.rotationZ set(value) { renderNode.rotationZ = value } override var rotationX: Float get() = renderNode.rotationX set(value) { renderNode.rotationX = value } override var rotationY: Float get() = renderNode.rotationY set(value) { renderNode.rotationY = value } override var cameraDistance: Float get() = renderNode.cameraDistance set(value) { renderNode.cameraDistance = value } override var pivotX: Float get() = renderNode.pivotX set(value) { renderNode.pivotX = value } override var pivotY: Float get() = renderNode.pivotY set(value) { renderNode.pivotY = value } override var clipToOutline: Boolean get() = renderNode.clipToOutline set(value) { renderNode.clipToOutline = value } override var clipToBounds: Boolean get() = renderNode.clipToBounds set(value) { renderNode.clipToBounds = value } override var alpha: Float get() = renderNode.alpha set(value) { renderNode.alpha = value } override var renderEffect: RenderEffect? get() = internalRenderEffect set(value) { internalRenderEffect = value if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { RenderNodeApi29VerificationHelper.setRenderEffect(renderNode, value) } } override var compositingStrategy: CompositingStrategy get() = internalCompositingStrategy set(value) { with(renderNode) { when (value) { CompositingStrategy.Offscreen -> { setUseCompositingLayer(true, null) setHasOverlappingRendering(true) } CompositingStrategy.ModulateAlpha -> { setUseCompositingLayer(false, null) setHasOverlappingRendering(false) } else -> { // CompositingStrategy.Auto setUseCompositingLayer(false, null) setHasOverlappingRendering(true) } } } internalCompositingStrategy = value } override val hasDisplayList: Boolean get() = renderNode.hasDisplayList() override fun setOutline(outline: Outline?) { renderNode.setOutline(outline) } override fun setPosition(left: Int, top: Int, right: Int, bottom: Int): Boolean { return renderNode.setPosition(left, top, right, bottom) } override fun offsetLeftAndRight(offset: Int) { renderNode.offsetLeftAndRight(offset) } override fun offsetTopAndBottom(offset: Int) { renderNode.offsetTopAndBottom(offset) } override fun record( canvasHolder: CanvasHolder, clipPath: Path?, drawBlock: (Canvas) -> Unit ) { canvasHolder.drawInto(renderNode.beginRecording()) { if (clipPath != null) { save() clipPath(clipPath) } drawBlock(this) if (clipPath != null) { restore() } } renderNode.endRecording() } override fun getMatrix(matrix: android.graphics.Matrix) { return renderNode.getMatrix(matrix) } override fun getInverseMatrix(matrix: android.graphics.Matrix) { return renderNode.getInverseMatrix(matrix) } override fun drawInto(canvas: android.graphics.Canvas) { canvas.drawRenderNode(renderNode) } override fun setHasOverlappingRendering(hasOverlappingRendering: Boolean): Boolean = renderNode.setHasOverlappingRendering(hasOverlappingRendering) override fun dumpRenderNodeData(): DeviceRenderNodeData = DeviceRenderNodeData( uniqueId = renderNode.uniqueId, left = renderNode.left, top = renderNode.top, right = renderNode.right, bottom = renderNode.bottom, width = renderNode.width, height = renderNode.height, scaleX = renderNode.scaleX, scaleY = renderNode.scaleY, translationX = renderNode.translationX, translationY = renderNode.translationY, elevation = renderNode.elevation, ambientShadowColor = renderNode.ambientShadowColor, spotShadowColor = renderNode.spotShadowColor, rotationZ = renderNode.rotationZ, rotationX = renderNode.rotationX, rotationY = renderNode.rotationY, cameraDistance = renderNode.cameraDistance, pivotX = renderNode.pivotX, pivotY = renderNode.pivotY, clipToOutline = renderNode.clipToOutline, clipToBounds = renderNode.clipToBounds, alpha = renderNode.alpha, renderEffect = internalRenderEffect, compositingStrategy = internalCompositingStrategy ) override fun discardDisplayList() { renderNode.discardDisplayList() } } @RequiresApi(Build.VERSION_CODES.S) private object RenderNodeApi29VerificationHelper { @androidx.annotation.DoNotInline fun setRenderEffect(renderNode: RenderNode, target: RenderEffect?) { renderNode.setRenderEffect(target?.asAndroidRenderEffect()) } }
compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/RenderNodeApi29.android.kt
4160365247
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.datastore.core import androidx.datastore.core.handlers.NoOpCorruptionHandler import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler import java.io.File import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob public object MultiProcessDataStoreFactory { /** * Create an instance of MultiProcessDataStore, which provides cross-process eventual * consistency. Never create more than one instance of DataStore for a given file in the same * process; doing so can break all DataStore functionality. You should consider managing your * DataStore instance for each file as a singleton. If there are multiple DataStores active for * a given file in the same process, DataStore will throw IllegalStateException when reading or * updating data. A DataStore is considered active as long as its scope is active. Having * multiple instances, each for a different file, in the same process is OK. * * T is the type DataStore acts on. The type T must be immutable. Mutating a type used in * DataStore invalidates any guarantees that DataStore provides and will result in * potentially serious, hard-to-catch bugs. We strongly recommend using protocol buffers: * https://developers.google.com/protocol-buffers/docs/javatutorial - which provides * immutability guarantees, a simple API and efficient serialization. * * @param storage Storage to handle file reads and writes used with DataStore. The type T must * be immutable. The storage must operate on the same file as the one passed in * {@link produceFile}. * @param corruptionHandler The [ReplaceFileCorruptionHandler] is invoked if DataStore * encounters a [CorruptionException] when attempting to read data. CorruptionExceptions are * thrown by serializers when data can not be de-serialized. * @param migrations Migrations are run before any access to data can occur. Migrations must * be idempotent. * @param scope The scope in which IO operations and transform functions will execute. * @param produceFile Function which returns the file that the new DataStore will act on. The * function must return the same path every time. No two instances of DataStore should act on * the same file at the same time in the same process. * * @return a new DataStore instance with the provided configuration */ @ExperimentalMultiProcessDataStore @JvmOverloads // Generate constructors for default params for java users. public fun <T> create( storage: Storage<T>, corruptionHandler: ReplaceFileCorruptionHandler<T>? = null, migrations: List<DataMigration<T>> = listOf(), scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()), produceFile: () -> File ): DataStore<T> = MultiProcessDataStore<T>( storage = storage, produceFile = produceFile, initTasksList = listOf(DataMigrationInitializer.getInitializer(migrations)), corruptionHandler = corruptionHandler ?: NoOpCorruptionHandler(), scope = scope ) /** * Create an instance of MultiProcessDataStore, which provides cross-process eventual * consistency. Never create more than one instance of DataStore for a given file in the same * process; doing so can break all DataStore functionality. You should consider managing your * DataStore instance for each file as a singleton. If there are multiple DataStores active for * a given file in the same process, DataStore will throw IllegalStateException when reading or * updating data. A DataStore is considered active as long as its scope is active. Having * multiple instances, each for a different file, in the same process is OK. * * T is the type DataStore acts on. The type T must be immutable. Mutating a type used in * DataStore invalidates any guarantees that DataStore provides and will result in * potentially serious, hard-to-catch bugs. We strongly recommend using protocol buffers: * https://developers.google.com/protocol-buffers/docs/javatutorial - which provides * immutability guarantees, a simple API and efficient serialization. * * @param serializer Serializer for the type T used with DataStore. The type T must be immutable. * @param corruptionHandler The {@link androidx.datastore.core.handlers.ReplaceFileCorruptionHandler} * is invoked if DataStore encounters a [CorruptionException] when attempting to read data. * CorruptionExceptions are thrown by serializers when data can not be de-serialized. * @param migrations Migrations are run before any access to data can occur. Migrations must * be idempotent. * @param scope The scope in which IO operations and transform functions will execute. * @param produceFile Function which returns the file that the new DataStore will act on. The * function must return the same path every time. No two instances of DataStore should act on * the same file at the same time in the same process. * * @return a new DataStore instance with the provided configuration */ @ExperimentalMultiProcessDataStore @JvmOverloads // Generate constructors for default params for java users. public fun <T> create( serializer: Serializer<T>, corruptionHandler: ReplaceFileCorruptionHandler<T>? = null, migrations: List<DataMigration<T>> = listOf(), scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()), produceFile: () -> File ): DataStore<T> = MultiProcessDataStore<T>( storage = FileStorage(serializer, produceFile), initTasksList = listOf(DataMigrationInitializer.getInitializer(migrations)), corruptionHandler = corruptionHandler ?: NoOpCorruptionHandler(), scope = scope, produceFile = produceFile ) }
datastore/datastore-core/src/androidMain/kotlin/androidx/datastore/core/MultiProcessDataStoreFactory.kt
2290312896
/* * 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.window import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp /** * Creates a [WindowState] that is remembered across compositions. * * Changes to the provided initial values will **not** result in the state being recreated or * changed in any way if it has already been created. * * @param placement the initial value for [WindowState.placement] * @param isMinimized the initial value for [WindowState.isMinimized] * @param position the initial value for [WindowState.position] * @param size the initial value for [WindowState.size] */ @Composable fun rememberWindowState( placement: WindowPlacement = WindowPlacement.Floating, isMinimized: Boolean = false, position: WindowPosition = WindowPosition.PlatformDefault, size: DpSize = DpSize(800.dp, 600.dp), ): WindowState = rememberSaveable(saver = WindowStateImpl.Saver(position)) { WindowStateImpl( placement, isMinimized, position, size ) } /** * Creates a [WindowState] that is remembered across compositions. * * Changes to the provided initial values will **not** result in the state being recreated or * changed in any way if it has already been created. * * @param placement the initial value for [WindowState.placement] * @param isMinimized the initial value for [WindowState.isMinimized] * @param position the initial value for [WindowState.position] * @param size the initial value for [WindowState.size] */ @Suppress("DEPRECATION") @Composable @Deprecated("Use rememberWindowState which accepts DpSize") fun rememberWindowState( placement: WindowPlacement = WindowPlacement.Floating, isMinimized: Boolean = false, position: WindowPosition = WindowPosition.PlatformDefault, size: WindowSize ): WindowState = rememberSaveable(saver = WindowStateImpl.Saver(position)) { WindowStateImpl( placement, isMinimized, position, DpSize(size.width, size.height) ) } /** * Creates a [WindowState] that is remembered across compositions. * * Changes to the provided initial values will **not** result in the state being recreated or * changed in any way if it has already been created. * * @param placement the initial value for [WindowState.placement] * @param isMinimized the initial value for [WindowState.isMinimized] * @param position the initial value for [WindowState.position] * @param width the initial value for width of [WindowState.size] * @param height the initial value for height of [WindowState.size] */ @Composable fun rememberWindowState( placement: WindowPlacement = WindowPlacement.Floating, isMinimized: Boolean = false, position: WindowPosition = WindowPosition.PlatformDefault, width: Dp = 800.dp, height: Dp = 600.dp ): WindowState = rememberSaveable(saver = WindowStateImpl.Saver(position)) { WindowStateImpl( placement, isMinimized, position, DpSize(width, height) ) } /** * A state object that can be hoisted to control and observe window attributes * (size/position/state). * * @param placement the initial value for [WindowState.placement] * @param isMinimized the initial value for [WindowState.isMinimized] * @param position the initial value for [WindowState.position] * @param size the initial value for [WindowState.size] */ fun WindowState( placement: WindowPlacement = WindowPlacement.Floating, isMinimized: Boolean = false, position: WindowPosition = WindowPosition.PlatformDefault, size: DpSize = DpSize(800.dp, 600.dp) ): WindowState = WindowStateImpl( placement, isMinimized, position, size ) /** * A state object that can be hoisted to control and observe window attributes * (size/position/state). * * @param placement the initial value for [WindowState.placement] * @param isMinimized the initial value for [WindowState.isMinimized] * @param position the initial value for [WindowState.position] * @param size the initial value for [WindowState.size] */ @Deprecated("Use WindowState which accepts DpSize") @Suppress("DEPRECATION") fun WindowState( placement: WindowPlacement = WindowPlacement.Floating, isMinimized: Boolean = false, position: WindowPosition = WindowPosition.PlatformDefault, size: WindowSize ): WindowState = WindowStateImpl( placement, isMinimized, position, DpSize(size.width, size.height) ) /** * A state object that can be hoisted to control and observe window attributes * (size/position/state). * * @param placement the initial value for [WindowState.placement] * @param isMinimized the initial value for [WindowState.isMinimized] * @param position the initial value for [WindowState.position] * @param width the initial value for width of [WindowState.size] * @param height the initial value for height of [WindowState.size] */ fun WindowState( placement: WindowPlacement = WindowPlacement.Floating, isMinimized: Boolean = false, position: WindowPosition = WindowPosition.PlatformDefault, width: Dp = 800.dp, height: Dp = 600.dp ): WindowState = WindowStateImpl( placement, isMinimized, position, DpSize(width, height) ) /** * A state object that can be hoisted to control and observe window attributes * (size/position/state). */ interface WindowState { /** * Describes how the window is placed on the screen. */ var placement: WindowPlacement /** * `true` if the window is minimized. */ var isMinimized: Boolean /** * The current position of the window. If the position is not specified * ([WindowPosition.isSpecified] is false), the position will be set to absolute values * [WindowPosition.Absolute] when the window appears on the screen. */ var position: WindowPosition /** * The current size of the window. * * If the size is not specified * ([DpSize.width.isSpecified] or [DpSize.height.isSpecified] is false), the size will be set * to absolute values * ([Dp.isSpecified] is true) when the window appears on the screen. * * Unspecified can be only width, only height, or both. If, for example, window contains some * text and we use size=DpSize(300.dp, Dp.Unspecified) then the width will be exactly * 300.dp, but the height will be such that all the text will fit. */ var size: DpSize } private class WindowStateImpl( placement: WindowPlacement, isMinimized: Boolean, position: WindowPosition, size: DpSize ) : WindowState { override var placement by mutableStateOf(placement) override var isMinimized by mutableStateOf(isMinimized) override var position by mutableStateOf(position) override var size by mutableStateOf(size) companion object { /** * The default [Saver] implementation for [WindowStateImpl]. */ fun Saver(unspecifiedPosition: WindowPosition) = listSaver<WindowState, Any>( save = { listOf( it.placement.ordinal, it.isMinimized, it.position.isSpecified, it.position.x.value, it.position.y.value, it.size.width.value, it.size.height.value, ) }, restore = { state -> WindowStateImpl( placement = WindowPlacement.values()[state[0] as Int], isMinimized = state[1] as Boolean, position = if (state[2] as Boolean) { WindowPosition((state[3] as Float).dp, (state[4] as Float).dp) } else { unspecifiedPosition }, size = DpSize((state[5] as Float).dp, (state[6] as Float).dp), ) } ) } }
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/window/WindowState.desktop.kt
1703934417
package org.thoughtcrime.securesms.conversation.ui.inlinequery /** * Called when a query changes. */ interface InlineQueryChangedListener { fun onQueryChanged(inlineQuery: InlineQuery) fun clearQuery() = onQueryChanged(InlineQuery.NoQuery) }
app/src/main/java/org/thoughtcrime/securesms/conversation/ui/inlinequery/InlineQueryChangedListener.kt
1484527060
package com.intellij.xdebugger.impl.ui.attach.dialog.items import com.intellij.ui.table.JBTable import java.awt.Rectangle import javax.swing.DefaultListSelectionModel import javax.swing.ListSelectionModel import javax.swing.table.TableModel internal interface AttachSelectionIgnoredNode internal interface AttachNodeContainer<TNodeType> { fun getAttachNode(): TNodeType } class AttachToProcessTableSelectionModel(private val table: JBTable) : DefaultListSelectionModel() { init { selectionMode = ListSelectionModel.SINGLE_SELECTION } override fun setSelectionInterval(index0: Int, index1: Int) { if (index0 >= 0 && index0 < table.rowCount && table.model.getValueAt<Any>(index0) is AttachSelectionIgnoredNode) { val currentIndex = minSelectionIndex if (currentIndex < 0 || currentIndex >= table.rowCount) { val next = getNextIndex(index0) setSelectionInterval(next, next) return } if (currentIndex == index0 - 1) { val newIndex = getNextIndex(index0) setSelectionInterval(newIndex, newIndex) return } if (currentIndex == index0 + 1) { val newIndex = getPreviousIndex(index0) setSelectionInterval(newIndex, newIndex) return } setSelectionInterval(-1, -1) return } super.setSelectionInterval(index0, index1) scrollIfNeeded(index0) } override fun addSelectionInterval(index0: Int, index1: Int) { if (index0 >= 0 && index0 < table.rowCount && table.model.getValueAt<Any>(index0) is AttachSelectionIgnoredNode) { return } super.addSelectionInterval(index0, index1) scrollIfNeeded(index0) } private fun scrollIfNeeded(index0: Int) { if (index0 >= 0 && index0 < table.rowCount) { val cellRect = table.getCellRect(index0, 0, true) val visibleRect = table.visibleRect if (visibleRect.isEmpty) return if (visibleRect.contains(cellRect)) return if (visibleRect.y + visibleRect.height < cellRect.y + cellRect.height) { table.scrollRectToVisible(Rectangle( cellRect.x,cellRect.y + cellRect.height, cellRect.width, 0)) } else { table.scrollRectToVisible(Rectangle( cellRect.x, cellRect.y, cellRect.width, 0)) } } } private fun getPreviousIndex(index0: Int): Int { var newIndex = index0 - 1 while (newIndex >= 0 && table.model.getValueAt<Any>(newIndex) is AttachSelectionIgnoredNode) { newIndex-- } return if (newIndex >= 0) newIndex else -1 } private fun getNextIndex(index0: Int): Int { var newIndex = index0 + 1 while (newIndex < table.rowCount && table.model.getValueAt<Any>(newIndex) is AttachSelectionIgnoredNode) { newIndex++ } return if (newIndex < table.rowCount) newIndex else -1 } } internal inline fun <reified TNodeType> TableModel.getValueAt(row: Int): TNodeType? { if (row < 0 || row >= rowCount) { return null } return when (val value = getValueAt(row, 0)) { is TNodeType -> value is AttachNodeContainer<*> -> value.getAttachNode() as? TNodeType else -> null } } internal fun JBTable.focusFirst() { val currentIndex = selectedRow if (currentIndex >= 0 && currentIndex < model.rowCount) { return } if (model.rowCount > 0) { selectionModel.setSelectionInterval(0, 0) } }
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/attach/dialog/items/AttachToProcessTableSelectionModel.kt
2052538972
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.highlighter.markers import com.intellij.application.options.colors.ColorAndFontOptions import com.intellij.codeInsight.daemon.GutterIconNavigationHandler import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.ide.DataManager import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.psi.PsiElement import com.intellij.util.Function import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.highlighter.dsl.DslKotlinHighlightingVisitorExtension import org.jetbrains.kotlin.idea.highlighter.dsl.isDslHighlightingMarker import org.jetbrains.kotlin.psi.KtClass import javax.swing.JComponent private val navHandler = GutterIconNavigationHandler<PsiElement> { event, element -> val dataContext = (event.component as? JComponent)?.let { DataManager.getInstance().getDataContext(it) } ?: return@GutterIconNavigationHandler val ktClass = element?.parent as? KtClass ?: return@GutterIconNavigationHandler val styleId = ktClass.styleIdForMarkerAnnotation() ?: return@GutterIconNavigationHandler ColorAndFontOptions.selectOrEditColor(dataContext, DslKotlinHighlightingVisitorExtension.styleOptionDisplayName(styleId), KotlinLanguage.NAME) } private val toolTipHandler = Function<PsiElement, String> { KotlinBundle.message("highlighter.tool.tip.marker.annotation.for.dsl") } fun collectHighlightingColorsMarkers( ktClass: KtClass, result: LineMarkerInfos ) { if (!KotlinLineMarkerOptions.dslOption.isEnabled) return val styleId = ktClass.styleIdForMarkerAnnotation() ?: return val anchor = ktClass.nameIdentifier ?: return @Suppress("MoveLambdaOutsideParentheses") result.add( LineMarkerInfo( anchor, anchor.textRange, createDslStyleIcon(styleId), toolTipHandler, navHandler, GutterIconRenderer.Alignment.RIGHT, { KotlinBundle.message("highlighter.tool.tip.marker.annotation.for.dsl") } ) ) } private fun KtClass.styleIdForMarkerAnnotation(): Int? { val classDescriptor = toDescriptor() as? ClassDescriptor ?: return null if (classDescriptor.kind != ClassKind.ANNOTATION_CLASS) return null if (!classDescriptor.isDslHighlightingMarker()) return null return DslKotlinHighlightingVisitorExtension.styleIdByMarkerAnnotation(classDescriptor) }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/DslHighlightingMarker.kt
829548537
package com.onyx.persistence.annotations import com.onyx.persistence.annotations.values.IdentifierGenerator /** * This annotation is used to indicate an attribute as a primary key * * * Note: The @Attribute annotation is still required in order to indicate a primary key * * @author Tim Osborn * @see com.onyx.persistence.annotations.Attribute * * @since 1.0.0 * * <pre> * * @Identifier(generator = IdentifierGenerator.SEQUENCE) * @Attribute(nullable = false, size = 200) * public long personID; * * </pre> */ @Target(AnnotationTarget.FIELD) annotation class Identifier( /** * Determines the generator mode. By default the primary key is not auto generated. * If a sequence identifier generator is selected you must declare the property as numeric. * * @return Generator Type * @since 1.0.0 */ val generator: IdentifierGenerator = IdentifierGenerator.NONE )
onyx-database/src/main/kotlin/com/onyx/persistence/annotations/Identifier.kt
299766025
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileSystemItem import com.intellij.refactoring.move.MoveCallback import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil import com.intellij.util.IncorrectOperationException import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.refactoring.isInKotlinAwareSourceRoot import org.jetbrains.kotlin.idea.refactoring.move.getOrCreateDirectory import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinAwareMoveFilesOrDirectoriesProcessor import org.jetbrains.kotlin.idea.refactoring.move.updatePackageDirective import org.jetbrains.kotlin.idea.statistics.KotlinMoveRefactoringFUSCollector import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import java.nio.file.InvalidPathException import java.nio.file.Paths internal class KotlinAwareMoveFilesOrDirectoriesModel( val project: Project, val elementsToMove: List<PsiFileSystemItem>, val targetDirectoryName: String, val updatePackageDirective: Boolean, val searchReferences: Boolean, val moveCallback: MoveCallback? ) : Model { private fun checkedGetElementsToMove(selectedDirectory: PsiDirectory): List<PsiElement> { val preparedElementsToMove = elementsToMove .filterNot { it is PsiFile && it.containingDirectory == selectedDirectory } .sortedWith( // process Kotlin files first so that light classes are updated before changing references in Java files java.util.Comparator { o1, o2 -> when { o1 is KtElement && o2 !is KtElement -> -1 o1 !is KtElement && o2 is KtElement -> 1 else -> 0 } }) try { preparedElementsToMove.forEach { MoveFilesOrDirectoriesUtil.checkMove(it, selectedDirectory) if (it is KtFile && it.isInKotlinAwareSourceRoot()) { it.updatePackageDirective = updatePackageDirective } } } catch (e: IncorrectOperationException) { throw ConfigurationException(e.message) } return preparedElementsToMove } private fun checkedGetTargetDirectory(): PsiDirectory { try { return getOrCreateDirectory(targetDirectoryName, project) } catch (e: IncorrectOperationException) { throw ConfigurationException(KotlinBundle.message("text.cannot.create.target.directory.0", targetDirectoryName)) } } @Throws(ConfigurationException::class) override fun computeModelResult() = computeModelResult(throwOnConflicts = false) private fun checkModel() { elementsToMove.firstOrNull { it !is PsiFile && it !is PsiDirectory }?.let { throw ConfigurationException(KotlinBundle.message("text.unexpected.element.type.0", it)) } if (elementsToMove.isEmpty()) { throw ConfigurationException(KotlinBundle.message("text.no.files.to.move")) } try { Paths.get(targetDirectoryName) } catch (e: InvalidPathException) { throw ConfigurationException(KotlinBundle.message("text.invalid.target.path.0", targetDirectoryName)) } if (DumbService.isDumb(project)) { throw ConfigurationException(KotlinBundle.message("text.move.refactoring.not.available.during.indexing")) } } @Throws(ConfigurationException::class) override fun computeModelResult(throwOnConflicts: Boolean): ModelResultWithFUSData { checkModel() val selectedDir = checkedGetTargetDirectory() val elementsToMove = checkedGetElementsToMove(selectedDir) val processor = KotlinAwareMoveFilesOrDirectoriesProcessor( project, elementsToMove, selectedDir, searchReferences = searchReferences, searchInComments = false, searchInNonJavaFiles = false, moveCallback = moveCallback ) return ModelResultWithFUSData( processor, elementsToMove.size, KotlinMoveRefactoringFUSCollector.MovedEntity.FILES, KotlinMoveRefactoringFUSCollector.MoveRefactoringDestination.PACKAGE ) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ui/KotlinAwareMoveFilesOrDirectoriesModel.kt
305529825
/* * Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.plugins.notebooks.visualization.r.inlays.components import org.jetbrains.plugins.notebooks.visualization.r.ui.UiCustomizer import java.awt.BorderLayout import javax.swing.JComponent import javax.swing.JPanel /** * ToolbarPane - a special component consisting of two parts which are * setDataComponent() - used for displaying some output and should fill the major part of ToolbarPane, is aligned to the left * setToolbarComponent() - typically occupies the small area to the right and contains the button that shows the output actions menu */ class ToolbarPane(val inlayOutput: InlayOutput) : JPanel(BorderLayout()) { private var mainPanel: JPanel? = null var dataComponent: JComponent? = null set(value) { field = value updateMainComponent() updateChildrenBounds() } var progressComponent: JComponent? = null set(value) { field = value updateMainComponent() updateChildrenBounds() UiCustomizer.instance.toolbarPaneProgressComponentChanged(this, value) } var toolbarComponent: JComponent? = null set(value) { field = value updateMainComponent() updateChildrenBounds() UiCustomizer.instance.toolbarPaneToolbarComponentChanged(this, value) } private fun updateMainComponent() { if (mainPanel == null) { mainPanel = JPanel(BorderLayout()).also { mainPanel -> UiCustomizer.instance.toolbarPaneMainPanelCreated(this, mainPanel) add(NotebookInlayMouseListener.wrapPanel(mainPanel, inlayOutput.editor), BorderLayout.CENTER) } } mainPanel?.let { main -> main.removeAll() progressComponent?.let { progress -> main.add(progress, BorderLayout.PAGE_START) } dataComponent?.let { central -> main.add(central, BorderLayout.CENTER) } toolbarComponent?.let { toolbar -> main.add(toolbar, BorderLayout.LINE_END) } } } private fun updateChildrenBounds() { mainPanel?.setBounds(0, 0, width, height) val progressBarWidth = if (progressComponent != null) PROGRESS_BAR_DEFAULT_WIDTH else 0 toolbarComponent?.setBounds(width - toolbarComponent!!.preferredSize.width, progressBarWidth, toolbarComponent!!.preferredSize.width, toolbarComponent!!.preferredSize.height) } override fun setBounds(x: Int, y: Int, width: Int, height: Int) { super.setBounds(x, y, width, height) updateChildrenBounds() } }
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/components/ToolbarPane.kt
3948156323
// 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.annotator import com.intellij.codeInspection.ProblemHighlightType import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.HighlightSeverity import com.intellij.psi.PsiElement import org.jetbrains.annotations.Nls import org.jetbrains.plugins.groovy.GroovyBundle import org.jetbrains.plugins.groovy.codeInspection.bugs.GrRemoveModifierFix import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor import org.jetbrains.plugins.groovy.lang.psi.api.GrRangeExpression import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrYieldStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrCaseSection import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrSwitchExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrPermitsClause import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrRecordDefinition import org.jetbrains.plugins.groovy.lang.psi.util.forbidRecord class GroovyAnnotatorPre40(private val holder: AnnotationHolder) : GroovyElementVisitor() { companion object { fun AnnotationHolder.registerModifierProblem(modifier : PsiElement, inspectionMessage : @Nls String, fixMessage : @Nls String) { val builder = newAnnotation(HighlightSeverity.ERROR, inspectionMessage).range(modifier) registerLocalFix(builder, GrRemoveModifierFix(modifier.text, fixMessage), modifier, inspectionMessage, ProblemHighlightType.ERROR, modifier.textRange) builder.create() } } override fun visitModifierList(modifierList: GrModifierList) { val sealed = modifierList.getModifier(GrModifier.SEALED) if (sealed != null) { holder.registerModifierProblem(sealed, GroovyBundle.message("inspection.message.modifier.sealed.available.with.groovy.or.later"), GroovyBundle.message("illegal.sealed.modifier.fix")) } val nonSealed = modifierList.getModifier(GrModifier.NON_SEALED) if (nonSealed != null) { holder.registerModifierProblem(nonSealed, GroovyBundle.message("inspection.message.modifier.nonsealed.available.with.groovy.or.later"), GroovyBundle.message("illegal.nonsealed.modifier.fix")) } } override fun visitPermitsClause(permitsClause: GrPermitsClause) { permitsClause.keyword?.let {holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.permits.available.with.groovy.4.or.later")).range(it).create() } } override fun visitSwitchExpression(switchExpression: GrSwitchExpression) { switchExpression.firstChild?.let { holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.switch.expressions.are.available.with.groovy.4.or.later")).range(it).create() } super.visitSwitchExpression(switchExpression) } override fun visitCaseSection(caseSection: GrCaseSection) : Unit = with(caseSection) { arrow?.let { holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.arrows.in.case.expressions.are.available.with.groovy.4.or.later")).range(it).create() } expressions?.takeIf { it.size > 1 }?.let { holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.multiple.expressions.in.case.section.are.available.with.groovy.4.or.later")).range( it.first()?.parent ?: this).create() } super.visitCaseSection(caseSection) } override fun visitYieldStatement(yieldStatement: GrYieldStatement) { yieldStatement.yieldKeyword.let { holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.keyword.yield.available.with.groovy.4.or.later")).range(it).create() } super.visitYieldStatement(yieldStatement) } override fun visitRangeExpression(range: GrRangeExpression) { when (range.boundaryType) { GrRangeExpression.BoundaryType.LEFT_OPEN -> holder .newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.left.open.ranges.are.available.in.groovy.4.or.later")) .range(range) .create() GrRangeExpression.BoundaryType.BOTH_OPEN -> holder .newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.both.open.ranges.are.available.in.groovy.4.or.later")) .range(range) .create() else -> {} } } override fun visitLiteralExpression(literal: GrLiteral) { super.visitLiteralExpression(literal) if (literal.text.startsWith(".")) { holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.fraction.literals.without.leading.zero.are.available.in.groovy.or.later")) .range(literal) .create() } } override fun visitRecordDefinition(recordDefinition: GrRecordDefinition) { forbidRecord(holder, recordDefinition) super.visitRecordDefinition(recordDefinition) } }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotatorPre40.kt
591640764
// 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.script import com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase import com.intellij.testFramework.exceptionCases.AbstractExceptionCase import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings import org.jetbrains.kotlin.test.InTextDirectivesUtils import org.junit.ComparisonFailure @DaemonAnalyzerTestCase.CanChangeDocumentDuringHighlighting abstract class AbstractScriptDefinitionsOrderTest : AbstractScriptConfigurationTest() { fun doTest(unused: String) { configureScriptFile(testDataFile()) assertException(object : AbstractExceptionCase<ComparisonFailure>() { override fun getExpectedExceptionClass(): Class<ComparisonFailure> = ComparisonFailure::class.java override fun tryClosure() { checkHighlighting(editor, false, false) } }) val definitions = InTextDirectivesUtils.findStringWithPrefixes(myFile.text, "// SCRIPT DEFINITIONS: ") ?.split(";") ?.map { it.substringBefore(":").trim() to it.substringAfter(":").trim() } ?: error("SCRIPT DEFINITIONS directive should be defined") val allDefinitions = ScriptDefinitionsManager.getInstance(project).getAllDefinitions() for ((definitionName, action) in definitions) { val scriptDefinition = allDefinitions .find { it.name == definitionName } ?: error("Unknown script definition name in SCRIPT DEFINITIONS directive: name=$definitionName, all={${allDefinitions.joinToString { it.name }}}") when (action) { "off" -> KotlinScriptingSettings.getInstance(project).setEnabled(scriptDefinition, false) else -> KotlinScriptingSettings.getInstance(project).setOrder(scriptDefinition, action.toInt()) } } ScriptDefinitionsManager.getInstance(project).reorderScriptDefinitions() checkHighlighting(editor, false, false) } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/script/AbstractScriptDefinitionsOrderTest.kt
741791428
fun conflict() {} class Convertable {} fun <caret>Convertable.conflict() {}
plugins/kotlin/idea/tests/testData/intentions/convertReceiverToParameter/validOverload.kt
2313698122
// 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. @file:ApiStatus.Experimental package com.intellij.openapi.progress import com.intellij.openapi.util.Computable import com.intellij.util.ConcurrencyUtil import kotlinx.coroutines.* import org.jetbrains.annotations.ApiStatus import kotlin.coroutines.coroutineContext /** * Checks whether the coroutine is active, and throws [CancellationException] if the coroutine is canceled. * This function might suspend if the coroutine is paused, * or yield if the coroutine has a lower priority while higher priority task is running. * * @throws CancellationException if the coroutine is canceled; the exception is also thrown if coroutine is canceled while suspended * @see ensureActive * @see coroutineSuspender */ suspend fun checkCanceled() { val ctx = coroutineContext ctx.ensureActive() // standard check first ctx[CoroutineSuspenderElementKey]?.checkPaused() // will suspend if paused } /** * The method has same semantics as [runBlocking], * and additionally [action] is canceled when current progress indicator is canceled. * * This is a bridge for invoking suspending code from blocking code. * * Example: * ``` * ProgressManager.getInstance().runProcess({ * runSuspendingAction { * someSuspendingFunctionWhichDoesntKnowAboutIndicator() * } * }, progress); * ``` * @see runUnderIndicator * @see runBlocking */ fun <T> runSuspendingAction(action: suspend CoroutineScope.() -> T): T { val indicator = ProgressManager.getGlobalProgressIndicator() return runSuspendingAction(indicator, action) } fun <T> runSuspendingAction(indicator: ProgressIndicator?, action: suspend CoroutineScope.() -> T): T { if (indicator == null) { // we are not under indicator => just run the action, since nobody will cancel it anyway return runBlocking(block = action) } // we are under indicator => the Job must be canceled when indicator is canceled return runBlocking(progressSinkElement(ProgressIndicatorSink(indicator)) + CoroutineName("indicator run blocking")) { val indicatorWatchJob = launch(Dispatchers.Default + CoroutineName("indicator watcher")) { while (true) { if (indicator.isCanceled) { // will throw PCE which will cancel the runBlocking Job and thrown further in the caller of runSuspendingAction indicator.checkCanceled() } delay(ConcurrencyUtil.DEFAULT_TIMEOUT_MS) } } val result = action() indicatorWatchJob.cancel() result } } /** * Runs blocking (e.g. Java) code under indicator, which is canceled if current Job is canceled. * * This is a bridge for invoking blocking code from suspending code. * * Example: * ``` * launch { * runUnderIndicator { * someJavaFunctionWhichDoesntKnowAboutCoroutines() * } * } * ``` * @see runSuspendingAction * @see ProgressManager.runProcess */ fun <T> CoroutineScope.runUnderIndicator(action: () -> T): T { return runUnderIndicator(coroutineContext.job, coroutineContext.progressSink, action) } @Suppress("EXPERIMENTAL_API_USAGE_ERROR") internal fun <T> runUnderIndicator(job: Job, progressSink: ProgressSink?, action: () -> T): T { job.ensureActive() val indicator = if (progressSink == null) EmptyProgressIndicator() else ProgressSinkIndicator(progressSink) try { return ProgressManager.getInstance().runProcess(Computable { // Register handler inside runProcess to avoid cancelling the indicator before even starting the progress. // If the Job was canceled while runProcess was preparing, // then CompletionHandler is invoked right away and cancels the indicator. val completionHandle = job.invokeOnCompletion(onCancelling = true) { if (it is CancellationException) { indicator.cancel() } } try { indicator.checkCanceled() action() } finally { completionHandle.dispose() } }, indicator) } catch (e: ProcessCanceledException) { if (!indicator.isCanceled) { // means the exception was thrown manually // => treat it as any other exception throw e } // indicator is canceled // => CompletionHandler was actually invoked // => current Job is canceled check(job.isCancelled) throw job.getCancellationException() } }
platform/util-ex/src/com/intellij/openapi/progress/coroutines.kt
78161509
package com.zeke.home.api import android.content.Context import com.zeke.network.response.IRequestResponse interface DataApiService<T>{ fun requestData(context: Context, callback: IRequestResponse<T>) }
module-Home/src/main/java/com/zeke/home/api/DataApiService.kt
4162066929
class DerivedClass2 : DerivedClass1() { }
plugins/kotlin/jps/jps-plugin/tests/testData/incremental/withJava/javaUsedInKotlin/mixedInheritance/DerivedClass2.kt
3621494753
// 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.openapi.application import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test import java.nio.file.Files import java.nio.file.Path class CustomConfigMigrationOptionTest : ConfigImportHelperBaseTest() { @Test fun `empty marker file indicates clean config`() { val configDir = createMarkerFile("") val option = readOption(configDir) assertTrue("Option parsed incorrectly", option is CustomConfigMigrationOption.StartWithCleanConfig) } @Test fun `marker file with import path`() { val path = PathManager.getDefaultConfigPathFor("IntelliJIdea2019.3") Files.createDirectories(memoryFs.fs.getPath(path)) val configDir = createMarkerFile("import $path") val option = readOption(configDir) assertTrue("Option parsed incorrectly", option is CustomConfigMigrationOption.MigrateFromCustomPlace) assertEquals("Import path parsed incorrectly", path, (option as CustomConfigMigrationOption.MigrateFromCustomPlace).location.toString()) } @Test fun `marker file with properties to set`() { val properties = listOf("intellij.first.ide.session", "intellij.config.imported.in.current.session") val configDir = createMarkerFile("properties ${properties.joinToString(" ")}") val option = readOption(configDir) assertTrue("Option parsed incorrectly", option is CustomConfigMigrationOption.SetProperties) assertEquals("Properties parsed incorrectly", properties, (option as CustomConfigMigrationOption.SetProperties).properties) } private fun readOption(configDir: Path) = CustomConfigMigrationOption.readCustomConfigMigrationOptionAndRemoveMarkerFile(configDir) private fun createMarkerFile(content: String): Path { val configDir = createConfigDir() val markerFile = CustomConfigMigrationOption.getCustomConfigMarkerFilePath(configDir) Files.write(markerFile, content.toByteArray()) return configDir } private fun createConfigDir(): Path { val configPath = PathManager.getDefaultConfigPathFor("IntelliJIdea2020.1") return Files.createDirectories(memoryFs.fs.getPath(configPath).normalize()) } }
platform/platform-tests/testSrc/com/intellij/openapi/application/CustomConfigMigrationOptionTest.kt
2805535880
package com.github.firenox89.shinobooru.cloud import android.content.Context import com.github.firenox89.shinobooru.repo.DataSource import com.github.firenox89.shinobooru.repo.model.CloudPost import com.github.firenox89.shinobooru.repo.model.DownloadedPost import com.github.firenox89.shinobooru.settings.SettingsManager import com.github.kittinunf.result.Result import com.github.kittinunf.result.flatMap import com.github.kittinunf.result.map import com.github.kittinunf.result.mapError import com.owncloud.android.lib.common.OwnCloudClient import com.owncloud.android.lib.common.OwnCloudClientFactory import com.owncloud.android.lib.common.OwnCloudCredentialsFactory import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.resources.files.* import com.owncloud.android.lib.resources.files.model.RemoteFile import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.produce import org.koin.core.KoinComponent import org.koin.core.inject import timber.log.Timber import java.io.File import java.lang.Exception import java.lang.IllegalArgumentException import java.util.concurrent.Executors import kotlin.coroutines.coroutineContext const val SHINOBOORU_REMOTE_PATH = "/Shinobooru/" class NextCloudSyncer(private val appContext: Context, private val dataSource: DataSource) : CloudSync, KoinComponent { private val settingsManager: SettingsManager by inject() private val networkDispatcher = Executors.newFixedThreadPool(8).asCoroutineDispatcher() private val syncDir = dataSource.getSyncDir() private fun getClient(): Result<OwnCloudClient, Exception> = settingsManager.nextcloudBaseUri?.let { baseUri -> Result.of<OwnCloudClient, Exception> { OwnCloudClientFactory.createOwnCloudClient(baseUri, appContext, true).apply { credentials = OwnCloudCredentialsFactory.newBasicCredentials( settingsManager.nextcloudUser, settingsManager.nextcloudPassword ) } } } ?: Result.error(IllegalArgumentException("Nextcloud Uri not set.")) override suspend fun upload(posts: List<DownloadedPost>): Result<Channel<UploadProgress>, Exception> = getClient().map { client -> val progressChannel = Channel<UploadProgress>() CoroutineScope(coroutineContext).async { var currentProgress = UploadProgress(posts.size, 0, null) posts.map { post -> async(networkDispatcher) { Timber.d("Upload $post") UploadFileRemoteOperation( post.file.absolutePath, SHINOBOORU_REMOTE_PATH + post.file.name, post.getMIMEType(), (post.file.lastModified() / 1000).toString() ).execute(client).let { result -> if (!result.isSuccess) { Timber.e("Uploaded failed $result") Result.error(result.exception) } else { Timber.d("Uploaded $result") Result.success(Unit) } } } }.forEach { it.await().fold({ currentProgress = currentProgress.copy(postsUploaded = currentProgress.postsUploaded + 1) progressChannel.offer(currentProgress) }, { exception -> currentProgress = currentProgress.copy(postsUploaded = currentProgress.postsUploaded + 1, error = exception) progressChannel.offer(currentProgress) }) } progressChannel.close() } progressChannel } override suspend fun download(posts: List<CloudPost>): Result<ReceiveChannel<DownloadProgress>, Exception> = getClient().map { client -> CoroutineScope(coroutineContext).produce(networkDispatcher) { var currentProgress = DownloadProgress(posts.size, 0, null) posts.map { post -> async { DownloadFileRemoteOperation( post.remotePath, syncDir.absolutePath ).execute(client).let { result -> if (!result.isSuccess) { Timber.e("Download failed $result") Result.error(result.exception) } else { Timber.d("Download $result") val syncFile = File(syncDir.absolutePath + post.remotePath) val fileDst = dataSource.getFileDestinationFor(post.fileName) syncFile.renameTo(fileDst) Timber.d("Download $fileDst") DownloadedPost.postFromName(fileDst).mapError { Timber.e("Failed to parse file $fileDst, deleting it.") fileDst.delete() it } } } } }.forEach { Timber.e("Await $it") it.await().fold({ Timber.e("Downloaded $it") currentProgress = currentProgress.copy(postsDownloaded = currentProgress.postsDownloaded + 1) offer(currentProgress) }, { exception -> Timber.e("Downloaded $exception") currentProgress = currentProgress.copy(postsDownloaded = currentProgress.postsDownloaded + 1, error = exception) offer(currentProgress) }) } dataSource.refreshLocalPosts() close() } } override suspend fun remove(posts: List<DownloadedPost>): Result<Unit, Exception> = withContext(Dispatchers.IO) { Result.of<Unit, Exception> { getClient().flatMap { client -> posts.forEach { post -> Timber.d("Remove $post") RemoveFileRemoteOperation( SHINOBOORU_REMOTE_PATH + "/" + post.file.name ).execute(client).let { result -> if (!result.isSuccess) { Timber.e("Remove failed $result") return@flatMap Result.error(result.exception) } else { Timber.d("Removed $result") } } } Result.success(Unit) } } } override suspend fun fetchData(): Result<List<CloudPost>, Exception> = withContext(Dispatchers.IO) { getClient().flatMap { client -> val res = ReadFolderRemoteOperation(SHINOBOORU_REMOTE_PATH).execute(client) when { res.isSuccess -> { val remoteFiles = res.data as ArrayList<RemoteFile> val list = remoteFiles.filter { !it.remotePath.endsWith("/") }.mapNotNull { val createPostResult = CloudPost.fromRemotePath( it.remotePath, it.remotePath.removePrefix(SHINOBOORU_REMOTE_PATH) ) if (createPostResult is Result.Success) { createPostResult.get() } else { createPostResult as Result.Failure Timber.e(createPostResult.error, "Failed to load ${it.remotePath}") null } } Result.success(list) } res.code == RemoteOperationResult.ResultCode.FILE_NOT_FOUND -> { val createRes = CreateFolderRemoteOperation(SHINOBOORU_REMOTE_PATH, true) .execute(client) when { createRes.isSuccess -> { Result.success(emptyList()) } createRes.exception != null -> { Result.error(createRes.exception) } else -> { Result.error(IllegalArgumentException("Create root dir failed with unknown code $createRes")) } } } res.exception != null -> { Result.error(res.exception) } else -> { Result.error(IllegalArgumentException("Unhandled result code ${res.code}")) } } } } }
app/src/main/java/com/github/firenox89/shinobooru/cloud/NextCloudSyncer.kt
1510357261
// IS_APPLICABLE: false // ERROR: 'operator' modifier is inapplicable on this function: must have no value parameters fun test() { class Test { operator fun unaryPlus(vararg a: Int): Test = Test() } val test = Test() test.unaryPl<caret>us(0) }
plugins/kotlin/idea/tests/testData/intentions/conventionNameCalls/replaceCallWithUnaryOperator/unacceptableVararg.kt
2385199074
class A : B({ "${<selection>C.c</selection>}" }) class C() { companion object { val c = 23 } } open class B(param: () -> String)
plugins/kotlin/idea/tests/testData/refactoring/introduceParameter/superCallArgument.kt
176269980
// 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.compilerPlugin.kotlinxSerialization import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.idea.artifacts.KotlinArtifactNames import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts import org.jetbrains.kotlin.idea.facet.KotlinFacet import java.io.File object KotlinSerializationImportHandler { val PLUGIN_JPS_JAR: String by lazy { KotlinArtifacts.instance.kotlinxSerializationCompilerPlugin.absolutePath } fun isPluginJarPath(path: String): Boolean { return path.endsWith(KotlinArtifactNames.KOTLINX_SERIALIZATION_COMPILER_PLUGIN) } fun modifyCompilerArguments(facet: KotlinFacet, buildSystemPluginJar: String) { val facetSettings = facet.configuration.settings val commonArguments = facetSettings.compilerArguments ?: CommonCompilerArguments.DummyImpl() var pluginWasEnabled = false val oldPluginClasspaths = (commonArguments.pluginClasspaths ?: emptyArray()).filterTo(mutableListOf()) { val lastIndexOfFile = it.lastIndexOfAny(charArrayOf('/', File.separatorChar)) if (lastIndexOfFile < 0) { return@filterTo true } val match = it.drop(lastIndexOfFile + 1).matches("$buildSystemPluginJar-.*\\.jar".toRegex()) if (match) pluginWasEnabled = true !match } val newPluginClasspaths = if (pluginWasEnabled) oldPluginClasspaths + PLUGIN_JPS_JAR else oldPluginClasspaths commonArguments.pluginClasspaths = newPluginClasspaths.toTypedArray() facetSettings.compilerArguments = commonArguments } }
plugins/kotlin/compiler-plugins/kotlinx-serialization/common/src/org/jetbrains/kotlin/idea/compilerPlugin/kotlinxSerialization/KotlinSerializationImportHandler.kt
2754586779
// 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.workspaceModel.ide.impl.legacyBridge.module.roots import com.intellij.configurationStore.serializeStateInto import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.ModuleOrderEnumerator import com.intellij.openapi.roots.impl.RootConfigurationAccessor import com.intellij.openapi.roots.impl.RootModelBase.CollectDependentModules import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtilRt import com.intellij.util.SmartList import com.intellij.util.isEmpty import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.getInstance import com.intellij.workspaceModel.ide.impl.legacyBridge.LegacyBridgeModifiableBase import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity import com.intellij.workspaceModel.ide.legacyBridge.ModifiableRootModelBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleExtensionBridge import com.intellij.workspaceModel.storage.CachedValue import com.intellij.workspaceModel.storage.WorkspaceEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jdom.Element import org.jetbrains.jps.model.module.JpsModuleSourceRoot import org.jetbrains.jps.model.module.JpsModuleSourceRootType import java.util.concurrent.ConcurrentHashMap internal class ModifiableRootModelBridgeImpl( diff: WorkspaceEntityStorageBuilder, override val moduleBridge: ModuleBridge, override val accessor: RootConfigurationAccessor, cacheStorageResult: Boolean = true ) : LegacyBridgeModifiableBase(diff, cacheStorageResult), ModifiableRootModelBridge, ModuleRootModelBridge { /* We save the module entity for the following case: - Modifiable model created - module disposed - modifiable model used This case can appear, for example, during maven import moduleEntity would be removed from this diff after module disposing */ private var savedModuleEntity: ModuleEntity init { savedModuleEntity = getModuleEntity(entityStorageOnDiff.current, module) ?: error("Cannot find module entity for ${module.moduleEntityId}. Bridge: '$moduleBridge'. Store: $diff") } private fun getModuleEntity(current: WorkspaceEntityStorage, myModuleBridge: ModuleBridge): ModuleEntity? { // Try to get entity by module id // In some cases this won't work. These cases can happen during maven or gradle import where we provide a general builder. // The case: we rename the module. Since the changes not yet committed, the module will remain with the old persistentId. After that // we try to get modifiableRootModel. In general case it would work fine because the builder will be based on main store, but // in case of gradle/maven import we take the builder that was used for renaming. So, the old name cannot be found in the new store. return current.resolve(myModuleBridge.moduleEntityId) ?: current.findModuleEntity(myModuleBridge) } override fun getModificationCount(): Long = diff.modificationCount private val extensionsDisposable = Disposer.newDisposable() private val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(project) private val extensionsDelegate = lazy { RootModelBridgeImpl.loadExtensions(storage = entityStorageOnDiff, module = module, diff = diff, writable = true, parentDisposable = extensionsDisposable) } private val extensions by extensionsDelegate private val sourceRootPropertiesMap = ConcurrentHashMap<VirtualFileUrl, JpsModuleSourceRoot>() internal val moduleEntity: ModuleEntity get() { val actualModuleEntity = getModuleEntity(entityStorageOnDiff.current, module) ?: return savedModuleEntity savedModuleEntity = actualModuleEntity return actualModuleEntity } private val moduleLibraryTable = ModifiableModuleLibraryTableBridge(this) /** * Contains instances of OrderEntries edited via [ModifiableRootModel] interfaces; we need to keep references to them to update their indices; * it should be used for modifications only, in order to read actual state one need to use [orderEntriesArray]. */ private val mutableOrderEntries: ArrayList<OrderEntryBridge> by lazy { ArrayList<OrderEntryBridge>().also { addOrderEntries(moduleEntity.dependencies, it) } } /** * Provides cached value for [mutableOrderEntries] converted to an array to avoid creating array each time [getOrderEntries] is called; * also it updates instances in [mutableOrderEntries] when underlying entities are changed via [WorkspaceModel] interface (e.g. when a * library referenced from [LibraryOrderEntry] is renamed). */ private val orderEntriesArrayValue: CachedValue<Array<OrderEntry>> = CachedValue { storage -> val dependencies = storage.findModuleEntity(module)?.dependencies ?: return@CachedValue emptyArray() if (mutableOrderEntries.size == dependencies.size) { //keep old instances of OrderEntries if possible (i.e. if only some properties of order entries were changes via WorkspaceModel) for (i in mutableOrderEntries.indices) { if (dependencies[i] != mutableOrderEntries[i].item && dependencies[i].javaClass == mutableOrderEntries[i].item.javaClass) { mutableOrderEntries[i].item = dependencies[i] } } } else { mutableOrderEntries.clear() addOrderEntries(dependencies, mutableOrderEntries) } mutableOrderEntries.toTypedArray() } private val orderEntriesArray get() = entityStorageOnDiff.cachedValue(orderEntriesArrayValue) private fun addOrderEntries(dependencies: List<ModuleDependencyItem>, target: MutableList<OrderEntryBridge>) = dependencies.mapIndexedTo(target) { index, item -> RootModelBridgeImpl.toOrderEntry(item, index, this, this::updateDependencyItem) } private val contentEntriesImplValue: CachedValue<List<ModifiableContentEntryBridge>> = CachedValue { storage -> val moduleEntity = storage.findModuleEntity(module) ?: return@CachedValue emptyList<ModifiableContentEntryBridge>() val contentEntries = moduleEntity.contentRoots.sortedBy { it.url.url }.toList() contentEntries.map { ModifiableContentEntryBridge( diff = diff, contentEntryUrl = it.url, modifiableRootModel = this ) } } private fun updateDependencyItem(index: Int, transformer: (ModuleDependencyItem) -> ModuleDependencyItem) { val oldItem = moduleEntity.dependencies[index] val newItem = transformer(oldItem) if (oldItem == newItem) return diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { val copy = dependencies.toMutableList() copy[index] = newItem dependencies = copy } } override val storage: WorkspaceEntityStorage get() = entityStorageOnDiff.current override fun getOrCreateJpsRootProperties(sourceRootUrl: VirtualFileUrl, creator: () -> JpsModuleSourceRoot): JpsModuleSourceRoot { return sourceRootPropertiesMap.computeIfAbsent(sourceRootUrl) { creator() } } override fun removeCachedJpsRootProperties(sourceRootUrl: VirtualFileUrl) { sourceRootPropertiesMap.remove(sourceRootUrl) } private val contentEntries get() = entityStorageOnDiff.cachedValue(contentEntriesImplValue) override fun getProject(): Project = moduleBridge.project override fun addContentEntry(root: VirtualFile): ContentEntry = addContentEntry(root.url) override fun addContentEntry(url: String): ContentEntry { assertModelIsLive() val virtualFileUrl = virtualFileManager.fromUrl(url) val existingEntry = contentEntries.firstOrNull { it.contentEntryUrl == virtualFileUrl } if (existingEntry != null) { return existingEntry } diff.addContentRootEntity( module = moduleEntity, excludedUrls = emptyList(), excludedPatterns = emptyList(), url = virtualFileUrl ) // TODO It's N^2 operations since we need to recreate contentEntries every time return contentEntries.firstOrNull { it.contentEntryUrl == virtualFileUrl } ?: error("addContentEntry: unable to find content entry after adding: $url to module ${moduleEntity.name}") } override fun removeContentEntry(entry: ContentEntry) { assertModelIsLive() val entryImpl = entry as ModifiableContentEntryBridge val contentEntryUrl = entryImpl.contentEntryUrl val entity = currentModel.contentEntities.firstOrNull { it.url == contentEntryUrl } ?: error("ContentEntry $entry does not belong to modifiableRootModel of module ${moduleBridge.name}") entry.clearSourceFolders() diff.removeEntity(entity) if (assertChangesApplied && contentEntries.any { it.url == contentEntryUrl.url }) { error("removeContentEntry: removed content entry url '$contentEntryUrl' still exists after removing") } } override fun addOrderEntry(orderEntry: OrderEntry) { assertModelIsLive() when (orderEntry) { is LibraryOrderEntryBridge -> { if (orderEntry.isModuleLevel) { moduleLibraryTable.addLibraryCopy(orderEntry.library as LibraryBridgeImpl, orderEntry.isExported, orderEntry.libraryDependencyItem.scope) } else { appendDependency(orderEntry.libraryDependencyItem) } } is ModuleOrderEntry -> orderEntry.module?.let { addModuleOrderEntry(it) } ?: error("Module is empty: $orderEntry") is ModuleSourceOrderEntry -> appendDependency(ModuleDependencyItem.ModuleSourceDependency) is InheritedJdkOrderEntry -> appendDependency(ModuleDependencyItem.InheritedSdkDependency) is ModuleJdkOrderEntry -> appendDependency((orderEntry as SdkOrderEntryBridge).sdkDependencyItem) else -> error("OrderEntry should not be extended by external systems") } } override fun addLibraryEntry(library: Library): LibraryOrderEntry { appendDependency(ModuleDependencyItem.Exportable.LibraryDependency( library = library.libraryId, exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE )) return (mutableOrderEntries.lastOrNull() as? LibraryOrderEntry ?: error("Unable to find library orderEntry after adding")) } private val Library.libraryId: LibraryId get() { val libraryId = if (this is LibraryBridge) libraryId else { val libraryName = name if (libraryName.isNullOrEmpty()) { error("Library name is null or empty: ${this}") } LibraryId(libraryName, LibraryNameGenerator.getLibraryTableId(table.tableLevel)) } return libraryId } override fun addLibraryEntries(libraries: List<Library>, scope: DependencyScope, exported: Boolean) { val dependencyScope = scope.toEntityDependencyScope() appendDependencies(libraries.map { ModuleDependencyItem.Exportable.LibraryDependency(it.libraryId, exported, dependencyScope) }) } override fun addInvalidLibrary(name: String, level: String): LibraryOrderEntry { val libraryDependency = ModuleDependencyItem.Exportable.LibraryDependency( library = LibraryId(name, LibraryNameGenerator.getLibraryTableId(level)), exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE ) appendDependency(libraryDependency) return (mutableOrderEntries.lastOrNull() as? LibraryOrderEntry ?: error("Unable to find library orderEntry after adding")) } override fun addModuleOrderEntry(module: Module): ModuleOrderEntry { val moduleDependency = ModuleDependencyItem.Exportable.ModuleDependency( module = (module as ModuleBridge).moduleEntityId, productionOnTest = false, exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE ) appendDependency(moduleDependency) return mutableOrderEntries.lastOrNull() as? ModuleOrderEntry ?: error("Unable to find module orderEntry after adding") } override fun addModuleEntries(modules: MutableList<Module>, scope: DependencyScope, exported: Boolean) { val dependencyScope = scope.toEntityDependencyScope() appendDependencies(modules.map { ModuleDependencyItem.Exportable.ModuleDependency((it as ModuleBridge).moduleEntityId, exported, dependencyScope, productionOnTest = false) }) } override fun addInvalidModuleEntry(name: String): ModuleOrderEntry { val moduleDependency = ModuleDependencyItem.Exportable.ModuleDependency( module = ModuleId(name), productionOnTest = false, exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE ) appendDependency(moduleDependency) return mutableOrderEntries.lastOrNull() as? ModuleOrderEntry ?: error("Unable to find module orderEntry after adding") } internal fun appendDependency(dependency: ModuleDependencyItem) { mutableOrderEntries.add(RootModelBridgeImpl.toOrderEntry(dependency, mutableOrderEntries.size, this, this::updateDependencyItem)) entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = dependencies + dependency } } internal fun appendDependencies(dependencies: List<ModuleDependencyItem>) { for (dependency in dependencies) { mutableOrderEntries.add(RootModelBridgeImpl.toOrderEntry(dependency, mutableOrderEntries.size, this, this::updateDependencyItem)) } entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { this.dependencies = this.dependencies + dependencies } } internal fun insertDependency(dependency: ModuleDependencyItem, position: Int): OrderEntryBridge { val last = position == mutableOrderEntries.size val newEntry = RootModelBridgeImpl.toOrderEntry(dependency, position, this, this::updateDependencyItem) if (last) { mutableOrderEntries.add(newEntry) } else { mutableOrderEntries.add(position, newEntry) for (i in position + 1 until mutableOrderEntries.size) { mutableOrderEntries[i].updateIndex(i) } } entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = if (last) dependencies + dependency else dependencies.subList(0, position) + dependency + dependencies.subList(position, dependencies.size) } return newEntry } internal fun removeDependencies(filter: (Int, ModuleDependencyItem) -> Boolean) { val newDependencies = ArrayList<ModuleDependencyItem>() val newOrderEntries = ArrayList<OrderEntryBridge>() val oldDependencies = moduleEntity.dependencies for (i in oldDependencies.indices) { if (!filter(i, oldDependencies[i])) { newDependencies.add(oldDependencies[i]) val entryBridge = mutableOrderEntries[i] entryBridge.updateIndex(newOrderEntries.size) newOrderEntries.add(entryBridge) } } mutableOrderEntries.clear() mutableOrderEntries.addAll(newOrderEntries) entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = newDependencies } } override fun findModuleOrderEntry(module: Module): ModuleOrderEntry? { return orderEntries.filterIsInstance<ModuleOrderEntry>().firstOrNull { module == it.module } } override fun findLibraryOrderEntry(library: Library): LibraryOrderEntry? { if (library is LibraryBridge) { val libraryIdToFind = library.libraryId return orderEntries .filterIsInstance<LibraryOrderEntry>() .firstOrNull { libraryIdToFind == (it.library as? LibraryBridge)?.libraryId } } else { return orderEntries.filterIsInstance<LibraryOrderEntry>().firstOrNull { it.library == library } } } override fun removeOrderEntry(orderEntry: OrderEntry) { assertModelIsLive() val entryImpl = orderEntry as OrderEntryBridge val item = entryImpl.item if (mutableOrderEntries.none { it.item == item }) { LOG.error("OrderEntry $item does not belong to modifiableRootModel of module ${moduleBridge.name}") return } if (orderEntry is LibraryOrderEntryBridge && orderEntry.isModuleLevel) { moduleLibraryTable.removeLibrary(orderEntry.library as LibraryBridge) } else { val itemIndex = entryImpl.currentIndex removeDependencies { index, _ -> index == itemIndex } } } override fun rearrangeOrderEntries(newOrder: Array<out OrderEntry>) { val newOrderEntries = newOrder.mapTo(ArrayList()) { it as OrderEntryBridge } val newEntities = newOrderEntries.map { it.item } if (newEntities.toSet() != moduleEntity.dependencies.toSet()) { error("Expected the same entities as existing order entries, but in a different order") } mutableOrderEntries.clear() mutableOrderEntries.addAll(newOrderEntries) for (i in mutableOrderEntries.indices) { mutableOrderEntries[i].updateIndex(i) } entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = newEntities } } override fun clear() { for (library in moduleLibraryTable.libraries) { moduleLibraryTable.removeLibrary(library) } val currentSdk = sdk val jdkItem = currentSdk?.let { ModuleDependencyItem.SdkDependency(it.name, it.sdkType.name) } if (moduleEntity.dependencies != listOfNotNull(jdkItem, ModuleDependencyItem.ModuleSourceDependency)) { removeDependencies { _, _ -> true } if (jdkItem != null) { appendDependency(jdkItem) } appendDependency(ModuleDependencyItem.ModuleSourceDependency) } for (contentRoot in moduleEntity.contentRoots) { diff.removeEntity(contentRoot) } } fun collectChangesAndDispose(): WorkspaceEntityStorageBuilder? { assertModelIsLive() Disposer.dispose(moduleLibraryTable) if (!isChanged) { moduleLibraryTable.restoreLibraryMappingsAndDisposeCopies() disposeWithoutLibraries() return null } if (extensionsDelegate.isInitialized() && extensions.any { it.isChanged }) { val element = Element("component") for (extension in extensions) { if (extension is ModuleExtensionBridge) continue extension.commit() if (extension is PersistentStateComponent<*>) { serializeStateInto(extension, element) } else { @Suppress("DEPRECATION") extension.writeExternal(element) } } val elementAsString = JDOMUtil.writeElement(element) val customImlDataEntity = moduleEntity.customImlData if (customImlDataEntity?.rootManagerTagCustomData != elementAsString) { when { customImlDataEntity == null && !element.isEmpty() -> diff.addModuleCustomImlDataEntity( module = moduleEntity, rootManagerTagCustomData = elementAsString, customModuleOptions = emptyMap(), source = moduleEntity.entitySource ) customImlDataEntity == null && element.isEmpty() -> Unit customImlDataEntity != null && customImlDataEntity.customModuleOptions.isEmpty() && element.isEmpty() -> diff.removeEntity(customImlDataEntity) customImlDataEntity != null && customImlDataEntity.customModuleOptions.isNotEmpty() && element.isEmpty() -> diff.modifyEntity(ModifiableModuleCustomImlDataEntity::class.java, customImlDataEntity) { rootManagerTagCustomData = null } customImlDataEntity != null && !element.isEmpty() -> diff.modifyEntity(ModifiableModuleCustomImlDataEntity::class.java, customImlDataEntity) { rootManagerTagCustomData = elementAsString } else -> error("Should not be reached") } } } if (!sourceRootPropertiesMap.isEmpty()) { for (sourceRoot in moduleEntity.sourceRoots) { val actualSourceRootData = sourceRootPropertiesMap[sourceRoot.url] ?: continue SourceRootPropertiesHelper.applyChanges(diff, sourceRoot, actualSourceRootData) } } disposeWithoutLibraries() return diff } private fun areSourceRootPropertiesChanged(): Boolean { if (sourceRootPropertiesMap.isEmpty()) return false return moduleEntity.sourceRoots.any { sourceRoot -> val actualSourceRootData = sourceRootPropertiesMap[sourceRoot.url] actualSourceRootData != null && !SourceRootPropertiesHelper.hasEqualProperties(sourceRoot, actualSourceRootData) } } override fun commit() { val diff = collectChangesAndDispose() ?: return val moduleDiff = module.diff if (moduleDiff != null) { moduleDiff.addDiff(diff) } else { WorkspaceModel.getInstance(project).updateProjectModel { it.addDiff(diff) } } postCommit() } override fun prepareForCommit() { collectChangesAndDispose() } override fun postCommit() { moduleLibraryTable.disposeOriginalLibrariesAndUpdateCopies() } override fun dispose() { disposeWithoutLibraries() moduleLibraryTable.restoreLibraryMappingsAndDisposeCopies() Disposer.dispose(moduleLibraryTable) } private fun disposeWithoutLibraries() { if (!modelIsCommittedOrDisposed) { Disposer.dispose(extensionsDisposable) } // No assertions here since it is ok to call dispose twice or more modelIsCommittedOrDisposed = true } override fun getModuleLibraryTable(): LibraryTable = moduleLibraryTable override fun setSdk(jdk: Sdk?) { if (jdk == null) { setSdkItem(null) if (assertChangesApplied && sdkName != null) { error("setSdk: expected sdkName is null, but got: $sdkName") } } else { if (ModifiableRootModelBridge.findSdk(jdk.name, jdk.sdkType.name) == null) { error("setSdk: sdk '${jdk.name}' type '${jdk.sdkType.name}' is not registered in ProjectJdkTable") } setInvalidSdk(jdk.name, jdk.sdkType.name) } } override fun setInvalidSdk(sdkName: String, sdkType: String) { setSdkItem(ModuleDependencyItem.SdkDependency(sdkName, sdkType)) if (assertChangesApplied && getSdkName() != sdkName) { error("setInvalidSdk: expected sdkName '$sdkName' but got '${getSdkName()}' after doing a change") } } override fun inheritSdk() { if (isSdkInherited) return setSdkItem(ModuleDependencyItem.InheritedSdkDependency) if (assertChangesApplied && !isSdkInherited) { error("inheritSdk: Sdk is still not inherited after inheritSdk()") } } // TODO compare by actual values override fun isChanged(): Boolean { if (!diff.isEmpty()) return true if (extensionsDelegate.isInitialized() && extensions.any { it.isChanged }) return true if (areSourceRootPropertiesChanged()) return true return false } override fun isWritable(): Boolean = true override fun <T : OrderEntry?> replaceEntryOfType(entryClass: Class<T>, entry: T) = throw NotImplementedError("Not implemented since it was used only by project model implementation") override fun getSdkName(): String? = orderEntries.filterIsInstance<JdkOrderEntry>().firstOrNull()?.jdkName // TODO override fun isDisposed(): Boolean = modelIsCommittedOrDisposed private fun setSdkItem(item: ModuleDependencyItem?) { removeDependencies { _, it -> it is ModuleDependencyItem.InheritedSdkDependency || it is ModuleDependencyItem.SdkDependency } if (item != null) { insertDependency(item, 0) } } private val modelValue = CachedValue { storage -> RootModelBridgeImpl( moduleEntity = getModuleEntity(storage, moduleBridge), storage = entityStorageOnDiff, itemUpdater = null, rootModel = this, updater = { transformer -> transformer(diff) } ) } internal val currentModel get() = entityStorageOnDiff.cachedValue(modelValue) override fun getExcludeRoots(): Array<VirtualFile> = currentModel.excludeRoots override fun orderEntries(): OrderEnumerator = ModuleOrderEnumerator(this, null) override fun <T : Any?> getModuleExtension(klass: Class<T>): T? { return extensions.filterIsInstance(klass).firstOrNull() } override fun getDependencyModuleNames(): Array<String> { val result = orderEntries().withoutSdk().withoutLibraries().withoutModuleSourceEntries().process(CollectDependentModules(), ArrayList()) return ArrayUtilRt.toStringArray(result) } override fun getModule(): ModuleBridge = moduleBridge override fun isSdkInherited(): Boolean = orderEntriesArray.any { it is InheritedJdkOrderEntry } override fun getOrderEntries(): Array<OrderEntry> = orderEntriesArray override fun getSourceRootUrls(): Array<String> = currentModel.sourceRootUrls override fun getSourceRootUrls(includingTests: Boolean): Array<String> = currentModel.getSourceRootUrls(includingTests) override fun getContentEntries(): Array<ContentEntry> = contentEntries.toTypedArray() override fun getExcludeRootUrls(): Array<String> = currentModel.excludeRootUrls override fun <R : Any?> processOrder(policy: RootPolicy<R>, initialValue: R): R { var result = initialValue for (orderEntry in orderEntries) { result = orderEntry.accept(policy, result) } return result } override fun getSdk(): Sdk? = (orderEntriesArray.find { it is JdkOrderEntry } as JdkOrderEntry?)?.jdk override fun getSourceRoots(): Array<VirtualFile> = currentModel.sourceRoots override fun getSourceRoots(includingTests: Boolean): Array<VirtualFile> = currentModel.getSourceRoots(includingTests) override fun getSourceRoots(rootType: JpsModuleSourceRootType<*>): MutableList<VirtualFile> = currentModel.getSourceRoots(rootType) override fun getSourceRoots(rootTypes: MutableSet<out JpsModuleSourceRootType<*>>): MutableList<VirtualFile> = currentModel.getSourceRoots(rootTypes) override fun getContentRoots(): Array<VirtualFile> = currentModel.contentRoots override fun getContentRootUrls(): Array<String> = currentModel.contentRootUrls override fun getModuleDependencies(): Array<Module> = getModuleDependencies(true) override fun getModuleDependencies(includeTests: Boolean): Array<Module> { var result: MutableList<Module>? = null for (entry in orderEntriesArray) { if (entry is ModuleOrderEntry) { val scope = entry.scope if (includeTests || scope.isForProductionCompile || scope.isForProductionRuntime) { val module = entry.module if (module != null) { if (result == null) { result = SmartList() } result.add(module) } } } } return if (result.isNullOrEmpty()) Module.EMPTY_ARRAY else result.toTypedArray() } companion object { private val LOG = logger<ModifiableRootModelBridgeImpl>() } }
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModifiableRootModelBridgeImpl.kt
1879228477
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.setType import org.jetbrains.kotlin.idea.formatter.adjustLineIndent import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.isNullabilityFlexible import org.jetbrains.kotlin.types.typeUtil.isNothing import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.types.typeUtil.makeNotNullable class ConvertToBlockBodyIntention : SelfTargetingIntention<KtDeclarationWithBody>( KtDeclarationWithBody::class.java, KotlinBundle.lazyMessage("convert.to.block.body") ) { override fun isApplicableTo(element: KtDeclarationWithBody, caretOffset: Int): Boolean { if (element is KtFunctionLiteral || element.hasBlockBody() || !element.hasBody()) return false when (element) { is KtNamedFunction -> { val returnType = element.returnType() ?: return false if (!element.hasDeclaredReturnType() && returnType.isError) return false// do not convert when type is implicit and unknown return true } is KtPropertyAccessor -> return true else -> error("Unknown declaration type: $element") } } override fun allowCaretInsideElement(element: PsiElement) = element !is KtDeclaration && super.allowCaretInsideElement(element) override fun applyTo(element: KtDeclarationWithBody, editor: Editor?) { convert(element, true) } companion object { fun convert(declaration: KtDeclarationWithBody, withReformat: Boolean = false): KtDeclarationWithBody { val body = declaration.bodyExpression!! fun generateBody(returnsValue: Boolean): KtExpression { val bodyType = body.analyze().getType(body) val factory = KtPsiFactory(declaration) if (bodyType != null && bodyType.isUnit() && body is KtNameReferenceExpression) return factory.createEmptyBody() val unitWhenAsResult = (bodyType == null || bodyType.isUnit()) && body.resultingWhens().isNotEmpty() val needReturn = returnsValue && (bodyType == null || (!bodyType.isUnit() && !bodyType.isNothing())) return if (needReturn || unitWhenAsResult) { val annotatedExpr = body as? KtAnnotatedExpression val returnedExpr = annotatedExpr?.baseExpression ?: body val block = factory.createSingleStatementBlock(factory.createExpressionByPattern("return $0", returnedExpr)) val statement = block.firstStatement annotatedExpr?.annotationEntries?.forEach { block.addBefore(it, statement) block.addBefore(factory.createNewLine(), statement) } block } else { factory.createSingleStatementBlock(body) } } val newBody = when (declaration) { is KtNamedFunction -> { val returnType = declaration.returnType()!! if (!declaration.hasDeclaredReturnType() && !returnType.isUnit()) { declaration.setType(returnType) } generateBody(!returnType.isUnit() && !returnType.isNothing()) } is KtPropertyAccessor -> { val parent = declaration.parent if (parent is KtProperty && parent.typeReference == null) { val descriptor = parent.resolveToDescriptorIfAny() (descriptor as? CallableDescriptor)?.returnType?.let { parent.setType(it) } } generateBody(declaration.isGetter) } else -> throw RuntimeException("Unknown declaration type: $declaration") } declaration.equalsToken!!.delete() val replaced = body.replace(newBody) if (withReformat) declaration.containingKtFile.adjustLineIndent(replaced.startOffset, replaced.endOffset) return declaration } private fun KtNamedFunction.returnType(): KotlinType? { val descriptor = resolveToDescriptorIfAny() val returnType = descriptor?.returnType ?: return null if (returnType.isNullabilityFlexible() && descriptor.overriddenDescriptors.firstOrNull()?.returnType?.isMarkedNullable == false ) return returnType.makeNotNullable() return returnType } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToBlockBodyIntention.kt
2881016602
class TestFromJava() : BaseJava() { override fun testMethod() { } } fun test() { BaseJava().testMethod<caret>() } // REF: (in TestFromJava).testMethod() // REF: of BaseJava.testMethod()
plugins/kotlin/idea/tests/testData/navigation/implementations/multifile/ImplementMethodInKotlin/ImplementMethodInKotlin.kt
734628590
// INTENTION_TEXT: Add @TargetApi(LOLLIPOP) Annotation // INSPECTION_CLASS: com.android.tools.idea.lint.AndroidLintNewApiInspection import android.graphics.drawable.VectorDrawable fun withDefaultParameter(vector: VectorDrawable = <caret>VectorDrawable()) { }
plugins/kotlin/idea/tests/testData/android/lintQuickfix/targetApi/defaultParameter.kt
1886014040
// 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.filePrediction.features.history.ngram import com.intellij.internal.ml.ngram.NGramIncrementalModelRunner import com.intellij.internal.ml.ngram.VocabularyWithLimit import junit.framework.TestCase internal class FilePredictionRunnerAssertion { private var withVocabulary: Boolean = false private var vocabularySize: Int = 3 private var withFileSequence: Boolean = false private var fileSequence: List<Int> = emptyList() private var withRecentFiles: Boolean = false private var nextFileSequenceIdx: Int = -1 private var recentFiles: List<String> = emptyList() private var recentFilesIdx: List<Int> = emptyList() fun withVocabulary(size: Int): FilePredictionRunnerAssertion { withVocabulary = true vocabularySize = size return this } fun withFileSequence(files: List<Int>): FilePredictionRunnerAssertion { withFileSequence = true fileSequence = files return this } fun withRecentFiles(nextIdx: Int, recent: List<String>, idx: List<Int>): FilePredictionRunnerAssertion { withRecentFiles = true nextFileSequenceIdx = nextIdx recentFiles = recent recentFilesIdx = idx return this } fun assert(runner: NGramIncrementalModelRunner) { TestCase.assertTrue(runner.vocabulary is VocabularyWithLimit) val vocabulary = runner.vocabulary as VocabularyWithLimit if (withVocabulary) { // unknown token is always added to wordIndices, therefore, actual size will be always size + 1 TestCase.assertEquals(vocabularySize, vocabulary.wordIndices.size - 1) } if (withFileSequence) { val actualFileSequence = vocabulary.recentSequence.subListFromStart(vocabulary.recentSequence.size()) TestCase.assertEquals("File sequence is different from expected", fileSequence, actualFileSequence) } if (withRecentFiles) { val recent = vocabulary.recent TestCase.assertEquals("Next file sequence index is different from expected", nextFileSequenceIdx, recent.lastIndex() + 1) val tokens = recent.getRecentTokens() TestCase.assertEquals("Recent files are different from expected", recentFiles, tokens.map { it.first }) TestCase.assertEquals("Recent files indices are different from expected", recentFilesIdx, tokens.map { it.second }) } } }
plugins/filePrediction/test/com/intellij/filePrediction/features/history/ngram/FilePredictionRunnerAssertion.kt
1058997099
// 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.ide.konan import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.idea.configuration.LibraryKindSearchScope import org.jetbrains.kotlin.idea.configuration.hasKotlinFilesOnlyInTests import org.jetbrains.kotlin.idea.util.runReadActionInSmartMode import org.jetbrains.kotlin.idea.vfilefinder.KlibMetaFileIndex import org.jetbrains.kotlin.idea.vfilefinder.hasSomethingInPackage import org.jetbrains.kotlin.name.FqName fun hasKotlinNativeRuntimeInScope(module: Module): Boolean = module.project.runReadActionInSmartMode { val scope = module.getModuleWithDependenciesAndLibrariesScope(hasKotlinFilesOnlyInTests(module)) hasKotlinNativeMetadataFile(module.project, LibraryKindSearchScope(module, scope, NativeLibraryKind)) } private val KOTLIN_NATIVE_FQ_NAME = FqName("kotlin.native") fun hasKotlinNativeMetadataFile(project: Project, scope: GlobalSearchScope): Boolean = project.runReadActionInSmartMode { KlibMetaFileIndex.hasSomethingInPackage(KOTLIN_NATIVE_FQ_NAME, scope) }
plugins/kotlin/native/src/org/jetbrains/kotlin/ide/konan/KotlinNativeModuleConfigurator.kt
1872541603
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.annotator.intentions import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.SmartPsiElementPointer import com.intellij.psi.util.createSmartPointer import org.jetbrains.plugins.groovy.GroovyBundle.message import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory import org.jetbrains.plugins.groovy.lang.psi.api.GrBlockLambdaBody import org.jetbrains.plugins.groovy.lang.psi.api.GrLambdaExpression class ConvertLambdaToClosureAction(lambda: GrLambdaExpression) : IntentionAction { private val myLambda: SmartPsiElementPointer<GrLambdaExpression> = lambda.createSmartPointer() override fun getText(): String = familyName override fun getFamilyName(): String = message("action.convert.lambda.to.closure") override fun startInWriteAction(): Boolean = true override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = myLambda.element != null override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { val lambda = myLambda.element ?: return val closureText = closureText(lambda) ?: return val closure = GroovyPsiElementFactory.getInstance(project).createClosureFromText(closureText) lambda.replaceWithExpression(closure, false) } private fun closureText(lambda: GrLambdaExpression): String? { val parameterList = lambda.parameterList val body = lambda.body ?: return null val closureText = StringBuilder() closureText.append("{") if (parameterList.parametersCount != 0) { appendTextBetween(closureText, parameterList.text, parameterList.lParen, parameterList.rParen) } appendElements(closureText, parameterList, body) if (body is GrBlockLambdaBody) { appendTextBetween(closureText, body.text, body.lBrace, body.rBrace) } else { closureText.append(body.text) } closureText.append("}") return closureText.toString() } }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/intentions/ConvertLambdaToClosureAction.kt
2647989199
class MyFile class MyFileStream fun foo(myFi<caret>) // ORDER: myFile: MyFile // ORDER: myFileStream: MyFileStream
plugins/kotlin/completion/tests/testData/weighers/basic/parameterNameAndType/ShorterFirst.kt
2075285181
package com.cognifide.gradle.aem.common.instance.service.sling import com.cognifide.gradle.aem.common.instance.InstanceException open class SlingException : InstanceException { constructor(message: String, cause: Throwable) : super(message, cause) constructor(message: String) : super(message) }
src/main/kotlin/com/cognifide/gradle/aem/common/instance/service/sling/SlingException.kt
131003117
/* * Copyright [2017] [NIRVANA PRIVATE LIMITED] * * 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.zwq65.unity.data.db import com.zwq65.unity.data.db.model.DaoMaster import com.zwq65.unity.data.db.model.DaoSession import com.zwq65.unity.data.db.model.Picture import io.reactivex.Observable import javax.inject.Inject import javax.inject.Singleton /** * ================================================ * Database操作帮助类 * <p> * Created by NIRVANA on 2017/01/27. * Contact with <[email protected]> * ================================================ */ @Singleton class AppDbHelper @Inject internal constructor(dbOpenHelper: DbOpenHelper) : DbHelper { private val mDaoSession: DaoSession = DaoMaster(dbOpenHelper.writableDb).newSession() override val collectionPictures: Observable<List<Picture>> get() = Observable.fromCallable { mDaoSession.pictureDao.loadAll() } override fun savePicture(picture: Picture): Observable<Long> { return Observable.fromCallable { mDaoSession.pictureDao.insertOrReplace(picture) } } override fun deletePicture(id: String): Observable<Long> { return Observable.fromCallable { mDaoSession.pictureDao.deleteByKey(id) 1L } } override fun isPictureExist(id: String): Observable<Boolean> { return Observable.fromCallable { val picture = mDaoSession.pictureDao.load(id) picture != null } } }
app/src/main/java/com/zwq65/unity/data/db/AppDbHelper.kt
68479433
package com.xmartlabs.bigbang.core.helper.gsonadapters import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonPrimitive import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import com.xmartlabs.bigbang.core.extensions.ifException import com.xmartlabs.bigbang.core.extensions.localDateTimeFromEpochMilli import org.threeten.bp.LocalDateTime import org.threeten.bp.ZoneOffset import timber.log.Timber import java.lang.reflect.Type class MillisecondsLocalDateTimeAdapter : JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> { @Synchronized override fun serialize(dateTime: LocalDateTime?, type: Type?, jsonSerializationContext: JsonSerializationContext?) = dateTime?.toInstant(ZoneOffset.UTC) ?.toEpochMilli() .ifException(::JsonPrimitive) { Timber.e(it, "Date cannot be serialized, date='%s'", dateTime) } @Synchronized override fun deserialize(jsonElement: JsonElement?, type: Type?, jsonDeserializationContext: JsonDeserializationContext?) = jsonElement ?.let(JsonElement::toString) ?.takeIf(String::isNotEmpty) ?.let(String::toLong) ?.ifException(::localDateTimeFromEpochMilli) { Timber.e(it, "Date cannot be parsed, date='%s'", jsonElement) } }
core/src/main/java/com/xmartlabs/bigbang/core/helper/gsonadapters/MillisecondsLocalDateTimeAdapter.kt
1106985384
package eu.kanade.tachiyomi.network import android.content.Context import okhttp3.Cookie import okhttp3.CookieJar import okhttp3.HttpUrl class PersistentCookieJar(context: Context) : CookieJar { val store = PersistentCookieStore(context) override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) { store.addAll(url, cookies) } override fun loadForRequest(url: HttpUrl): List<Cookie> { return store.get(url) } }
Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/network/PersistentCookieJar.kt
2649084250
package org.maxur.mserv.frame.service.properties import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.context import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.junit.platform.runner.JUnitPlatform import org.junit.runner.RunWith import org.maxur.mserv.frame.LocatorImpl import org.maxur.mserv.frame.TestLocatorHolder import java.net.URI import kotlin.test.assertFailsWith @RunWith(JUnitPlatform::class) class NullPropertiesSpec : Spek({ describe("a unknown Properties Source") { beforeEachTest { LocatorImpl.holder = TestLocatorHolder } context("create new properties source") { val sut = NullProperties it("should throw exception when properties is read") { assertFailsWith<IllegalStateException> { sut.asString("name") } assertFailsWith<IllegalStateException> { sut.asLong("id") } assertFailsWith<IllegalStateException> { sut.asInteger("id") } assertFailsWith<IllegalStateException> { sut.asURI("url") } assertFailsWith<IllegalStateException> { sut.read("url", URI::class) } } } } })
maxur-mserv-core/src/test/kotlin/org/maxur/mserv/frame/service/properties/NullPropertiesSpec.kt
3575397428
package com.ipmus.resources import com.ipmus.entities.Broker import javax.ws.rs.* import javax.ws.rs.POST import javax.ws.rs.core.MediaType /** * Created by mdozturk on 7/27/17. */ @Path("brokers") class BrokerResource : GenericResource<Broker>(Broker.type, ::Broker) { @GET @Produces("application/json") fun brokers() : String{ return getAll() } @Path("/{entityID}") @GET @Produces("application/json") fun broker(@PathParam("entityID") entityID: String) : String { return getSpecific(entityID) } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces("application/json") fun newBroker(entity: Broker) : String { return newEntity(entity) } }
src/main/kotlin/com/ipmus/resources/BrokerResource.kt
4150402754
package com.sksamuel.kotest.matchers.string import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.should import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNot import io.kotest.matchers.string.endWith import io.kotest.matchers.string.shouldEndWith import io.kotest.matchers.string.shouldNotEndWith @Suppress("RedundantNullableReturnType") class EndWithTest : FreeSpec() { init { "should endWith" - { "should test strings" { "hello" should endWith("o") "hello" should endWith("o" as CharSequence) "hello" should endWith("") "hello" should endWith("" as CharSequence) "hello" shouldEndWith "" "hello" shouldEndWith "lo" "hello" shouldEndWith "o" "hello" shouldNotEndWith "w" "" should endWith("") shouldThrow<AssertionError> { "" should endWith("h") } shouldThrow<AssertionError> { "hello" should endWith("goodbye") } } "work with char seqs" { val cs: CharSequence = "hello" cs should endWith("o") cs.shouldEndWith("o") val csnullable: CharSequence? = "hello" csnullable should endWith("o") csnullable.shouldEndWith("o") } "return the correct type" { val cs1: CharSequence = "hello" val a1 = cs1.shouldEndWith("o") a1 shouldBe "hello" val cs2: CharSequence? = "hello" val a2 = cs2.shouldEndWith("o") a2 shouldBe "hello" } "should fail if value is null" { shouldThrow<AssertionError> { null shouldNot endWith("") }.message shouldBe "Expecting actual not to be null" shouldThrow<AssertionError> { null shouldNotEndWith "" }.message shouldBe "Expecting actual not to be null" shouldThrow<AssertionError> { null should endWith("o") }.message shouldBe "Expecting actual not to be null" shouldThrow<AssertionError> { null shouldEndWith "o" }.message shouldBe "Expecting actual not to be null" } } } }
kotest-assertions/kotest-assertions-core/src/jvmTest/kotlin/com/sksamuel/kotest/matchers/string/EndWithTest.kt
2703666301
package com.mycollab.module.user.esb import com.google.common.eventbus.AllowConcurrentEvents import com.google.common.eventbus.Subscribe import com.mycollab.common.GenericLinkUtils import com.mycollab.common.domain.MailRecipientField import com.mycollab.common.i18n.MailI18nEnum import com.mycollab.configuration.ApplicationConfiguration import com.mycollab.configuration.IDeploymentMode import com.mycollab.core.utils.DateTimeUtils import com.mycollab.i18n.LocalizationHelper import com.mycollab.module.billing.UserStatusConstants import com.mycollab.module.esb.GenericCommand import com.mycollab.module.mail.service.ExtMailService import com.mycollab.module.mail.service.IContentGenerator import com.mycollab.module.user.accountsettings.localization.UserI18nEnum import com.mycollab.module.user.domain.User import com.mycollab.module.user.service.BillingAccountService import com.mycollab.module.user.service.UserService import org.slf4j.LoggerFactory import org.springframework.stereotype.Component import org.springframework.transaction.event.TransactionPhase import org.springframework.transaction.event.TransactionalEventListener import java.util.* /** * @author MyCollab Ltd * @since 6.0.0 */ @Component class SendVerifyUserEmailCommand(private val deploymentMode: IDeploymentMode, private val billingAccountService: BillingAccountService, private val userService: UserService, private val extMailService: ExtMailService, private val contentGenerator: IContentGenerator, private val applicationConfiguration: ApplicationConfiguration) : GenericCommand() { @AllowConcurrentEvents @Subscribe @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) fun sendVerifyEmailRequest(event: SendUserEmailVerifyRequestEvent) { Thread.sleep(5000) sendConfirmEmailToUser(event.sAccountId, event.user) event.user.status = UserStatusConstants.EMAIL_VERIFIED_REQUEST userService.updateWithSession(event.user, event.user.username) } fun sendConfirmEmailToUser(sAccountId:Int, user: User) { val account = billingAccountService.getAccountById(sAccountId) if (account != null) { contentGenerator.putVariable("user", user) val siteUrl = deploymentMode.getSiteUrl(account.subdomain) contentGenerator.putVariable("siteUrl", siteUrl) val confirmLink = GenericLinkUtils.generateConfirmEmailLink(siteUrl, user.username) contentGenerator.putVariable("linkConfirm", confirmLink) contentGenerator.putVariable("copyRight", LocalizationHelper.getMessage(Locale.US, MailI18nEnum.Copyright, DateTimeUtils.getCurrentYear())) extMailService.sendHTMLMail(applicationConfiguration.notifyEmail, applicationConfiguration.siteName, listOf(MailRecipientField(user.email, "${user.firstname} ${user.lastname}")), LocalizationHelper.getMessage(Locale.US, UserI18nEnum.MAIL_CONFIRM_EMAIL_SUBJECT), contentGenerator.parseFile("mailVerifyEmailUser.ftl", Locale.US)) } else { LOG.error("Can not find account with id $sAccountId then can not send the verification email") } } companion object { val LOG = LoggerFactory.getLogger(SendVerifyUserEmailCommand::class.java) } }
mycollab-esb/src/main/java/com/mycollab/module/user/esb/SendVerifyUserEmailCommand.kt
112519994
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.project.service.impl import com.google.common.eventbus.AsyncEventBus import com.mycollab.aspect.ClassInfo import com.mycollab.aspect.ClassInfoMap import com.mycollab.aspect.Traceable import com.mycollab.cache.CleanCacheEvent import com.mycollab.common.ModuleNameConstants import com.mycollab.core.cache.CacheKey import com.mycollab.core.cache.CleanCache import com.mycollab.db.persistence.ICrudGenericDAO import com.mycollab.db.persistence.ISearchableDAO import com.mycollab.db.persistence.service.DefaultService import com.mycollab.module.project.ProjectTypeConstants import com.mycollab.module.project.dao.MilestoneMapper import com.mycollab.module.project.dao.MilestoneMapperExt import com.mycollab.module.project.domain.Milestone import com.mycollab.module.project.domain.SimpleMilestone import com.mycollab.module.project.domain.criteria.MilestoneSearchCriteria import com.mycollab.module.project.i18n.OptionI18nEnum.MilestoneStatus import com.mycollab.module.project.service.* import org.springframework.jdbc.core.BatchPreparedStatementSetter import org.springframework.jdbc.core.JdbcTemplate import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.sql.PreparedStatement import java.sql.SQLException import javax.sql.DataSource /** * @author MyCollab Ltd. * @since 1.0 */ @Service @Transactional @Traceable(nameField = "name", extraFieldName = "projectid") class MilestoneServiceImpl(private val milestoneMapper: MilestoneMapper, private val milestoneMapperExt: MilestoneMapperExt, private val dataSource: DataSource, private val asyncEventBus: AsyncEventBus) : DefaultService<Int, Milestone, MilestoneSearchCriteria>(), MilestoneService { override val crudMapper: ICrudGenericDAO<Int, Milestone> get() = milestoneMapper as ICrudGenericDAO<Int, Milestone> override val searchMapper: ISearchableDAO<MilestoneSearchCriteria> get() = milestoneMapperExt override fun findById(milestoneId: Int, sAccountId: Int): SimpleMilestone? = milestoneMapperExt.findById(milestoneId) override fun saveWithSession(record: Milestone, username: String?): Int { if (record.status == null) { record.status = MilestoneStatus.InProgress.name } return super.saveWithSession(record, username) } @CleanCache fun postDirtyUpdate(sAccountId: Int?) { asyncEventBus.post(CleanCacheEvent(sAccountId, arrayOf(ProjectService::class.java, ProjectTicketService::class.java, ProjectActivityStreamService::class.java))) } override fun massUpdateOptionIndexes(mapIndexes: List<Map<String, Int>>, @CacheKey sAccountId: Int) { val jdbcTemplate = JdbcTemplate(dataSource) jdbcTemplate.batchUpdate("UPDATE `m_prj_milestone` SET `orderIndex`=? WHERE `id`=?", object : BatchPreparedStatementSetter { @Throws(SQLException::class) override fun setValues(preparedStatement: PreparedStatement, i: Int) { preparedStatement.setInt(1, mapIndexes[i]["index"]!!) preparedStatement.setInt(2, mapIndexes[i]["id"]!!) } override fun getBatchSize(): Int = mapIndexes.size }) } companion object { init { ClassInfoMap.put(MilestoneServiceImpl::class.java, ClassInfo(ModuleNameConstants.PRJ, ProjectTypeConstants.MILESTONE)) } } }
mycollab-services/src/main/java/com/mycollab/module/project/service/impl/MilestoneServiceImpl.kt
2698191325
package com.github.kerubistan.kerub.planner.steps.host.startup class WakeHostException(message: String, reason: Exception?) : Exception(message, reason)
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/host/startup/WakeHostException.kt
3950703186
package com.jtransc import com.jtransc.annotation.haxe.HaxeMethodBody import com.jtransc.ast.* import com.jtransc.backend.toAst import com.jtransc.ds.diff import com.jtransc.ds.hasAnyFlags import com.jtransc.ds.hasFlag import com.jtransc.maven.MavenLocalRepository import com.jtransc.org.objectweb.asm.ClassReader import com.jtransc.org.objectweb.asm.Opcodes import com.jtransc.org.objectweb.asm.tree.AnnotationNode import com.jtransc.org.objectweb.asm.tree.ClassNode import com.jtransc.org.objectweb.asm.tree.FieldNode import com.jtransc.org.objectweb.asm.tree.MethodNode import com.jtransc.vfs.* import java.util.function.BiConsumer class JTranscRtReport { val types = AstTypes() companion object { @JvmStatic fun main(args: Array<String>) { JTranscRtReport().report() } } val jtranscVersion = JTranscVersion.getVersion() val javaRt = MergeVfs(listOf( ZipVfs(GetClassJar(String::class.java)), ZipVfs(GetClassJar(BiConsumer::class.java)) )) val jtranscRt = MergedLocalAndJars(MavenLocalRepository.locateJars("com.jtransc:jtransc-rt:$jtranscVersion")) fun report() { reportPackage("java", listOf("java.rmi", "java.sql", "java.beans", "java.awt", "java.applet", "java/applet", "sun", "javax", "com/sun", "com.sun", "jdk")) reportNotImplementedNatives("java") } fun reportPackage(packageName: String, ignoreSet: List<String>) { val ignoreSetNormalized = ignoreSet.map { it.replace('.', '/') } val packagePath = packageName.replace('.', '/') fileList@ for (e in javaRt[packagePath].listdirRecursive().filter { it.name.endsWith(".class") }) { //for (e.file) for (base in ignoreSetNormalized) { if (e.file.path.startsWith(base)) { continue@fileList } } compareFiles(e.file, jtranscRt[e.path]) } } fun reportNotImplementedNatives(packageName: String) { val packagePath = packageName.replace('.', '/') fileList@ for (e in jtranscRt[packagePath].listdirRecursive().filter { it.name.endsWith(".class") }) { val clazz = readClass(e.file.readBytes()) val nativeMethodsWithoutBody = clazz.methods.filterIsInstance<MethodNode>() .filter { it.access hasFlag Opcodes.ACC_NATIVE } if (nativeMethodsWithoutBody.isNotEmpty()) { println("CLASS ${clazz.name} (native without body):") try { for (method in nativeMethodsWithoutBody.filter { method -> if (method.invisibleAnnotations != null) { !AstAnnotationList( AstMethodRef(FqName.fromInternal(clazz.name), method.name, types.demangleMethod(method.desc)), method.invisibleAnnotations.filterIsInstance<AnnotationNode>().map { it.toAst(types) }).contains<HaxeMethodBody>() } else { true } }) { println(" - ${method.name} : ${method.desc}") } } catch (e: Throwable) { e.printStackTrace() } } } } private fun readClass(data: ByteArray): ClassNode { return ClassNode(Opcodes.ASM5).apply { ClassReader(data).accept(this, ClassReader.SKIP_CODE + ClassReader.SKIP_DEBUG + ClassReader.SKIP_FRAMES) } } fun compareFiles(f1: SyncVfsFile, f2: SyncVfsFile) { //interface MemberRef {} data class MethodRef(val name: String, val desc: String) fun ClassNode.getPublicOrProtectedMethodDescs() = this.methods .filterIsInstance<MethodNode>() .filter { it.access hasAnyFlags (Opcodes.ACC_PUBLIC or Opcodes.ACC_PROTECTED) } .map { MethodRef(it.name, it.desc) } fun ClassNode.getPublicOrProtectedFieldDescs() = this.methods .filterIsInstance<FieldNode>() .filter { it.access hasAnyFlags (Opcodes.ACC_PUBLIC or Opcodes.ACC_PROTECTED) } .map { AstFieldWithoutClassRef(it.name, types.demangle(it.desc)) } if (f1.exists) { val javaClass = readClass(f1.readBytes()) if (javaClass.access hasAnyFlags Opcodes.ACC_PUBLIC) { if (f2.exists) { val jtranscClass = readClass(f2.readBytes()) val javaMethods = javaClass.getPublicOrProtectedMethodDescs() val jtranscMethods = jtranscClass.getPublicOrProtectedMethodDescs() val javaFields = javaClass.getPublicOrProtectedFieldDescs() val jtranscFields = jtranscClass.getPublicOrProtectedFieldDescs() val methodResults = javaMethods.diff(jtranscMethods) val fieldResults = javaFields.diff(jtranscFields) if (methodResults.justFirst.isNotEmpty()) { println("${javaClass.name} (missing methods)") for (i in methodResults.justFirst) { println(" - ${i.name} : ${i.desc}") } } if (fieldResults.justFirst.isNotEmpty()) { println("${javaClass.name} (missing fields)") for (i in fieldResults.justFirst) { println(" - ${i.name} : ${i.type.mangle()}") } } } else { println("${javaClass.name} (missing class)") } } //for (node in origClass.methods.filterIsInstance<MethodNode>()) node.name + node.desc //println("" + f1.path + " : " + f2.path) } } }
jtransc-main/src/com/jtransc/report.kt
1831997544
/* * Copyright (c) 2017 Kotlin Algorithm Club * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.uuddlrlrba.ktalgs.datastructures import org.junit.Assert import org.junit.Test import java.util.* class QueueTest { @Test fun emptyTest() { val queue = Queue<Int>() Assert.assertEquals(0, queue.size) Assert.assertTrue(queue.isEmpty()) } @Test(expected= NoSuchElementException::class) fun exceptionTest() { val queue = Queue<Int>() queue.peek() } @Test fun naiveTest() { val queue = Queue<Int>() for (i in 0..10) { queue.add(i) } for (i in 0..10) { Assert.assertEquals(i, queue.peek()) Assert.assertEquals(i, queue.poll()) } Assert.assertEquals(0, queue.size) } @Test fun naiveIteratorTest() { val queue = Queue<Int>() for (i in 0..10) { queue.add(i) } var k = 0 for (i in queue) { Assert.assertEquals(i, k++) } } @Test fun naiveContainsTest() { val queue = Queue<Int>() for (i in 0..10) { queue.add(i) } for (i in 0..10) { Assert.assertTrue(queue.contains(i)) } Assert.assertFalse(queue.contains(100)) Assert.assertFalse(queue.contains(101)) Assert.assertFalse(queue.contains(103)) } }
src/test/io/uuddlrlrba/ktalgs/datastructures/QueueTest.kt
2769145652
/* * Copyright (C) 2017-2019 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.adblock.filter.unified import android.net.Uri class EndWithFilter( filter: String, contentType: Int, domains: DomainMap?, thirdParty: Int ) : UnifiedFilter(filter, contentType, false, domains, thirdParty) { override val filterType: Int get() = FILTER_TYPE_END override fun check(url: Uri): Boolean { val urlStr = url.toString() val index = urlStr.indexOf(pattern) if (index >= 0) { return if (index + pattern.length == urlStr.length) { true } else { urlStr[index + pattern.length].checkSeparator() } } return false } }
module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/filter/unified/EndWithFilter.kt
1121433546
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.kork.sql.config import org.springframework.boot.context.properties.ConfigurationProperties /** * The entrypoint configuration properties for SQL integrations. * * This configuration supports multiple, named connection pools, as well as dedicated configurations for * performing database migrations. * * @param migration The primary migration configuration * @param secondaryMigration Migration configuration for the secondary database, if one is available * @param connectionPools All non-migration connection pools for the application * @param retries Default, global retry configuration across connection pools * @param connectionPool Deprecated. Use [connectionPools] instead. */ @ConfigurationProperties("sql") data class SqlProperties( var migration: SqlMigrationProperties = SqlMigrationProperties(), var secondaryMigration: SqlMigrationProperties = SqlMigrationProperties(), var connectionPools: MutableMap<String, ConnectionPoolProperties> = mutableMapOf(), var retries: SqlRetryProperties = SqlRetryProperties(), @Deprecated("use named connection pools instead") var connectionPool: ConnectionPoolProperties? = null ) { /** * Convenience method for accessing all connection pool properties, backwards-compatible with deprecated * [connectionPool] configuration. */ fun getDefaultConnectionPoolProperties(): ConnectionPoolProperties { if (connectionPools.isEmpty()) { if (connectionPool == null) { throw MisconfiguredConnectionPoolsException.NEITHER_PRESENT } return connectionPool!! } return if (connectionPools.size == 1) { connectionPools.values.first() } else { connectionPools.values.first { it.default } } } } internal class MisconfiguredConnectionPoolsException(message: String) : IllegalStateException(message) { companion object { val NEITHER_PRESENT = MisconfiguredConnectionPoolsException( "Neither 'sql.connectionPools' nor 'sql.connectionPool' have been configured" ) val BOTH_PRESENT = MisconfiguredConnectionPoolsException( "Both 'sql.connectionPools' and 'sql.connectionPool' are configured: Use only one" ) } }
kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/SqlProperties.kt
1140825326
package com.niortreactnative.activities import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.util.Log import com.niortreactnative.R import com.niortreactnative.adapters.Line import com.niortreactnative.fragments.LineDetailFragment import com.niortreactnative.fragments.LineListFragment class MainActivity : AppCompatActivity(), LineListFragment.OnLineSelectedListener { private val TAG:String = "MainActivity" private val TAG_LINELIST_FRAGMENT = "tag_linelist_fragment" private val TAG_LINEDETAIL_FRAGMENT = "tag_linedetail_fragment" private var lineListFragment:LineListFragment? = null override fun onLineSelected(line: Line){ Log.d(TAG, "hey ! it works dude") Log.d(TAG, "line departure is " + line.departure) supportFragmentManager.beginTransaction() .add(R.id.fragment_stack, LineDetailFragment(), TAG_LINEDETAIL_FRAGMENT) .addToBackStack(TAG_LINEDETAIL_FRAGMENT) .commit() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG, "on create") setContentView(R.layout.activity_main) lineListFragment = supportFragmentManager.findFragmentByTag(TAG_LINELIST_FRAGMENT) as? LineListFragment if (lineListFragment == null) { lineListFragment = LineListFragment() supportFragmentManager.beginTransaction() .replace(R.id.fragment_stack, lineListFragment, TAG_LINELIST_FRAGMENT) .commit() } //todo manager navigation between views /* supportFragmentManager.beginTransaction() .replace(R.id.fragment_stack, LineDetailFragment(), TAG_LINEDETAIL_FRAGMENT) .commit() */ } }
app/src/main/java/com/niortreactnative/activities/MainActivity.kt
1156604106
package com.github.badoualy.telegram.mtproto.secure.pq import com.github.badoualy.telegram.mtproto.util.SolvedPQ import java.math.BigInteger import java.util.* internal class PQSolver { companion object { /** * Decomposes pq into prime factors such that p < q * Same implementation than https://github.com/enricostara/telegram-mt-node/blob/master/lib/security/pq-finder.js * TODO: check origin */ @JvmStatic @SuppressWarnings("SuspiciousNameCombination") fun solve(input: BigInteger): SolvedPQ { val r = Random() val pq = input.toLong() var q: Long = 0 for (i in 0..2) { val w = (r.nextInt(128) and 15) + 17 var x = (r.nextInt(1000000000) + 1).toLong() var y = x val lim = 1 shl (i + 18) for (j in 1..lim - 1) { var a = x var b = x var c = w.toLong() while (b != 0L) { if ((b and 1) != 0L) { c += a if (c >= pq) { c -= pq } } a += a if (a >= pq) { a -= pq } b = b shr 1 } x = c val z = if (x < y) y - x else x - y // var z = y.gt(x) TODO why different here ? q = GCD(z, pq) if (q != 1L) break if ((j and (j - 1)) == 0) y = x } if (q > 1) break } val p = pq / q return SolvedPQ(p, q) } private fun GCD(x: Long, y: Long): Long { var a = x var b = y while (a != 0L && b != 0L) { while ((b and 1) == 0L) { b = b shr 1 } while ((a and 1) == 0L) { a = a shr 1 } if (a > b) { a -= b } else { b -= a } } return if (b == 0L) a else b } } }
mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/secure/pq/PQSolver.kt
2390956128
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.sqldelight.runtime.coroutines import co.touchlab.sqliter.DatabaseFileContext import com.squareup.sqldelight.db.SqlDriver import com.squareup.sqldelight.drivers.native.NativeSqliteDriver private fun defaultSchema(): SqlDriver.Schema { return object : SqlDriver.Schema { override val version: Int = 1 override fun create(driver: SqlDriver) {} override fun migrate( driver: SqlDriver, oldVersion: Int, newVersion: Int ) {} } } actual suspend fun testDriver(): SqlDriver { val name = "testdb" DatabaseFileContext.deleteDatabase(name) return NativeSqliteDriver(defaultSchema(), name) }
extensions/coroutines-extensions/src/nativeTest/kotlin/com/squareup/sqldelight/runtime/coroutines/TestDb.kt
596143895
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package cx.ring.tv.about import android.content.Context import androidx.leanback.widget.Presenter import android.view.ViewGroup import android.view.LayoutInflater import cx.ring.databinding.DetailViewContentBinding import cx.ring.tv.cards.iconcards.IconCard class AboutDetailsPresenter(private val context: Context) : Presenter() { private var binding: DetailViewContentBinding? = null override fun onCreateViewHolder(parent: ViewGroup): ViewHolder { return ViewHolder(DetailViewContentBinding.inflate(LayoutInflater.from(context)) .apply { binding = this } .root) } override fun onBindViewHolder(viewHolder: ViewHolder, itemData: Any) { val card = itemData as IconCard binding?.apply { primaryText.text = card.title extraText.text = card.description } } override fun onUnbindViewHolder(viewHolder: ViewHolder) {} }
ring-android/app/src/main/java/cx/ring/tv/about/AboutDetailsPresenter.kt
1785627010
@file:Include("include_6.kt") fun include_5() = println("include_5")
test/resources/includes/rel_includes/include_5.kt
1661238463
package com.gmail.blueboxware.libgdxplugin.versions /* * Copyright 2017 Blue Box Ware * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ internal enum class Repository(val baseUrl: String) { MAVEN_CENTRAL("https://repo1.maven.org/maven2/"), JCENTER("https://jcenter.bintray.com/"), JITPACK("https://jitpack.io/api/builds/") }
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/versions/Repository.kt
2132316429
package com.hadihariri.markcode import java.io.File fun main(args: Array<String>) { if (args.size < 2) { println("Usage: <doc_directory> <examples output directory> [-o]") return } val writeExpectedOutput = args.size > 2 && args[2] == "-o" val chapters = mutableListOf<Chapter>() File(args[0]).listFiles { _, name -> name.endsWith(".adoc") }.forEach { val chapterCodeDir = File(args[1], it.nameWithoutExtension ) val chapter = Chapter(it, chapterCodeDir) chapters.add(chapter) chapter.process(writeExpectedOutput) } if (writeExpectedOutput) { writeVerifyAllSamples(chapters, File(args[1])) } if (chapters.any { it.hasErrors }) { System.exit(1) } }
src/main/kotlin/com/hadihariri/markcode/Main.kt
2826294439
/* * Copyright (C) 2014 Contentful 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.contentful.java.cma import com.contentful.java.cma.model.CMAResource import retrofit.RestAdapter import java.util.concurrent.CountDownLatch import kotlin.test.assertEquals import kotlin.test.assertNotEquals import org.junit.Before as before import org.junit.Test as test class ModuleTests : BaseTest() { var module: AbsModule<Any>? = null before fun setup() { super<BaseTest>.setUp() module = object : AbsModule<Any>(null, SynchronousExecutor()) { override fun createService(restAdapter: RestAdapter?): Any? { return null } } } test(expected = IllegalArgumentException::class) fun testNotNull() { try { module!!.assertNotNull(null, "parameter") } catch (e: IllegalArgumentException) { assertEquals("parameter may not be null.", e.getMessage()) throw e } } test(expected = IllegalArgumentException::class) fun testResourceId() { try { module!!.getResourceIdOrThrow(CMAResource(), "parameter") } catch (e: IllegalArgumentException) { assertEquals("parameter.setId() was not called.", e.getMessage()) throw e } } test(expected = IllegalArgumentException::class) fun testSpaceId() { try { module!!.getSpaceIdOrThrow(CMAResource(), "parameter") } catch (e: IllegalArgumentException) { assertEquals("parameter must have a space associated.", e.getMessage()) throw e } } test fun testDefersToBackgroundThread() { val currentThreadId = Thread.currentThread().getId() var workerThreadId: Long? = null val module = object : AbsModule<Any>(null, SynchronousExecutor()) { override fun createService(restAdapter: RestAdapter?): Any? = null fun work() { val cdl = CountDownLatch(1) defer( object : RxExtensions.DefFunc<Long>() { override fun method(): Long? { workerThreadId = Thread.currentThread().getId() return workerThreadId } }, object : CMACallback<Long>() { override fun onSuccess(result: Long?) { cdl.countDown() } }) cdl.await() } } module.work() assertNotEquals(currentThreadId, workerThreadId) } }
src/test/kotlin/com/contentful/java/cma/ModuleTests.kt
339663730
package chat.rocket.android.authentication.onboarding.di import androidx.lifecycle.LifecycleOwner import chat.rocket.android.authentication.onboarding.presentation.OnBoardingView import chat.rocket.android.authentication.onboarding.ui.OnBoardingFragment import chat.rocket.android.dagger.scope.PerFragment import dagger.Module import dagger.Provides @Module class OnBoardingFragmentModule { @Provides @PerFragment fun onBoardingView(frag: OnBoardingFragment): OnBoardingView = frag @Provides @PerFragment fun provideLifecycleOwner(frag: OnBoardingFragment): LifecycleOwner = frag }
app/src/main/java/chat/rocket/android/authentication/onboarding/di/OnBoardingFragmentModule.kt
3670305232
package com.michalkowol.base.web import spark.Spark.port import spark.Spark.staticFiles class HttpServer( private val serverConfiguration: ServerConfiguration, private val controllers: List<Controller> ) { fun start() { port(serverConfiguration.port) staticFiles.location("/public") controllers.forEach { it.start() } } }
src/main/kotlin/com/michalkowol/base/web/HttpServer.kt
3200952566