content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package org.runestar.client.api.game import org.runestar.client.raw.access.XActor import org.runestar.client.raw.access.XHeadbar import org.runestar.client.raw.access.XHeadbarUpdate abstract class Actor(override val accessor: XActor) : Entity(accessor), ActorTargeting { abstract val plane: Int override val npcTargetIndex: Int get() = accessor.targetIndex.let { if (it in 0..32767) it else -1 } override val playerTargetIndex: Int get() = accessor.targetIndex.let { if (it > 32768) it - 32768 else -1 } override val modelPosition get() = Position(accessor.x, accessor.y, 0, plane) val location get() = SceneTile(accessor.pathX[0], accessor.pathY[0], plane) override val orientation get() = Angle.of(accessor.orientation) var overheadText: String? get() = accessor.overheadText set(value) { accessor.overheadText = value } var overheadTextCyclesRemaining: Int get() = accessor.overheadTextCyclesRemaining set(value) { accessor.overheadTextCyclesRemaining = value } /** * Health percent between `0.0` and `1.0` of limited precision. `null` if the health-bar is not visible. */ val health: Double? get() { val headbars = accessor.headbars ?: return null val headbar = headbars.sentinel.next if (headbar is XHeadbar) { val update = headbar.updates.sentinel.next if (update is XHeadbarUpdate) { val def = headbar.type ?: return null return update.health.toDouble() / def.width } } return null } val defaultHeight: Int get() = accessor.defaultHeight }
api/src/main/java/org/runestar/client/api/game/Actor.kt
3783279798
// 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.completion import com.intellij.codeInsight.lookup.LookupElementBuilder import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.completion.implCommon.handlers.NamedArgumentInsertHandler import org.jetbrains.kotlin.idea.core.ArgumentPositionData import org.jetbrains.kotlin.idea.core.ExpectedInfo import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.CallType import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtCallElement import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.psi.KtValueArgument import org.jetbrains.kotlin.psi.ValueArgument import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.calls.components.isVararg import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument import org.jetbrains.kotlin.types.KotlinType object NamedArgumentCompletion { fun isOnlyNamedArgumentExpected(nameExpression: KtSimpleNameExpression, resolutionFacade: ResolutionFacade): Boolean { val thisArgument = nameExpression.parent as? KtValueArgument ?: return false if (thisArgument.isNamed()) return false val resolvedCall = thisArgument.getStrictParentOfType<KtCallElement>()?.resolveToCall(resolutionFacade) ?: return false return !thisArgument.canBeUsedWithoutNameInCall(resolvedCall) } fun complete(collector: LookupElementsCollector, expectedInfos: Collection<ExpectedInfo>, callType: CallType<*>) { if (callType != CallType.DEFAULT) return val nameToParameterType = HashMap<Name, MutableSet<KotlinType>>() for (expectedInfo in expectedInfos) { val argumentData = expectedInfo.additionalData as? ArgumentPositionData.Positional ?: continue for (parameter in argumentData.namedArgumentCandidates) { nameToParameterType.getOrPut(parameter.name) { HashSet() }.add(parameter.type) } } for ((name, types) in nameToParameterType) { val typeText = types.singleOrNull()?.let { BasicLookupElementFactory.SHORT_NAMES_RENDERER.renderType(it) } ?: "..." val nameString = name.asString() val lookupElement = LookupElementBuilder.create("$nameString =") .withPresentableText("$nameString =") .withTailText(" $typeText") .withIcon(KotlinIcons.PARAMETER) .withInsertHandler(NamedArgumentInsertHandler(name)) lookupElement.putUserData(SmartCompletionInBasicWeigher.NAMED_ARGUMENT_KEY, Unit) collector.addElement(lookupElement) } } } /** * Checks whether argument in the [resolvedCall] can be used without its name (as positional argument). */ fun KtValueArgument.canBeUsedWithoutNameInCall(resolvedCall: ResolvedCall<out CallableDescriptor>): Boolean { if (resolvedCall.resultingDescriptor.valueParameters.isEmpty()) return true val argumentsThatCanBeUsedWithoutName = collectAllArgumentsThatCanBeUsedWithoutName(resolvedCall).map { it.argument } if (argumentsThatCanBeUsedWithoutName.isEmpty() || argumentsThatCanBeUsedWithoutName.none { it == this }) return false val argumentsBeforeThis = argumentsThatCanBeUsedWithoutName.takeWhile { it != this } return if (languageVersionSettings.supportsFeature(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition)) { argumentsBeforeThis.none { it.isNamed() && !it.placedOnItsOwnPositionInCall(resolvedCall) } } else { argumentsBeforeThis.none { it.isNamed() } } } data class ArgumentThatCanBeUsedWithoutName( val argument: KtValueArgument, /** * When we didn't manage to map an argument to the appropriate parameter then the parameter is `null`. It's useful for cases when we * want to analyze possibility for the argument to be used without name even when appropriate parameter doesn't yet exist * (it may start existing when user will create the parameter from usage with "Add parameter to function" refactoring) */ val parameter: ValueParameterDescriptor? ) fun collectAllArgumentsThatCanBeUsedWithoutName( resolvedCall: ResolvedCall<out CallableDescriptor>, ): List<ArgumentThatCanBeUsedWithoutName> { val arguments = resolvedCall.call.valueArguments.filterIsInstance<KtValueArgument>() val argumentAndParameters = arguments.map { argument -> val parameter = resolvedCall.getParameterForArgument(argument) argument to parameter }.sortedBy { (_, parameter) -> parameter?.index ?: Int.MAX_VALUE } val firstVarargArgumentIndex = argumentAndParameters.indexOfFirst { (_, parameter) -> parameter?.isVararg ?: false } val lastVarargArgumentIndex = argumentAndParameters.indexOfLast { (_, parameter) -> parameter?.isVararg ?: false } return argumentAndParameters .asSequence() .mapIndexed { argumentIndex, (argument, parameter) -> val parameterIndex = parameter?.index ?: argumentIndex val isAfterVararg = lastVarargArgumentIndex != -1 && argumentIndex > lastVarargArgumentIndex val isVarargArg = argumentIndex in firstVarargArgumentIndex..lastVarargArgumentIndex if (!isVarargArg && argumentIndex != parameterIndex || isAfterVararg || isVarargArg && argumentAndParameters.drop(lastVarargArgumentIndex + 1).any { (argument, _) -> !argument.isNamed() } ) { null } else { ArgumentThatCanBeUsedWithoutName(argument, parameter) } } .takeWhile { it != null } // When any argument can't be used without a name then all subsequent arguments must have a name too! .map { it ?: error("It cannot be null because of the previous takeWhile in the chain") } .toList() } /** * Checks whether argument in the [resolvedCall] is on the same position as it listed in the callable definition. * * It is always true for the positional arguments, but may be untrue for the named arguments. * * ``` * fun foo(a: Int, b: Int, c: Int, d: Int) {} * * foo( * 10, // true * b = 10, // true, possible since Kotlin 1.4 with `MixedNamedArgumentsInTheirOwnPosition` feature * d = 30, // false, 3 vs 4 * c = 40 // false, 4 vs 3 * ) * ``` */ fun ValueArgument.placedOnItsOwnPositionInCall(resolvedCall: ResolvedCall<out CallableDescriptor>): Boolean { return resolvedCall.getParameterForArgument(this)?.index == resolvedCall.call.valueArguments.indexOf(this) }
plugins/kotlin/completion/impl-k1/src/org/jetbrains/kotlin/idea/completion/NamedArgumentCompletion.kt
474565958
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.collaboration.auth import java.util.* /** * @param A - account type */ @JvmDefaultWithCompatibility interface AccountsListener<A> : EventListener { fun onAccountListChanged(old: Collection<A>, new: Collection<A>) {} fun onAccountCredentialsChanged(account: A) {} }
platform/collaboration-tools/src/com/intellij/collaboration/auth/AccountsListener.kt
2762785072
// 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.vcs.impl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.AbstractVcs import com.intellij.openapi.vcs.VcsDirectoryMapping import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx.MAPPING_DETECTION_LOG import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Alarm import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.ui.update.DisposableUpdate import com.intellij.util.ui.update.MergingUpdateQueue import com.intellij.workspaceModel.ide.WorkspaceModelTopics internal class ModuleVcsDetector(private val project: Project) { private val vcsManager by lazy(LazyThreadSafetyMode.NONE) { ProjectLevelVcsManagerImpl.getInstanceImpl(project) } private val queue = MergingUpdateQueue("ModuleVcsDetector", 1000, true, null, project, null, Alarm.ThreadToUse.POOLED_THREAD).also { it.setRestartTimerOnAdd(true) } private fun startDetection() { MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.startDetection") project.messageBus.connect().subscribe(WorkspaceModelTopics.CHANGED, MyWorkspaceModelChangeListener()) if (vcsManager.needAutodetectMappings() && vcsManager.haveDefaultMapping() == null) { queue.queue(DisposableUpdate.createDisposable(queue, "initial scan") { autoDetectDefaultRoots() }) } } @RequiresBackgroundThread private fun autoDetectDefaultRoots() { MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.autoDetectDefaultRoots") if (vcsManager.haveDefaultMapping() != null) return val contentRoots = DefaultVcsRootPolicy.getInstance(project).defaultVcsRoots MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.autoDetectDefaultRoots - contentRoots", contentRoots) val usedVcses = mutableSetOf<AbstractVcs>() val detectedRoots = mutableSetOf<Pair<VirtualFile, AbstractVcs>>() contentRoots .forEach { root -> val foundVcs = vcsManager.findVersioningVcs(root) if (foundVcs != null) { detectedRoots.add(Pair(root, foundVcs)) usedVcses.add(foundVcs) } } if (detectedRoots.isEmpty()) return MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.autoDetectDefaultRoots - detectedRoots", detectedRoots) val commonVcs = usedVcses.singleOrNull() if (commonVcs != null) { // Remove existing mappings that will duplicate added <Project> mapping. val rootPaths = detectedRoots.mapTo(mutableSetOf()) { it.first.path } val additionalMappings = vcsManager.directoryMappings.filter { it.vcs != commonVcs.name || it.directory !in rootPaths } vcsManager.setAutoDirectoryMappings(additionalMappings + VcsDirectoryMapping.createDefault(commonVcs.name)) } else { registerNewDirectMappings(detectedRoots) } } @RequiresBackgroundThread private fun autoDetectForContentRoots(contentRoots: List<VirtualFile>) { MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.autoDetectForContentRoots - contentRoots", contentRoots) if (vcsManager.haveDefaultMapping() != null) return val usedVcses = mutableSetOf<AbstractVcs>() val detectedRoots = mutableSetOf<Pair<VirtualFile, AbstractVcs>>() contentRoots .filter { it.isInLocalFileSystem } .filter { it.isDirectory } .forEach { root -> val foundVcs = vcsManager.findVersioningVcs(root) if (foundVcs != null && foundVcs !== vcsManager.getVcsFor(root)) { detectedRoots.add(Pair(root, foundVcs)) usedVcses.add(foundVcs) } } if (detectedRoots.isEmpty()) return MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.autoDetectForContentRoots - detectedRoots", detectedRoots) val commonVcs = usedVcses.singleOrNull() if (commonVcs != null && !vcsManager.hasAnyMappings()) { vcsManager.setAutoDirectoryMappings(listOf(VcsDirectoryMapping.createDefault(commonVcs.name))) } else { registerNewDirectMappings(detectedRoots) } } private fun registerNewDirectMappings(detectedRoots: Collection<Pair<VirtualFile, AbstractVcs>>) { val oldMappings = vcsManager.directoryMappings val knownMappedRoots = oldMappings.mapTo(mutableSetOf()) { it.directory } val newMappings = detectedRoots.asSequence() .map { (root, vcs) -> VcsDirectoryMapping(root.path, vcs.name) } .filter { it.directory !in knownMappedRoots } vcsManager.setAutoDirectoryMappings(oldMappings + newMappings) } private inner class MyWorkspaceModelChangeListener : ContentRootChangeListener(skipFileChanges = true) { private val dirtyContentRoots = mutableSetOf<VirtualFile>() override fun contentRootsChanged(removed: List<VirtualFile>, added: List<VirtualFile>) { if (added.isNotEmpty()) { MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.contentRootsChanged - roots added", added) if (vcsManager.haveDefaultMapping() == null) { synchronized(dirtyContentRoots) { dirtyContentRoots.addAll(added) dirtyContentRoots.removeAll(removed.toSet()) } queue.queue(DisposableUpdate.createDisposable(queue, "modules scan") { runScanForNewContentRoots() }) } } if (removed.isNotEmpty()) { MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.contentRootsChanged - roots removed", removed) val remotedPaths = removed.map { it.path }.toSet() val removedMappings = vcsManager.directoryMappings.filter { it.directory in remotedPaths } removedMappings.forEach { mapping -> vcsManager.removeDirectoryMapping(mapping) } } } private fun runScanForNewContentRoots() { val contentRoots: List<VirtualFile> synchronized(dirtyContentRoots) { contentRoots = dirtyContentRoots.toList() dirtyContentRoots.clear() } autoDetectForContentRoots(contentRoots) } } internal class MyStartUpActivity : VcsStartupActivity { init { if (ApplicationManager.getApplication().isUnitTestMode) { throw ExtensionNotApplicableException.create() } } override fun runActivity(project: Project) { project.service<ModuleVcsDetector>().startDetection() } override fun getOrder(): Int { return VcsInitObject.MAPPINGS.order + 10; } } }
platform/vcs-impl/src/com/intellij/openapi/vcs/impl/ModuleVcsDetector.kt
3465153169
package cc.protea.spreedly.model import org.simpleframework.xml.Default import org.simpleframework.xml.Element @Default(required = false) data class SpreedlyBankAccount( @field:Element(name = "first_name") var firstName: String? = null, @field:Element(name = "last_name") var lastName: String? = null, @field:Element(name = "bank_routing_number") var bankRoutingNumber: String? = null, @field:Element(name = "bank_account_number") var bankAccountNumber: String? = null, @field:Element(name = "phone_number") var phoneNumber: String? = null, var email: String? = null, var address1: String? = null, var address2: String? = null, var city: String? = null, var state: String? = null, var zip: String? = null ) { override fun toString(): String { return "SpreedlyBankAccount(firstName=$firstName)" } }
src/main/java/cc/protea/spreedly/model/SpreedlyBankAccount.kt
337446563
// 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.codeInsight import com.intellij.codeInspection.ex.EntryPointsManagerBase import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiFile import com.intellij.testFramework.TestLoggerFactory import com.intellij.util.ThrowableRunnable import org.jdom.Document import org.jdom.input.SAXBuilder import org.jetbrains.kotlin.formatter.FormatSettingsUtil import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.inspections.runInspection import org.jetbrains.kotlin.idea.test.* import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import org.jetbrains.kotlin.idea.test.KotlinTestUtils import org.jetbrains.plugins.groovy.GroovyFileType import org.junit.runner.Description import java.io.File abstract class AbstractInspectionTest : KotlinLightCodeInsightFixtureTestCase() { companion object { const val ENTRY_POINT_ANNOTATION = "test.anno.EntryPoint" } override fun setUp() { try { super.setUp() EntryPointsManagerBase.getInstance(project).ADDITIONAL_ANNOTATIONS.add(ENTRY_POINT_ANNOTATION) registerGradlPlugin() } catch (e: Throwable) { TestLoggerFactory.logTestFailure(e) TestLoggerFactory.onTestFinished(false, Description.createTestDescription(javaClass, name)) throw e } } protected open fun registerGradlPlugin() { runWriteAction { FileTypeManager.getInstance().associateExtension(GroovyFileType.GROOVY_FILE_TYPE, "gradle") } } override fun tearDown() { runAll( ThrowableRunnable { EntryPointsManagerBase.getInstance(project).ADDITIONAL_ANNOTATIONS.remove(ENTRY_POINT_ANNOTATION) }, ThrowableRunnable { super.tearDown() } ) } protected open fun configExtra(psiFiles: List<PsiFile>, options: String) { } protected open val forceUsePackageFolder: Boolean = false //workaround for IDEA-176033 protected open fun inspectionClassDirective(): String = "// INSPECTION_CLASS: " protected open fun doTest(path: String) { val optionsFile = File(path) val options = FileUtil.loadFile(optionsFile, true) val inspectionClass = Class.forName(InTextDirectivesUtils.findStringWithPrefixes(options, inspectionClassDirective()) ?: error("Not found line with directive ${inspectionClassDirective()}")) val fixtureClasses = InTextDirectivesUtils.findListWithPrefixes(options, "// FIXTURE_CLASS: ") withCustomCompilerOptions(options, project, module) { val inspectionsTestDir = optionsFile.parentFile!! val srcDir = inspectionsTestDir.parentFile!! val settingsFile = File(inspectionsTestDir, "settings.xml") val settingsElement = if (settingsFile.exists()) { (SAXBuilder().build(settingsFile) as Document).rootElement } else { null } with(myFixture) { testDataPath = srcDir.path val afterFiles = srcDir.listFiles { it -> it.name == "inspectionData" } ?.single() ?.listFiles { it -> it.extension == "after" } ?: emptyArray() val psiFiles = srcDir.walkTopDown().onEnter { it.name != "inspectionData" }.mapNotNull { file -> when { file.isDirectory -> null file.extension == "kt" -> { val text = FileUtil.loadFile(file, true) val fileText = if (text.lines().any { it.startsWith("package") }) text else "package ${file.nameWithoutExtension};$text" if (forceUsePackageFolder) { val packageName = fileText.substring( "package".length, fileText.indexOfAny(charArrayOf(';', '\n')), ).trim() val projectFileName = packageName.replace('.', '/') + "/" + file.name addFileToProject(projectFileName, fileText) } else { configureByText(file.name, fileText)!! } } file.extension == "gradle" -> { val text = FileUtil.loadFile(file, true) val kgpArtifactVersion = KotlinPluginLayout.standaloneCompilerVersion.artifactVersion val fileText = text.replace("\$PLUGIN_VERSION", kgpArtifactVersion) configureByText(file.name, fileText)!! } else -> { val filePath = file.relativeTo(srcDir).invariantSeparatorsPath configureByFile(filePath) } } }.toList() configureCodeStyleAndRun( project, configurator = { FormatSettingsUtil.createConfigurator(options, it).configureSettings() } ) { configureRegistryAndRun(options) { try { fixtureClasses.forEach { TestFixtureExtension.loadFixture(it, myFixture.module) } configExtra(psiFiles, options) val presentation = runInspection( inspectionClass, project, settings = settingsElement, files = psiFiles.map { it.virtualFile!! }, withTestDir = inspectionsTestDir.path, ) if (afterFiles.isNotEmpty()) { presentation.problemDescriptors.forEach { problem -> problem.fixes?.forEach { quickFix -> project.executeWriteCommand(quickFix.name, quickFix.familyName) { quickFix.applyFix(project, problem) } } } for (filePath in afterFiles) { val kotlinFile = psiFiles.first { filePath.name == it.name + ".after" } KotlinTestUtils.assertEqualsToFile(filePath, kotlinFile.text) } } } finally { fixtureClasses.forEach { TestFixtureExtension.unloadFixture(it) } } } } } } } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/AbstractInspectionTest.kt
3583347938
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.impl import com.intellij.execution.* import com.intellij.execution.configuration.ConfigurationFactoryEx import com.intellij.execution.configurations.* import com.intellij.execution.dashboard.RunDashboardManager import com.intellij.execution.impl.RunConfigurable.Companion.collectNodesRecursively import com.intellij.execution.impl.RunConfigurableNodeKind.* import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.options.* import com.intellij.openapi.project.Project import com.intellij.openapi.ui.LabeledComponent.create import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.VerticalFlowLayout import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Pair import com.intellij.openapi.util.Trinity import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.IdeFocusManager import com.intellij.openapi.wm.IdeFocusManager.getGlobalInstance import com.intellij.ui.* import com.intellij.ui.RowsDnDSupport.RefinedDropSupport.Position.* import com.intellij.ui.components.JBLabel import com.intellij.ui.components.labels.ActionLink import com.intellij.ui.treeStructure.Tree import com.intellij.util.ArrayUtilRt import com.intellij.util.IconUtil import com.intellij.util.PlatformIcons import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.HashMap import com.intellij.util.containers.nullize import com.intellij.util.ui.* import com.intellij.util.ui.tree.TreeUtil import gnu.trove.THashSet import gnu.trove.TObjectIntHashMap import net.miginfocom.swing.MigLayout import java.awt.* import java.awt.event.KeyEvent import java.util.* import java.util.function.ToIntFunction import java.util.stream.Collectors import javax.swing.* import javax.swing.border.EmptyBorder import javax.swing.event.DocumentEvent import javax.swing.tree.* private val DEFAULTS = object : Any() { override fun toString() = "Defaults" } private val INITIAL_VALUE_KEY = "initialValue" private val LOG = logger<RunConfigurable>() private fun getName(userObject: Any): String { return when { userObject is ConfigurationType -> userObject.displayName userObject === DEFAULTS -> "Defaults" userObject is ConfigurationFactory -> userObject.name //Folder objects are strings else -> if (userObject is SingleConfigurationConfigurable<*>) userObject.nameText else (userObject as? RunnerAndConfigurationSettingsImpl)?.name ?: userObject.toString() } } open class RunConfigurable @JvmOverloads constructor(private val myProject: Project, private var myRunDialog: RunDialogBase? = null) : BaseConfigurable(), Disposable { @Volatile private var isDisposed: Boolean = false val root = DefaultMutableTreeNode("Root") val treeModel = MyTreeModel(root) val tree = Tree(treeModel) private val rightPanel = JPanel(BorderLayout()) private val splitter = JBSplitter("RunConfigurable.dividerProportion", 0.3f) private var wholePanel: JPanel? = null private var selectedConfigurable: Configurable? = null private val recentsLimit = JTextField("5", 2) private val confirmation = JCheckBox(ExecutionBundle.message("rerun.confirmation.checkbox"), true) private val additionalSettings = ArrayList<Pair<UnnamedConfigurable, JComponent>>() private val storedComponents = HashMap<ConfigurationFactory, Configurable>() private var toolbarDecorator: ToolbarDecorator? = null private var isFolderCreating: Boolean = false private val toolbarAddAction = MyToolbarAddAction() private val runDashboardTypes = ContainerUtil.newHashSet<String>() private val hiddenRunDashboardTypesList = RunDashboardTypesList(myProject) private val shownRunDashboardTypesList = RunDashboardTypesList(myProject) companion object { fun collectNodesRecursively(parentNode: DefaultMutableTreeNode, nodes: MutableList<DefaultMutableTreeNode>, vararg allowed: RunConfigurableNodeKind) { for (i in 0 until parentNode.childCount) { val child = parentNode.getChildAt(i) as DefaultMutableTreeNode if (ArrayUtilRt.find(allowed, getKind(child)) != -1) { nodes.add(child) } collectNodesRecursively(child, nodes, *allowed) } } fun getKind(node: DefaultMutableTreeNode?): RunConfigurableNodeKind { if (node == null) { return UNKNOWN } val userObject = node.userObject return when (userObject) { is SingleConfigurationConfigurable<*>, is RunnerAndConfigurationSettings -> { val settings = getSettings(node) ?: return UNKNOWN if (settings.isTemporary) TEMPORARY_CONFIGURATION else CONFIGURATION } is String -> FOLDER else -> if (userObject is ConfigurationType) CONFIGURATION_TYPE else UNKNOWN } } } override fun getDisplayName(): String = ExecutionBundle.message("run.configurable.display.name") private fun initTree() { tree.isRootVisible = false tree.showsRootHandles = true UIUtil.setLineStyleAngled(tree) TreeUtil.installActions(tree) TreeSpeedSearch(tree) { o -> val node = o.lastPathComponent as DefaultMutableTreeNode val userObject = node.userObject when (userObject) { is RunnerAndConfigurationSettingsImpl -> return@TreeSpeedSearch userObject.name is SingleConfigurationConfigurable<*> -> return@TreeSpeedSearch userObject.nameText else -> if (userObject is ConfigurationType) { return@TreeSpeedSearch userObject.displayName } else if (userObject is String) { return@TreeSpeedSearch userObject } } o.toString() } tree.cellRenderer = object : ColoredTreeCellRenderer() { override fun customizeCellRenderer(tree: JTree, value: Any, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean) { if (value is DefaultMutableTreeNode) { val userObject = value.userObject var shared: Boolean? = null val name = getName(userObject) if (userObject is ConfigurationType) { append(name, if ((value.parent as DefaultMutableTreeNode).isRoot) SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES else SimpleTextAttributes.REGULAR_ATTRIBUTES) icon = userObject.icon } else if (userObject === DEFAULTS) { append(name, SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES) icon = AllIcons.General.Settings } else if (userObject is String) {//Folders append(name, SimpleTextAttributes.REGULAR_ATTRIBUTES) icon = AllIcons.Nodes.Folder } else if (userObject is ConfigurationFactory) { append(name) icon = userObject.icon } else { var configuration: RunnerAndConfigurationSettings? = null if (userObject is SingleConfigurationConfigurable<*>) { val configurationSettings: RunnerAndConfigurationSettings = userObject.settings configuration = configurationSettings shared = userObject.isStoreProjectConfiguration icon = ProgramRunnerUtil.getConfigurationIcon(configurationSettings, !userObject.isValid) } else if (userObject is RunnerAndConfigurationSettingsImpl) { val settings = userObject as RunnerAndConfigurationSettings shared = settings.isShared icon = RunManagerEx.getInstanceEx(myProject).getConfigurationIcon(settings) configuration = settings } if (configuration != null) { append(name, if (configuration.isTemporary) SimpleTextAttributes.GRAY_ATTRIBUTES else SimpleTextAttributes.REGULAR_ATTRIBUTES) } } if (shared != null) { val icon = icon val layeredIcon = LayeredIcon(icon, if (shared) AllIcons.Nodes.Shared else EmptyIcon.ICON_16) setIcon(layeredIcon) iconTextGap = 0 } else { iconTextGap = 2 } } } } val manager = runManager for (type in manager.configurationFactories) { val configurations = manager.getConfigurationSettingsList(type).nullize() ?: continue val typeNode = DefaultMutableTreeNode(type) root.add(typeNode) val folderMapping = HashMap<String, DefaultMutableTreeNode>() var folderCounter = 0 for (configuration in configurations) { val folder = configuration.folderName if (folder != null) { var node: DefaultMutableTreeNode? = folderMapping[folder] if (node == null) { node = DefaultMutableTreeNode(folder) typeNode.insert(node, folderCounter) folderCounter++ folderMapping.put(folder, node) } node.add(DefaultMutableTreeNode(configuration)) } else { typeNode.add(DefaultMutableTreeNode(configuration)) } } } // add defaults val defaults = DefaultMutableTreeNode(DEFAULTS) for (type in RunManagerImpl.getInstanceImpl(myProject).configurationFactoriesWithoutUnknown) { val configurationFactories = type.configurationFactories val typeNode = DefaultMutableTreeNode(type) defaults.add(typeNode) if (configurationFactories.size != 1) { for (factory in configurationFactories) { typeNode.add(DefaultMutableTreeNode(factory)) } } } if (defaults.childCount > 0) { root.add(defaults) } tree.addTreeSelectionListener { val selectionPath = tree.selectionPath if (selectionPath != null) { val node = selectionPath.lastPathComponent as DefaultMutableTreeNode val userObject = getSafeUserObject(node) if (userObject is SingleConfigurationConfigurable<*>) { @Suppress("UNCHECKED_CAST") updateRightPanel(userObject as SingleConfigurationConfigurable<RunConfiguration>) } else if (userObject is String) { showFolderField(node, userObject) } else { if (userObject is ConfigurationType || userObject === DEFAULTS) { val parent = node.parent as DefaultMutableTreeNode if (parent.isRoot) { drawPressAddButtonMessage(if (userObject === DEFAULTS) null else userObject as ConfigurationType) } else { val factories = (userObject as ConfigurationType).configurationFactories if (factories.size == 1) { showTemplateConfigurable(factories[0]) } else { drawPressAddButtonMessage(userObject) } } } else if (userObject is ConfigurationFactory) { showTemplateConfigurable(userObject) } } } updateDialog() } tree.registerKeyboardAction({ clickDefaultButton() }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED) sortTopLevelBranches() (tree.model as DefaultTreeModel).reload() } fun selectConfigurableOnShow(option: Boolean): RunConfigurable { if (!option) return this SwingUtilities.invokeLater { if (isDisposed) return@invokeLater tree.requestFocusInWindow() val settings = runManager.selectedConfiguration if (settings != null) { if (selectConfiguration(settings.configuration)) { return@invokeLater } } else { selectedConfigurable = null } //TreeUtil.selectInTree(defaults, true, myTree); drawPressAddButtonMessage(null) } return this } private fun selectConfiguration(configuration: RunConfiguration): Boolean { val enumeration = root.breadthFirstEnumeration() while (enumeration.hasMoreElements()) { val node = enumeration.nextElement() as DefaultMutableTreeNode var userObject = node.userObject if (userObject is SettingsEditorConfigurable<*>) { userObject = userObject.settings } if (userObject is RunnerAndConfigurationSettingsImpl) { val runnerAndConfigurationSettings = userObject as RunnerAndConfigurationSettings val configurationType = configuration.type if (Comparing.strEqual(runnerAndConfigurationSettings.configuration.type.id, configurationType.id) && Comparing.strEqual( runnerAndConfigurationSettings.configuration.name, configuration.name)) { TreeUtil.selectInTree(node, true, tree) return true } } } return false } private fun showTemplateConfigurable(factory: ConfigurationFactory) { var configurable: Configurable? = storedComponents[factory] if (configurable == null) { configurable = TemplateConfigurable(RunManagerImpl.getInstanceImpl(myProject).getConfigurationTemplate(factory)) storedComponents.put(factory, configurable) configurable.reset() } updateRightPanel(configurable) } private fun showFolderField(node: DefaultMutableTreeNode, folderName: String) { rightPanel.removeAll() val p = JPanel(MigLayout("ins ${toolbarDecorator!!.actionsPanel.height} 5 0 0, flowx")) val textField = JTextField(folderName) textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { node.userObject = textField.text treeModel.reload(node) } }) textField.addActionListener { getGlobalInstance().doWhenFocusSettlesDown { getGlobalInstance().requestFocus(tree, true) } } p.add(JLabel("Folder name:"), "gapright 5") p.add(textField, "pushx, growx, wrap") p.add(JLabel(ExecutionBundle.message("run.configuration.rename.folder.disclaimer")), "gaptop 5, spanx 2") rightPanel.add(p) rightPanel.revalidate() rightPanel.repaint() if (isFolderCreating) { textField.selectAll() getGlobalInstance().doWhenFocusSettlesDown { getGlobalInstance().requestFocus(textField, true) } } } private fun getSafeUserObject(node: DefaultMutableTreeNode): Any { val userObject = node.userObject if (userObject is RunnerAndConfigurationSettingsImpl) { val configurationConfigurable = SingleConfigurationConfigurable.editSettings<RunConfiguration>(userObject as RunnerAndConfigurationSettings, null) installUpdateListeners(configurationConfigurable) node.userObject = configurationConfigurable return configurationConfigurable } return userObject } fun setRunDialog(runDialog: RunDialogBase) { myRunDialog = runDialog } fun updateRightPanel(configurable: Configurable) { rightPanel.removeAll() selectedConfigurable = configurable val configurableComponent = configurable.createComponent() rightPanel.add(BorderLayout.CENTER, configurableComponent) if (configurable is SingleConfigurationConfigurable<*>) { rightPanel.add(configurable.validationComponent, BorderLayout.SOUTH) ApplicationManager.getApplication().invokeLater { configurable.updateWarning() } if (configurableComponent != null) { val dataProvider = DataManager.getDataProvider(configurableComponent) if (dataProvider != null) { DataManager.registerDataProvider(rightPanel, dataProvider) } } } setupDialogBounds() } private fun sortTopLevelBranches() { val expandedPaths = TreeUtil.collectExpandedPaths(tree) TreeUtil.sortRecursively(root) { o1, o2 -> val userObject1 = o1.userObject val userObject2 = o2.userObject when { userObject1 is ConfigurationType && userObject2 is ConfigurationType -> (userObject1).displayName.compareTo(userObject2.displayName) userObject1 === DEFAULTS && userObject2 is ConfigurationType -> 1 userObject2 === DEFAULTS && userObject1 is ConfigurationType -> - 1 else -> 0 } } TreeUtil.restoreExpandedPaths(tree, expandedPaths) } private fun update() { updateDialog() val selectionPath = tree.selectionPath if (selectionPath != null) { val node = selectionPath.lastPathComponent as DefaultMutableTreeNode treeModel.reload(node) } } private fun installUpdateListeners(info: SingleConfigurationConfigurable<RunConfiguration>) { val changed = booleanArrayOf(false) info.editor.addSettingsEditorListener { editor -> update() val configuration = info.configuration if (configuration is LocatableConfiguration) { if (configuration.isGeneratedName && !changed[0]) { try { val snapshot = editor.snapshot.configuration as LocatableConfiguration val generatedName = snapshot.suggestedName() if (generatedName != null && generatedName.isNotEmpty()) { info.nameText = generatedName changed[0] = false } } catch (ignore: ConfigurationException) { } } } setupDialogBounds() } info.addNameListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { changed[0] = true update() } }) info.addSharedListener { changed[0] = true update() } } private fun drawPressAddButtonMessage(configurationType: ConfigurationType?) { val panel = JPanel(FlowLayout(FlowLayout.LEFT, 0, 0)) panel.border = EmptyBorder(30, 0, 0, 0) panel.add(JLabel("Press the")) val addIcon = ActionLink("", IconUtil.getAddIcon(), toolbarAddAction) addIcon.border = EmptyBorder(0, 0, 0, 5) panel.add(addIcon) val configurationTypeDescription = if (configurationType != null) configurationType.configurationTypeDescription else ExecutionBundle.message("run.configuration.default.type.description") panel.add(JLabel(ExecutionBundle.message("empty.run.configuration.panel.text.label3", configurationTypeDescription))) val scrollPane = ScrollPaneFactory.createScrollPane(panel, true) rightPanel.removeAll() rightPanel.add(scrollPane, BorderLayout.CENTER) if (configurationType == null) { val settingsPanel = JPanel(GridBagLayout()) val grid = GridBag().setDefaultAnchor(GridBagConstraints.NORTHWEST) for (each in additionalSettings) { settingsPanel.add(each.second, grid.nextLine().next()) } settingsPanel.add(createSettingsPanel(), grid.nextLine().next()) val settingsWrapper = JPanel(BorderLayout()) settingsWrapper.add(settingsPanel, BorderLayout.WEST) settingsWrapper.add(Box.createGlue(), BorderLayout.CENTER) if (Registry.`is`("ide.run.dashboard.types.configuration") || ApplicationManager.getApplication().isInternal) { val wrapper = JPanel(BorderLayout()) wrapper.add(createRunDashboardTypesPanel(), BorderLayout.CENTER) wrapper.add(settingsWrapper, BorderLayout.SOUTH) rightPanel.add(wrapper, BorderLayout.SOUTH) } else { rightPanel.add(settingsWrapper, BorderLayout.SOUTH) } } rightPanel.revalidate() rightPanel.repaint() } private fun createLeftPanel(): JPanel { initTree() val removeAction = MyRemoveAction() val moveUpAction = MyMoveAction(ExecutionBundle.message("move.up.action.name"), null, IconUtil.getMoveUpIcon(), -1) val moveDownAction = MyMoveAction(ExecutionBundle.message("move.down.action.name"), null, IconUtil.getMoveDownIcon(), 1) toolbarDecorator = ToolbarDecorator.createDecorator(tree).setAsUsualTopToolbar() .setAddAction(toolbarAddAction).setAddActionName(ExecutionBundle.message("add.new.run.configuration.action2.name")) .setRemoveAction(removeAction).setRemoveActionUpdater(removeAction) .setRemoveActionName(ExecutionBundle.message("remove.run.configuration.action.name")) .setMoveUpAction(moveUpAction).setMoveUpActionName(ExecutionBundle.message("move.up.action.name")).setMoveUpActionUpdater( moveUpAction) .setMoveDownAction(moveDownAction).setMoveDownActionName(ExecutionBundle.message("move.down.action.name")).setMoveDownActionUpdater( moveDownAction) .addExtraAction(AnActionButton.fromAction(MyCopyAction())) .addExtraAction(AnActionButton.fromAction(MySaveAction())) .addExtraAction(AnActionButton.fromAction(MyEditDefaultsAction())) .addExtraAction(AnActionButton.fromAction(MyCreateFolderAction())) .addExtraAction(AnActionButton.fromAction(MySortFolderAction())) .setMinimumSize(JBDimension(200, 200)) .setButtonComparator(ExecutionBundle.message("add.new.run.configuration.action2.name"), ExecutionBundle.message("remove.run.configuration.action.name"), ExecutionBundle.message("copy.configuration.action.name"), ExecutionBundle.message("action.name.save.configuration"), ExecutionBundle.message("run.configuration.edit.default.configuration.settings.text"), ExecutionBundle.message("move.up.action.name"), ExecutionBundle.message("move.down.action.name"), ExecutionBundle.message("run.configuration.create.folder.text") ).setForcedDnD() return toolbarDecorator!!.createPanel() } private fun createSettingsPanel(): JPanel { val bottomPanel = JPanel(GridBagLayout()) val g = GridBag() bottomPanel.add(confirmation, g.nextLine().insets(JBUI.insets(10, 0, 0, 0)).anchor(GridBagConstraints.WEST)) bottomPanel.add(create(recentsLimit, ExecutionBundle.message("temporary.configurations.limit"), BorderLayout.WEST), g.nextLine().insets(JBUI.insets(10, 0, 0, 0)).anchor(GridBagConstraints.WEST)) recentsLimit.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { isModified = !Comparing.equal(recentsLimit.text, recentsLimit.getClientProperty(INITIAL_VALUE_KEY)) } }) confirmation.addChangeListener { isModified = !Comparing.equal(confirmation.isSelected, confirmation.getClientProperty(INITIAL_VALUE_KEY)) } return bottomPanel } private fun createRunDashboardTypesPanel(): JComponent { updateRunDashboardTypes() val buttonsPanel = JPanel(VerticalFlowLayout()) buttonsPanel.add(JButton(ExecutionBundle.message("run.dashboard.configurable.show")).apply { addActionListener { changeRunDashboardTypes(false, true) } }) buttonsPanel.add(JButton(ExecutionBundle.message("run.dashboard.configurable.hide")).apply { addActionListener { changeRunDashboardTypes(false, false) } }) buttonsPanel.add(JButton(ExecutionBundle.message("run.dashboard.configurable.show.all")).apply { addActionListener { changeRunDashboardTypes(true, true) } }) buttonsPanel.add(JButton(ExecutionBundle.message("run.dashboard.configurable.hide.all")).apply { addActionListener { changeRunDashboardTypes(true, false) } }) val gridBag = GridBag().setDefaultWeightX(0, 0.5).setDefaultWeightX(1, 0.0).setDefaultWeightX(2, 0.5) val treesPanel = JPanel(GridBagLayout()) val hiddenLabel = JBLabel(ExecutionBundle.message("run.dashboard.configurable.hidden.label")) val shownLabel = JBLabel(ExecutionBundle.message("run.dashboard.configurable.shown.label")) val hiddenSize = hiddenLabel.minimumSize val shownSize = shownLabel.minimumSize if (hiddenSize.width < shownSize.width) { val size = Dimension(shownSize.width, hiddenSize.height) hiddenLabel.minimumSize = size hiddenLabel.preferredSize = size hiddenLabel.maximumSize = size } else { val size = Dimension(hiddenSize.width, shownSize.height) shownLabel.minimumSize = size shownLabel.preferredSize = size shownLabel.maximumSize = size } treesPanel.add(hiddenLabel, gridBag.nextLine().next().anchor(GridBagConstraints.WEST)) treesPanel.add(shownLabel, gridBag.next().next().anchor(GridBagConstraints.WEST)) treesPanel.add(hiddenRunDashboardTypesList.component, gridBag.nextLine().next().weighty(1.0).fillCell()) treesPanel.add(buttonsPanel, gridBag.next().anchor(GridBagConstraints.CENTER)) treesPanel.add(shownRunDashboardTypesList.component, gridBag.next().weighty(1.0).fillCell()) return treesPanel } private fun updateRunDashboardTypes() { hiddenRunDashboardTypesList.updateModel(runDashboardTypes, false) shownRunDashboardTypesList.updateModel(runDashboardTypes, true) val hiddenSize = hiddenRunDashboardTypesList.component.preferredSize val shownSize = shownRunDashboardTypesList.component.preferredSize if (hiddenSize.width < shownSize.width) { hiddenRunDashboardTypesList.component.preferredSize = Dimension(shownSize.width, hiddenSize.height) } else { shownRunDashboardTypesList.component.preferredSize = Dimension(hiddenSize.width, shownSize.height) } } private fun changeRunDashboardTypes(all: Boolean, show: Boolean) { val list = if (show) hiddenRunDashboardTypesList else shownRunDashboardTypesList val types = if (all) list.allTypes else list.selectedTypes val ids = types.stream().map(ConfigurationType::getId).collect(Collectors.toSet<String>()) if (show) { runDashboardTypes.addAll(ids) } else { runDashboardTypes.removeAll(ids) } updateRunDashboardTypes() isModified = !Comparing.equal(runDashboardTypes, RunDashboardManager.getInstance(myProject).types) } private val selectedConfigurationType: ConfigurationType? get() { val configurationTypeNode = selectedConfigurationTypeNode return if (configurationTypeNode != null) configurationTypeNode.userObject as ConfigurationType else null } override fun createComponent(): JComponent? { for (each in Extensions.getExtensions(RunConfigurationsSettings.EXTENSION_POINT, myProject)) { val configurable = each.createConfigurable() additionalSettings.add(Pair.create(configurable, configurable.createComponent())) } wholePanel = JPanel(BorderLayout()) DataManager.registerDataProvider(wholePanel!!) { dataId -> if (RunConfigurationSelector.KEY.name == dataId) RunConfigurationSelector { configuration -> selectConfiguration(configuration) } else null } splitter.firstComponent = createLeftPanel() splitter.setHonorComponentsMinimumSize(true) splitter.secondComponent = rightPanel wholePanel!!.add(splitter, BorderLayout.CENTER) updateDialog() val d = wholePanel!!.preferredSize d.width = Math.max(d.width, 800) d.height = Math.max(d.height, 600) wholePanel!!.preferredSize = d return wholePanel } override fun reset() { val manager = runManager val config = manager.config recentsLimit.text = Integer.toString(config.recentsLimit) recentsLimit.putClientProperty(INITIAL_VALUE_KEY, recentsLimit.text) confirmation.isSelected = config.isRestartRequiresConfirmation confirmation.putClientProperty(INITIAL_VALUE_KEY, confirmation.isSelected) runDashboardTypes.clear() runDashboardTypes.addAll(RunDashboardManager.getInstance(myProject).types) for (each in additionalSettings) { each.first.reset() } isModified = false } @Throws(ConfigurationException::class) override fun apply() { val manager = runManager manager.fireBeginUpdate() try { val settingsToOrder = TObjectIntHashMap<RunnerAndConfigurationSettings>() var order = 0 val toDeleteSettings = THashSet(manager.allSettings) val selectedSettings = selectedSettings for (i in 0 until root.childCount) { val node = root.getChildAt(i) as DefaultMutableTreeNode val userObject = node.userObject if (userObject is ConfigurationType) { for (bean in applyByType(node, userObject, selectedSettings)) { settingsToOrder.put(bean.settings, order++) toDeleteSettings.remove(bean.settings) } } } manager.removeConfigurations(toDeleteSettings) val recentLimit = Math.max(RunManagerConfig.MIN_RECENT_LIMIT, StringUtil.parseInt(recentsLimit.text, 0)) if (manager.config.recentsLimit != recentLimit) { manager.config.recentsLimit = recentLimit manager.checkRecentsLimit() } manager.config.isRestartRequiresConfirmation = confirmation.isSelected val dashboardManager = RunDashboardManager.getInstance(myProject) if (!Comparing.equal(runDashboardTypes, dashboardManager.types)) { dashboardManager.types = runDashboardTypes } for (configurable in storedComponents.values) { if (configurable.isModified) { configurable.apply() } } additionalSettings.forEach { it.first.apply() } manager.setOrder(Comparator.comparingInt(ToIntFunction<RunnerAndConfigurationSettings> { settingsToOrder.get(it) })) } finally { manager.fireEndUpdate() } updateActiveConfigurationFromSelected() isModified = false tree.repaint() } fun updateActiveConfigurationFromSelected() { if (selectedConfigurable != null && selectedConfigurable is SingleConfigurationConfigurable<*>) { runManager.selectedConfiguration = (selectedConfigurable as SingleConfigurationConfigurable<*>).settings as RunnerAndConfigurationSettings } } @Throws(ConfigurationException::class) private fun applyByType(typeNode: DefaultMutableTreeNode, type: ConfigurationType, selectedSettings: RunnerAndConfigurationSettings?): List<RunConfigurationBean> { var indexToMove = -1 val configurationBeans = ArrayList<RunConfigurationBean>() val names = THashSet<String>() val configurationNodes = ArrayList<DefaultMutableTreeNode>() collectNodesRecursively(typeNode, configurationNodes, CONFIGURATION, TEMPORARY_CONFIGURATION) for (node in configurationNodes) { val userObject = node.userObject var configurationBean: RunConfigurationBean? = null var settings: RunnerAndConfigurationSettings? = null if (userObject is SingleConfigurationConfigurable<*>) { settings = userObject.settings as RunnerAndConfigurationSettings applyConfiguration(typeNode, userObject) configurationBean = RunConfigurationBean(userObject) } else if (userObject is RunnerAndConfigurationSettingsImpl) { settings = userObject configurationBean = RunConfigurationBean(settings) } if (configurationBean != null) { val configurable = configurationBean.configurable val nameText = if (configurable != null) configurable.nameText else configurationBean.settings.name if (!names.add(nameText)) { TreeUtil.selectNode(tree, node) throw ConfigurationException(type.displayName + " with name \'" + nameText + "\' already exists") } configurationBeans.add(configurationBean) if (settings === selectedSettings) { indexToMove = configurationBeans.size - 1 } } } val folderNodes = ArrayList<DefaultMutableTreeNode>() collectNodesRecursively(typeNode, folderNodes, FOLDER) names.clear() for (node in folderNodes) { val folderName = node.userObject as String if (folderName.isEmpty()) { TreeUtil.selectNode(tree, node) throw ConfigurationException("Folder name shouldn't be empty") } if (!names.add(folderName)) { TreeUtil.selectNode(tree, node) throw ConfigurationException("Folders name \'$folderName\' is duplicated") } } // try to apply all for (bean in configurationBeans) { applyConfiguration(typeNode, bean.configurable) } // just saved as 'stable' configuration shouldn't stay between temporary ones (here we order model to save) var shift = 0 if (selectedSettings != null && selectedSettings.type === type) { shift = adjustOrder() } if (shift != 0 && indexToMove != -1) { configurationBeans.add(indexToMove - shift, configurationBeans.removeAt(indexToMove)) } return configurationBeans } private fun getConfigurationTypeNode(type: ConfigurationType): DefaultMutableTreeNode? { for (i in 0 until root.childCount) { val node = root.getChildAt(i) as DefaultMutableTreeNode if (node.userObject === type) { return node } } return null } @Throws(ConfigurationException::class) private fun applyConfiguration(typeNode: DefaultMutableTreeNode, configurable: SingleConfigurationConfigurable<*>?) { try { if (configurable != null && configurable.isModified) { configurable.apply() } } catch (e: ConfigurationException) { for (i in 0 until typeNode.childCount) { val node = typeNode.getChildAt(i) as DefaultMutableTreeNode if (Comparing.equal(configurable, node.userObject)) { TreeUtil.selectNode(tree, node) break } } throw e } } override fun isModified(): Boolean { if (super.isModified()) { return true } val runManager = runManager val allSettings = runManager.allSettings var currentSettingCount = 0 for (i in 0 until root.childCount) { val typeNode = root.getChildAt(i) as DefaultMutableTreeNode val `object` = typeNode.userObject as? ConfigurationType ?: continue val configurationNodes = ArrayList<DefaultMutableTreeNode>() collectNodesRecursively(typeNode, configurationNodes, CONFIGURATION, TEMPORARY_CONFIGURATION) if (countSettingsOfType(allSettings, `object`) != configurationNodes.size) { return true } for (configurationNode in configurationNodes) { val userObject = configurationNode.userObject val settings: RunnerAndConfigurationSettings if (userObject is SingleConfigurationConfigurable<*>) { if (userObject.isModified) { return true } settings = userObject.settings as RunnerAndConfigurationSettings } else if (userObject is RunnerAndConfigurationSettings) { settings = userObject } else { continue } val index = currentSettingCount++ // we compare by instance, equals is not implemented and in any case object modification is checked by other logic if (allSettings.size <= index || allSettings[index] !== settings) { return true } } } if (allSettings.size != currentSettingCount) { return true } for (configurable in storedComponents.values) { if (configurable.isModified) return true } for (each in additionalSettings) { if (each.first.isModified) return true } return false } override fun disposeUIResources() { Disposer.dispose(this) } override fun dispose() { isDisposed = true storedComponents.values.forEach { it.disposeUIResources() } storedComponents.clear() additionalSettings.forEach { it.first.disposeUIResources() } TreeUtil.traverseDepth(root) { node -> if (node is DefaultMutableTreeNode) { val userObject = node.userObject (userObject as? SingleConfigurationConfigurable<*>)?.disposeUIResources() } true } rightPanel.removeAll() splitter.dispose() } private fun updateDialog() { val executor = (if (myRunDialog != null) myRunDialog!!.executor else null) ?: return val buffer = StringBuilder() buffer.append(executor.id) val configuration = selectedConfiguration if (configuration != null) { buffer.append(" - ") buffer.append(configuration.nameText) } myRunDialog!!.setOKActionEnabled(canRunConfiguration(configuration, executor)) myRunDialog!!.setTitle(buffer.toString()) } private fun setupDialogBounds() { SwingUtilities.invokeLater { UIUtil.setupEnclosingDialogBounds(wholePanel!!) } } private val selectedConfiguration: SingleConfigurationConfigurable<RunConfiguration>? get() { val selectionPath = tree.selectionPath if (selectionPath != null) { val treeNode = selectionPath.lastPathComponent as DefaultMutableTreeNode val userObject = treeNode.userObject if (userObject is SingleConfigurationConfigurable<*>) { @Suppress("UNCHECKED_CAST") return userObject as SingleConfigurationConfigurable<RunConfiguration> } } return null } open val runManager: RunManagerImpl get() = RunManagerImpl.getInstanceImpl(myProject) override fun getHelpTopic(): String? { val type = selectedConfigurationType ?: return "reference.dialogs.rundebug" return "reference.dialogs.rundebug.${type.id}" } private fun clickDefaultButton() { myRunDialog?.clickDefaultButton() } private val selectedConfigurationTypeNode: DefaultMutableTreeNode? get() { val selectionPath = tree.selectionPath var node: DefaultMutableTreeNode? = if (selectionPath != null) selectionPath.lastPathComponent as DefaultMutableTreeNode else null while (node != null) { val userObject = node.userObject if (userObject is ConfigurationType) { return node } node = node.parent as DefaultMutableTreeNode } return null } private fun getNode(row: Int) = tree.getPathForRow(row).lastPathComponent as DefaultMutableTreeNode fun getAvailableDropPosition(direction: Int): Trinity<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>? { val rows = tree.selectionRows if (rows == null || rows.size != 1) { return null } val oldIndex = rows[0] var newIndex = oldIndex + direction if (!getKind(tree.getPathForRow(oldIndex).lastPathComponent as DefaultMutableTreeNode).supportsDnD()) { return null } while (newIndex > 0 && newIndex < tree.rowCount) { val targetPath = tree.getPathForRow(newIndex) val allowInto = getKind(targetPath.lastPathComponent as DefaultMutableTreeNode) == FOLDER && !tree.isExpanded(targetPath) val position = when { allowInto && treeModel.isDropInto(tree, oldIndex, newIndex) -> INTO direction > 0 -> BELOW else -> ABOVE } val oldNode = getNode(oldIndex) val newNode = getNode(newIndex) if (oldNode.parent !== newNode.parent && getKind(newNode) != FOLDER) { var copy = position if (position == BELOW) { copy = ABOVE } else if (position == ABOVE) { copy = BELOW } if (treeModel.canDrop(oldIndex, newIndex, copy)) { return Trinity.create(oldIndex, newIndex, copy) } } if (treeModel.canDrop(oldIndex, newIndex, position)) { return Trinity.create(oldIndex, newIndex, position) } when { position == BELOW && newIndex < tree.rowCount - 1 && treeModel.canDrop(oldIndex, newIndex + 1, ABOVE) -> return Trinity.create(oldIndex, newIndex + 1, ABOVE) position == ABOVE && newIndex > 1 && treeModel.canDrop(oldIndex, newIndex - 1, BELOW) -> return Trinity.create(oldIndex, newIndex - 1, BELOW) position == BELOW && treeModel.canDrop(oldIndex, newIndex, ABOVE) -> return Trinity.create(oldIndex, newIndex, ABOVE) position == ABOVE && treeModel.canDrop(oldIndex, newIndex, BELOW) -> return Trinity.create(oldIndex, newIndex, BELOW) else -> newIndex += direction } } return null } private fun createNewConfiguration(settings: RunnerAndConfigurationSettings, node: DefaultMutableTreeNode?, selectedNode: DefaultMutableTreeNode?): SingleConfigurationConfigurable<RunConfiguration> { val configurationConfigurable = SingleConfigurationConfigurable.editSettings<RunConfiguration>(settings, null) installUpdateListeners(configurationConfigurable) val nodeToAdd = DefaultMutableTreeNode(configurationConfigurable) treeModel.insertNodeInto(nodeToAdd, node!!, if (selectedNode != null) node.getIndex(selectedNode) + 1 else node.childCount) TreeUtil.selectNode(tree, nodeToAdd) return configurationConfigurable } fun createNewConfiguration(factory: ConfigurationFactory): SingleConfigurationConfigurable<RunConfiguration> { var node: DefaultMutableTreeNode var selectedNode: DefaultMutableTreeNode? = null val selectionPath = tree.selectionPath if (selectionPath != null) { selectedNode = selectionPath.lastPathComponent as DefaultMutableTreeNode } var typeNode = getConfigurationTypeNode(factory.type) if (typeNode == null) { typeNode = DefaultMutableTreeNode(factory.type) root.add(typeNode) sortTopLevelBranches() (tree.model as DefaultTreeModel).reload() } node = typeNode if (selectedNode != null && typeNode.isNodeDescendant(selectedNode)) { node = selectedNode if (getKind(node).isConfiguration) { node = node.parent as DefaultMutableTreeNode } } val settings = runManager.createConfiguration(createUniqueName(typeNode, null, CONFIGURATION, TEMPORARY_CONFIGURATION), factory) @Suppress("UNCHECKED_CAST") (factory as? ConfigurationFactoryEx<RunConfiguration>)?.onNewConfigurationCreated(settings.configuration) return createNewConfiguration(settings, node, selectedNode) } private inner class MyToolbarAddAction : AnAction(ExecutionBundle.message("add.new.run.configuration.action2.name"), ExecutionBundle.message("add.new.run.configuration.action2.name"), IconUtil.getAddIcon()), AnActionButtonRunnable { init { registerCustomShortcutSet(CommonShortcuts.INSERT, tree) } override fun actionPerformed(e: AnActionEvent) { showAddPopup(true) } override fun run(button: AnActionButton) { showAddPopup(true) } private fun showAddPopup(showApplicableTypesOnly: Boolean) { val allTypes = runManager.configurationFactoriesWithoutUnknown val configurationTypes: MutableList<ConfigurationType?> = getTypesToShow(showApplicableTypesOnly, allTypes).toMutableList() configurationTypes.sortWith(kotlin.Comparator { type1, type2 -> type1!!.displayName.compareTo(type2!!.displayName, ignoreCase = true) }) val hiddenCount = allTypes.size - configurationTypes.size if (hiddenCount > 0) { configurationTypes.add(null) } val popup = NewRunConfigurationPopup.createAddPopup(configurationTypes, "$hiddenCount items more (irrelevant)...", { factory -> createNewConfiguration(factory) }, selectedConfigurationType, { showAddPopup(false) }, true) //new TreeSpeedSearch(myTree); popup.showUnderneathOf(toolbarDecorator!!.actionsPanel) } private fun getTypesToShow(showApplicableTypesOnly: Boolean, allTypes: List<ConfigurationType>): List<ConfigurationType> { if (showApplicableTypesOnly) { val applicableTypes = allTypes.filter { isApplicable(it) } if (applicableTypes.size < (allTypes.size - 3)) { return applicableTypes } } return allTypes } private fun isApplicable(type: ConfigurationType): Boolean { for (factory in type.configurationFactories) { if (factory.isApplicable(myProject)) { return true } } return false } } private inner class MyRemoveAction : AnAction(ExecutionBundle.message("remove.run.configuration.action.name"), ExecutionBundle.message("remove.run.configuration.action.name"), IconUtil.getRemoveIcon()), AnActionButtonRunnable, AnActionButtonUpdater { init { registerCustomShortcutSet(CommonShortcuts.getDelete(), tree) } override fun actionPerformed(e: AnActionEvent) { doRemove() } override fun run(button: AnActionButton) { doRemove() } private fun doRemove() { val selections = tree.selectionPaths tree.clearSelection() var nodeIndexToSelect = -1 var parentToSelect: DefaultMutableTreeNode? = null val changedParents = HashSet<DefaultMutableTreeNode>() var wasRootChanged = false for (each in selections!!) { val node = each.lastPathComponent as DefaultMutableTreeNode val parent = node.parent as DefaultMutableTreeNode val kind = getKind(node) if (!kind.isConfiguration && kind != FOLDER) continue if (node.userObject is SingleConfigurationConfigurable<*>) { (node.userObject as SingleConfigurationConfigurable<*>).disposeUIResources() } nodeIndexToSelect = parent.getIndex(node) parentToSelect = parent treeModel.removeNodeFromParent(node) changedParents.add(parent) if (kind == FOLDER) { val children = ArrayList<DefaultMutableTreeNode>() for (i in 0 until node.childCount) { val child = node.getChildAt(i) as DefaultMutableTreeNode val userObject = getSafeUserObject(child) if (userObject is SingleConfigurationConfigurable<*>) { userObject.folderName = null } children.add(0, child) } var confIndex = 0 for (i in 0 until parent.childCount) { if (getKind(parent.getChildAt(i) as DefaultMutableTreeNode).isConfiguration) { confIndex = i break } } for (child in children) { if (getKind(child) == CONFIGURATION) treeModel.insertNodeInto(child, parent, confIndex) } confIndex = parent.childCount for (i in 0 until parent.childCount) { if (getKind(parent.getChildAt(i) as DefaultMutableTreeNode) == TEMPORARY_CONFIGURATION) { confIndex = i break } } for (child in children) { if (getKind(child) == TEMPORARY_CONFIGURATION) { treeModel.insertNodeInto(child, parent, confIndex) } } } if (parent.childCount == 0 && parent.userObject is ConfigurationType) { changedParents.remove(parent) wasRootChanged = true nodeIndexToSelect = root.getIndex(parent) nodeIndexToSelect = Math.max(0, nodeIndexToSelect - 1) parentToSelect = root parent.removeFromParent() } } if (wasRootChanged) { (tree.model as DefaultTreeModel).reload() } else { for (each in changedParents) { treeModel.reload(each) tree.expandPath(TreePath(each)) } } selectedConfigurable = null if (root.childCount == 0) { drawPressAddButtonMessage(null) } else { if (parentToSelect!!.childCount > 0) { val nodeToSelect = if (nodeIndexToSelect < parentToSelect.childCount) { parentToSelect.getChildAt(nodeIndexToSelect) } else { parentToSelect.getChildAt(nodeIndexToSelect - 1) } TreeUtil.selectInTree(nodeToSelect as DefaultMutableTreeNode, true, tree) } } } override fun update(e: AnActionEvent) { e.presentation.isEnabled = isEnabled(e) } override fun isEnabled(e: AnActionEvent): Boolean { var enabled = false val selections = tree.selectionPaths if (selections != null) { for (each in selections) { val kind = getKind(each.lastPathComponent as DefaultMutableTreeNode) if (kind.isConfiguration || kind == FOLDER) { enabled = true break } } } return enabled } } private inner class MyCopyAction : AnAction(ExecutionBundle.message("copy.configuration.action.name"), ExecutionBundle.message("copy.configuration.action.name"), PlatformIcons.COPY_ICON) { init { val action = ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_DUPLICATE) registerCustomShortcutSet(action.shortcutSet, tree) } override fun actionPerformed(e: AnActionEvent) { val configuration = selectedConfiguration LOG.assertTrue(configuration != null) try { val typeNode = selectedConfigurationTypeNode!! val settings = configuration!!.snapshot val copyName = createUniqueName(typeNode, configuration.nameText, CONFIGURATION, TEMPORARY_CONFIGURATION) settings!!.name = copyName val factory = settings.factory @Suppress("UNCHECKED_CAST") (factory as? ConfigurationFactoryEx<RunConfiguration>)?.onConfigurationCopied(settings.configuration) val configurable = createNewConfiguration(settings, typeNode, selectedNode) IdeFocusManager.getInstance(myProject).requestFocus(configurable.nameTextField, true) configurable.nameTextField.selectionStart = 0 configurable.nameTextField.selectionEnd = copyName.length } catch (e1: ConfigurationException) { Messages.showErrorDialog(toolbarDecorator!!.actionsPanel, e1.message, e1.title) } } override fun update(e: AnActionEvent) { e.presentation.isEnabled = selectedConfiguration?.configuration !is UnknownRunConfiguration } } private inner class MySaveAction : AnAction(ExecutionBundle.message("action.name.save.configuration"), null, AllIcons.Actions.Menu_saveall) { override fun actionPerformed(e: AnActionEvent) { val configurationConfigurable = selectedConfiguration LOG.assertTrue(configurationConfigurable != null) val originalConfiguration = configurationConfigurable!!.settings if (originalConfiguration.isTemporary) { //todo Don't make 'stable' real configurations here but keep the set 'they want to be stable' until global 'Apply' action runManager.makeStable(originalConfiguration) adjustOrder() } tree.repaint() } override fun update(e: AnActionEvent) { val configuration = selectedConfiguration val presentation = e.presentation val enabled: Boolean if (configuration == null) { enabled = false } else { val settings = configuration.settings enabled = settings != null && settings.isTemporary } presentation.isEnabledAndVisible = enabled } } /** * Just saved as 'stable' configuration shouldn't stay between temporary ones (here we order nodes in JTree only) * @return shift (positive) for move configuration "up" to other stable configurations. Zero means "there is nothing to change" */ private fun adjustOrder(): Int { val selectionPath = tree.selectionPath ?: return 0 val treeNode = selectionPath.lastPathComponent as DefaultMutableTreeNode val selectedSettings = getSettings(treeNode) if (selectedSettings == null || selectedSettings.isTemporary) { return 0 } val parent = treeNode.parent as MutableTreeNode val initialPosition = parent.getIndex(treeNode) var position = initialPosition var node: DefaultMutableTreeNode? = treeNode.previousSibling while (node != null) { val settings = getSettings(node) if (settings != null && settings.isTemporary) { position-- } else { break } node = node.previousSibling } for (i in 0 until initialPosition - position) { TreeUtil.moveSelectedRow(tree, -1) } return initialPosition - position } private inner class MyMoveAction(text: String, description: String?, icon: Icon, private val myDirection: Int) : AnAction(text, description, icon), AnActionButtonRunnable, AnActionButtonUpdater { override fun actionPerformed(e: AnActionEvent) { doMove() } private fun doMove() { getAvailableDropPosition(myDirection)?.let { treeModel.drop(it.first, it.second, it.third) } } override fun run(button: AnActionButton) { doMove() } override fun update(e: AnActionEvent) { e.presentation.isEnabled = isEnabled(e) } override fun isEnabled(e: AnActionEvent) = getAvailableDropPosition(myDirection) != null } private inner class MyEditDefaultsAction : AnAction(ExecutionBundle.message("run.configuration.edit.default.configuration.settings.text"), ExecutionBundle.message( "run.configuration.edit.default.configuration.settings.description"), AllIcons.General.Settings) { override fun actionPerformed(e: AnActionEvent) { var defaults = TreeUtil.findNodeWithObject(DEFAULTS, tree.model, root) ?: return selectedConfigurationType?.let { defaults = TreeUtil.findNodeWithObject(it, tree.model, defaults) ?: return } val defaultsNode = defaults as DefaultMutableTreeNode? ?: return val path = TreeUtil.getPath(root, defaultsNode) tree.expandPath(path) TreeUtil.selectInTree(defaultsNode, true, tree) tree.scrollPathToVisible(path) } override fun update(e: AnActionEvent) { var isEnabled = TreeUtil.findNodeWithObject(DEFAULTS, tree.model, root) != null val path = tree.selectionPath if (path != null) { var o = path.lastPathComponent if (o is DefaultMutableTreeNode && o.userObject == DEFAULTS) { isEnabled = false } o = path.parentPath.lastPathComponent if (o is DefaultMutableTreeNode && o.userObject == DEFAULTS) { isEnabled = false } } e.presentation.isEnabled = isEnabled } } private inner class MyCreateFolderAction : AnAction(ExecutionBundle.message("run.configuration.create.folder.text"), ExecutionBundle.message("run.configuration.create.folder.description"), AllIcons.Nodes.Folder) { override fun actionPerformed(e: AnActionEvent) { val type = selectedConfigurationType ?: return val selectedNodes = selectedNodes val typeNode = getConfigurationTypeNode(type) ?: return val folderName = createUniqueName(typeNode, "New Folder", FOLDER) val folders = ArrayList<DefaultMutableTreeNode>() collectNodesRecursively(getConfigurationTypeNode(type)!!, folders, FOLDER) val folderNode = DefaultMutableTreeNode(folderName) treeModel.insertNodeInto(folderNode, typeNode, folders.size) isFolderCreating = true try { for (node in selectedNodes) { val folderRow = tree.getRowForPath(TreePath(folderNode.path)) val rowForPath = tree.getRowForPath(TreePath(node.path)) if (getKind(node).isConfiguration && treeModel.canDrop(rowForPath, folderRow, INTO)) { treeModel.drop(rowForPath, folderRow, INTO) } } tree.selectionPath = TreePath(folderNode.path) } finally { isFolderCreating = false } } override fun update(e: AnActionEvent) { var isEnabled = false var toMove = false val selectedNodes = selectedNodes var selectedType: ConfigurationType? = null for (node in selectedNodes) { val type = getType(node) if (selectedType == null) { selectedType = type } else { if (!Comparing.equal(type, selectedType)) { isEnabled = false break } } val kind = getKind(node) if (kind.isConfiguration || kind == CONFIGURATION_TYPE && node.parent === root || kind == FOLDER) { isEnabled = true } if (kind.isConfiguration) { toMove = true } } e.presentation.text = ExecutionBundle.message("run.configuration.create.folder.description${if (toMove) ".move" else ""}") e.presentation.isEnabled = isEnabled } } private inner class MySortFolderAction : AnAction(ExecutionBundle.message("run.configuration.sort.folder.text"), ExecutionBundle.message("run.configuration.sort.folder.description"), AllIcons.ObjectBrowser.Sorted), Comparator<DefaultMutableTreeNode> { override fun compare(node1: DefaultMutableTreeNode, node2: DefaultMutableTreeNode): Int { val kind1 = getKind(node1) val kind2 = getKind(node2) if (kind1 == FOLDER) { return if (kind2 == FOLDER) node1.parent.getIndex(node1) - node2.parent.getIndex(node2) else -1 } if (kind2 == FOLDER) { return 1 } val name1 = getName(node1.userObject) val name2 = getName(node2.userObject) return when (kind1) { TEMPORARY_CONFIGURATION -> if (kind2 == TEMPORARY_CONFIGURATION) name1.compareTo(name2) else 1 else -> if (kind2 == TEMPORARY_CONFIGURATION) -1 else name1.compareTo(name2) } } override fun actionPerformed(e: AnActionEvent) { val selectedNodes = selectedNodes val foldersToSort = ArrayList<DefaultMutableTreeNode>() for (node in selectedNodes) { val kind = getKind(node) if (kind == CONFIGURATION_TYPE || kind == FOLDER) { foldersToSort.add(node) } } for (folderNode in foldersToSort) { val children = ArrayList<DefaultMutableTreeNode>() for (i in 0 until folderNode.childCount) { val child = folderNode.getChildAt(i) as DefaultMutableTreeNode children.add(child) } children.sortWith(this) for (child in children) { folderNode.add(child) } treeModel.nodeStructureChanged(folderNode) } } override fun update(e: AnActionEvent) { val selectedNodes = selectedNodes for (node in selectedNodes) { val kind = getKind(node) if (kind == CONFIGURATION_TYPE || kind == FOLDER) { e.presentation.isEnabled = true return } } e.presentation.isEnabled = false } } private val selectedNodes: Array<DefaultMutableTreeNode> get() = tree.getSelectedNodes(DefaultMutableTreeNode::class.java, null) private val selectedNode: DefaultMutableTreeNode? get() = tree.getSelectedNodes(DefaultMutableTreeNode::class.java, null).firstOrNull() private val selectedSettings: RunnerAndConfigurationSettings? get() { val selectionPath = tree.selectionPath ?: return null return getSettings(selectionPath.lastPathComponent as DefaultMutableTreeNode) } inner class MyTreeModel(root: TreeNode) : DefaultTreeModel(root), EditableModel, RowsDnDSupport.RefinedDropSupport { override fun addRow() {} override fun removeRow(index: Int) {} override fun exchangeRows(oldIndex: Int, newIndex: Int) { //Do nothing, use drop() instead } //Legacy, use canDrop() instead override fun canExchangeRows(oldIndex: Int, newIndex: Int) = false override fun canDrop(oldIndex: Int, newIndex: Int, position: RowsDnDSupport.RefinedDropSupport.Position): Boolean { if (tree.rowCount <= oldIndex || tree.rowCount <= newIndex || oldIndex < 0 || newIndex < 0) { return false } val oldNode = tree.getPathForRow(oldIndex).lastPathComponent as DefaultMutableTreeNode val newNode = tree.getPathForRow(newIndex).lastPathComponent as DefaultMutableTreeNode val oldParent = oldNode.parent as DefaultMutableTreeNode val newParent = newNode.parent as DefaultMutableTreeNode val oldKind = getKind(oldNode) val newKind = getKind(newNode) val oldType = getType(oldNode) val newType = getType(newNode) if (oldParent === newParent) { if (oldNode.previousSibling === newNode && position == BELOW) { return false } if (oldNode.nextSibling === newNode && position == ABOVE) { return false } } when { oldType == null -> return false oldType !== newType -> { val typeNode = getConfigurationTypeNode(oldType) if (getKind(oldParent) == FOLDER && typeNode != null && typeNode.nextSibling === newNode && position == ABOVE) { return true } return getKind(oldParent) == CONFIGURATION_TYPE && oldKind == FOLDER && typeNode != null && typeNode.nextSibling === newNode && position == ABOVE && oldParent.lastChild !== oldNode && getKind(oldParent.lastChild as DefaultMutableTreeNode) == FOLDER } newParent === oldNode || oldParent === newNode -> return false oldKind == FOLDER && newKind != FOLDER -> return newKind.isConfiguration && position == ABOVE && getKind(newParent) == CONFIGURATION_TYPE && newIndex > 1 && getKind(tree.getPathForRow(newIndex - 1).parentPath.lastPathComponent as DefaultMutableTreeNode) == FOLDER !oldKind.supportsDnD() || !newKind.supportsDnD() -> return false oldKind.isConfiguration && newKind == FOLDER && position == ABOVE -> return false oldKind == TEMPORARY_CONFIGURATION && newKind == CONFIGURATION && position == ABOVE -> return false oldKind == CONFIGURATION && newKind == TEMPORARY_CONFIGURATION && position == BELOW -> return false oldKind == CONFIGURATION && newKind == TEMPORARY_CONFIGURATION && position == ABOVE -> return newNode.previousSibling == null || getKind(newNode.previousSibling) == CONFIGURATION || getKind(newNode.previousSibling) == FOLDER oldKind == TEMPORARY_CONFIGURATION && newKind == CONFIGURATION && position == BELOW -> return newNode.nextSibling == null || getKind(newNode.nextSibling) == TEMPORARY_CONFIGURATION oldParent === newParent -> //Same parent if (oldKind.isConfiguration && newKind.isConfiguration) { return oldKind == newKind//both are temporary or saved } else if (oldKind == FOLDER) { return !tree.isExpanded(newIndex) || position == ABOVE } } return true } override fun isDropInto(component: JComponent, oldIndex: Int, newIndex: Int): Boolean { val oldPath = tree.getPathForRow(oldIndex) val newPath = tree.getPathForRow(newIndex) if (oldPath == null || newPath == null) { return false } val oldNode = oldPath.lastPathComponent as DefaultMutableTreeNode val newNode = newPath.lastPathComponent as DefaultMutableTreeNode return getKind(oldNode).isConfiguration && getKind(newNode) == FOLDER } override fun drop(oldIndex: Int, newIndex: Int, position: RowsDnDSupport.RefinedDropSupport.Position) { val oldNode = tree.getPathForRow(oldIndex).lastPathComponent as DefaultMutableTreeNode val newNode = tree.getPathForRow(newIndex).lastPathComponent as DefaultMutableTreeNode var newParent = newNode.parent as DefaultMutableTreeNode val oldKind = getKind(oldNode) val wasExpanded = tree.isExpanded(TreePath(oldNode.path)) if (isDropInto(tree, oldIndex, newIndex)) { //Drop in folder removeNodeFromParent(oldNode) var index = newNode.childCount if (oldKind.isConfiguration) { var middleIndex = newNode.childCount for (i in 0 until newNode.childCount) { if (getKind(newNode.getChildAt(i) as DefaultMutableTreeNode) == TEMPORARY_CONFIGURATION) { middleIndex = i//index of first temporary configuration in target folder break } } if (position != INTO) { if (oldIndex < newIndex) { index = if (oldKind == CONFIGURATION) 0 else middleIndex } else { index = if (oldKind == CONFIGURATION) middleIndex else newNode.childCount } } else { index = if (oldKind == TEMPORARY_CONFIGURATION) newNode.childCount else middleIndex } } insertNodeInto(oldNode, newNode, index) tree.expandPath(TreePath(newNode.path)) } else { val type = getType(oldNode)!! removeNodeFromParent(oldNode) var index: Int if (type !== getType(newNode)) { val typeNode = getConfigurationTypeNode(type)!! newParent = typeNode index = newParent.childCount } else { index = newParent.getIndex(newNode) if (position == BELOW) { index++ } } insertNodeInto(oldNode, newParent, index) } val treePath = TreePath(oldNode.path) tree.selectionPath = treePath if (wasExpanded) { tree.expandPath(treePath) } } override fun insertNodeInto(newChild: MutableTreeNode, parent: MutableTreeNode, index: Int) { super.insertNodeInto(newChild, parent, index) if (!getKind(newChild as DefaultMutableTreeNode).isConfiguration) { return } val userObject = getSafeUserObject(newChild) val newFolderName = if (getKind(parent as DefaultMutableTreeNode) == FOLDER) parent.userObject as String else null if (userObject is SingleConfigurationConfigurable<*>) { userObject.folderName = newFolderName } } override fun reload(node: TreeNode?) { super.reload(node) val userObject = (node as DefaultMutableTreeNode).userObject if (userObject is String) { for (i in 0 until node.childCount) { val safeUserObject = getSafeUserObject(node.getChildAt(i) as DefaultMutableTreeNode) if (safeUserObject is SingleConfigurationConfigurable<*>) { safeUserObject.folderName = userObject } } } } private fun getType(treeNode: DefaultMutableTreeNode?): ConfigurationType? { val userObject = treeNode?.userObject ?: return null return when (userObject) { is SingleConfigurationConfigurable<*> -> userObject.configuration.type is RunnerAndConfigurationSettings -> userObject.type is ConfigurationType -> userObject else -> if (treeNode.parent is DefaultMutableTreeNode) getType(treeNode.parent as DefaultMutableTreeNode) else null } } } } private fun canRunConfiguration(configuration: SingleConfigurationConfigurable<RunConfiguration>?, executor: Executor): Boolean { return try { configuration != null && RunManagerImpl.canRunConfiguration(configuration.snapshot!!, executor) } catch (e: ConfigurationException) { false } } private fun createUniqueName(typeNode: DefaultMutableTreeNode, baseName: String?, vararg kinds: RunConfigurableNodeKind): String { val str = baseName ?: ExecutionBundle.message("run.configuration.unnamed.name.prefix") val configurationNodes = ArrayList<DefaultMutableTreeNode>() collectNodesRecursively(typeNode, configurationNodes, *kinds) val currentNames = ArrayList<String>() for (node in configurationNodes) { val userObject = node.userObject when (userObject) { is SingleConfigurationConfigurable<*> -> currentNames.add(userObject.nameText) is RunnerAndConfigurationSettingsImpl -> currentNames.add((userObject as RunnerAndConfigurationSettings).name) is String -> currentNames.add(userObject) } } return RunManager.suggestUniqueName(str, currentNames) } private fun getType(_node: DefaultMutableTreeNode?): ConfigurationType? { var node = _node while (node != null) { (node.userObject as? ConfigurationType)?.let { return it } node = node.parent as? DefaultMutableTreeNode } return null } private fun getSettings(treeNode: DefaultMutableTreeNode?): RunnerAndConfigurationSettings? { if (treeNode == null) { return null } val settings: RunnerAndConfigurationSettings? = null if (treeNode.userObject is SingleConfigurationConfigurable<*>) { return (treeNode.userObject as SingleConfigurationConfigurable<*>).settings as RunnerAndConfigurationSettings } if (treeNode.userObject is RunnerAndConfigurationSettings) { return treeNode.userObject as RunnerAndConfigurationSettings } return settings }
platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.kt
2668063045
package com.aemtools.reference.htl.reference import com.aemtools.reference.htl.HtlListHelperDeclarationIdentifier import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiReferenceBase import com.intellij.psi.xml.XmlAttribute /** * @author Dmytro Troynikov */ class HtlListHelperReference(val xmlAttribute: XmlAttribute, holder: PsiElement, range: TextRange) : PsiReferenceBase<PsiElement>(holder, range, true) { override fun resolve(): PsiElement? = HtlListHelperDeclarationIdentifier(xmlAttribute) override fun getVariants(): Array<Any> { return arrayOf() } }
aem-intellij-core/src/main/kotlin/com/aemtools/reference/htl/reference/HtlListHelperReference.kt
535991948
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.inspections.missingApi.resolve import com.intellij.jarRepository.JarRepositoryManager import com.intellij.jarRepository.RemoteRepositoryDescription import com.intellij.openapi.project.Project import com.intellij.openapi.util.BuildNumber import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.annotations.NonNls import org.jetbrains.idea.maven.aether.ArtifactKind import org.jetbrains.jps.model.library.JpsMavenRepositoryLibraryDescriptor /** * Default implementation of [IntelliJSdkExternalAnnotationsRepository] that delegates to [JarRepositoryManager] * for searching and downloading artifacts from the IntelliJ Artifacts Repositories. */ class PublicIntelliJSdkExternalAnnotationsRepository(private val project: Project) : IntelliJSdkExternalAnnotationsRepository { @Suppress("HardCodedStringLiteral") companion object { const val RELEASES_REPO_URL = "https://www.jetbrains.com/intellij-repository/releases/" const val SNAPSHOTS_REPO_URL = "https://www.jetbrains.com/intellij-repository/snapshots/" val RELEASES_REPO_DESCRIPTION = RemoteRepositoryDescription( "IntelliJ Artifacts Repository (Releases)", "IntelliJ Artifacts Repository (Releases)", RELEASES_REPO_URL ) val SNAPSHOTS_REPO_DESCRIPTION = RemoteRepositoryDescription( "IntelliJ Artifacts Repository (Snapshots)", "IntelliJ Artifacts Repository (Snapshots)", SNAPSHOTS_REPO_URL ) } private fun getAnnotationsCoordinates(): Pair<String, String>? { //Currently, for any IDE download ideaIU's annotations. return "com.jetbrains.intellij.idea" to "ideaIU" } override fun downloadExternalAnnotations(ideBuildNumber: BuildNumber): IntelliJSdkExternalAnnotations? { val (groupId, artifactId) = getAnnotationsCoordinates() ?: return null val lastReleaseVersion = "${ideBuildNumber.baselineVersion}.999999" val lastReleaseAnnotations = tryDownload(groupId, artifactId, lastReleaseVersion, listOf(RELEASES_REPO_DESCRIPTION)) if (lastReleaseAnnotations != null && lastReleaseAnnotations.annotationsBuild >= ideBuildNumber) { return lastReleaseAnnotations } @NonNls val snapshotVersion = "${ideBuildNumber.baselineVersion}-SNAPSHOT" val snapshotAnnotations = tryDownload(groupId, artifactId, snapshotVersion, listOf(SNAPSHOTS_REPO_DESCRIPTION)) if (snapshotAnnotations != null && snapshotAnnotations.annotationsBuild >= ideBuildNumber) { return snapshotAnnotations } @NonNls val latestTrunkSnapshot = "LATEST-TRUNK-SNAPSHOT" val latestTrunkSnapshotAnnotations = tryDownload(groupId, artifactId, latestTrunkSnapshot, listOf(SNAPSHOTS_REPO_DESCRIPTION)) if (latestTrunkSnapshotAnnotations != null && latestTrunkSnapshotAnnotations.annotationsBuild >= ideBuildNumber) { return latestTrunkSnapshotAnnotations } return sequenceOf(lastReleaseAnnotations, snapshotAnnotations, latestTrunkSnapshotAnnotations).filterNotNull().maxBy { it.annotationsBuild } } private fun tryDownload( groupId: String, artifactId: String, version: String, repos: List<RemoteRepositoryDescription> ): IntelliJSdkExternalAnnotations? { val annotations = tryDownloadAnnotationsArtifact(groupId, artifactId, version, repos) if (annotations != null) { val buildNumber = getAnnotationsBuildNumber(annotations) if (buildNumber != null) { return IntelliJSdkExternalAnnotations(buildNumber, annotations) } } return null } private fun tryDownloadAnnotationsArtifact( groupId: String, artifactId: String, version: String, repos: List<RemoteRepositoryDescription> ): VirtualFile? { return JarRepositoryManager.loadDependenciesSync( project, JpsMavenRepositoryLibraryDescriptor(groupId, artifactId, version), setOf(ArtifactKind.ANNOTATIONS), repos, null )?.firstOrNull()?.file } }
plugins/devkit/devkit-core/src/inspections/missingApi/resolve/PublicIntelliJSdkExternalAnnotationsRepository.kt
1471612570
package com.aemtools.analysis.htl.callchain.typedescriptor.properties import com.aemtools.analysis.htl.callchain.typedescriptor.base.BaseTypeDescriptor import com.aemtools.analysis.htl.callchain.typedescriptor.base.TypeDescriptor import com.aemtools.common.util.resourceType import com.aemtools.common.util.withPriority import com.aemtools.completion.htl.CompletionPriority.DIALOG_PROPERTY import com.aemtools.index.model.dialog.AemComponentClassicDialogDefinition import com.aemtools.index.model.dialog.AemComponentTouchUIDialogDefinition import com.aemtools.index.search.AemComponentSearch import com.intellij.codeInsight.lookup.LookupElement import com.intellij.psi.PsiElement /** * Type descriptor for `properties` context object. * * @author Dmytro Troynikov */ class PropertiesTypeDescriptor(val element: PsiElement) : BaseTypeDescriptor() { private val myResourceType: String? by lazy { element.containingFile.originalFile.virtualFile.resourceType() } private val touchUIDialog: AemComponentTouchUIDialogDefinition? by lazy { myResourceType?.let { AemComponentSearch.findTouchUIDialogByResourceType(it, element.project) } } private val classicDialog: AemComponentClassicDialogDefinition? by lazy { myResourceType?.let { AemComponentSearch.findClassicDialogByResourceType(it, element.project) } } override fun myVariants(): List<LookupElement> { touchUIDialog?.let { return it.myParameters.map { it.toLookupElement() .withPriority(DIALOG_PROPERTY) } } classicDialog?.let { return it.myParameters.map { it.toLookupElement() .withPriority(DIALOG_PROPERTY) } } return emptyList() } override fun subtype(identifier: String): TypeDescriptor { touchUIDialog?.let { return TouchDialogPropertyTypeDescriptor( identifier, element, it) } classicDialog?.let { return ClassicDialogPropertyTypeDescriptor( identifier, element, it ) } return TypeDescriptor.empty() } }
aem-intellij-core/src/main/kotlin/com/aemtools/analysis/htl/callchain/typedescriptor/properties/PropertiesTypeDescriptor.kt
338884640
// 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.util.indexing.diagnostic class TimeStats { private var _count: Long? = null private var _minTime: TimeNano? = null private var _maxTime: TimeNano? = null private var _sum: TimeNano? = null @Synchronized fun addTime(time: TimeNano) { if (_maxTime == null || _maxTime!! < time) _maxTime = time if (_minTime == null || _minTime!! > time) _minTime = time _sum = (_sum ?: 0) + time _count = (_count ?: 0) + 1 } private fun failEmpty(): Nothing = throw IllegalStateException("No times have been added yet") val isEmpty: Boolean @Synchronized get() = _sum == null val sumTime: TimeNano @Synchronized get() = _sum ?: failEmpty() val minTime: TimeNano @Synchronized get() = _minTime ?: failEmpty() val maxTime: TimeNano @Synchronized get() = _maxTime ?: failEmpty() val meanTime: Double @Synchronized get() = (_sum ?: failEmpty()).toDouble() / (_count ?: failEmpty()) }
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/TimeStats.kt
1274043273
// 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.authentication.util import com.intellij.openapi.progress.ProgressIndicator import org.jetbrains.plugins.github.api.* import org.jetbrains.plugins.github.api.data.GithubAuthenticatedUser object GHSecurityUtil { private const val REPO_SCOPE = "repo" private const val GIST_SCOPE = "gist" private const val READ_ORG_SCOPE = "read:org" val MASTER_SCOPES = listOf(REPO_SCOPE, GIST_SCOPE, READ_ORG_SCOPE) const val DEFAULT_CLIENT_NAME = "Github Integration Plugin" @JvmStatic internal fun loadCurrentUserWithScopes(executor: GithubApiRequestExecutor, progressIndicator: ProgressIndicator, server: GithubServerPath): Pair<GithubAuthenticatedUser, String?> { var scopes: String? = null val details = executor.execute(progressIndicator, object : GithubApiRequest.Get.Json<GithubAuthenticatedUser>( GithubApiRequests.getUrl(server, GithubApiRequests.CurrentUser.urlSuffix), GithubAuthenticatedUser::class.java) { override fun extractResult(response: GithubApiResponse): GithubAuthenticatedUser { scopes = response.findHeader("X-OAuth-Scopes") return super.extractResult(response) } }.withOperationName("get profile information")) return details to scopes } @JvmStatic internal fun isEnoughScopes(grantedScopes: String): Boolean { val scopesArray = grantedScopes.split(", ") if (scopesArray.isEmpty()) return false if (!scopesArray.contains(REPO_SCOPE)) return false if (!scopesArray.contains(GIST_SCOPE)) return false if (scopesArray.none { it.endsWith(":org") }) return false return true } }
plugins/github/src/org/jetbrains/plugins/github/authentication/util/GHSecurityUtil.kt
3656863317
package info.vividcode.oauth import java.time.Instant object OAuthProtocolParameters { sealed class Options { data class PlaintextSigning(val nonce: String?, val timestamp: Instant?) : Options() data class HmcSha1Signing(val nonce: String, val timestamp: Instant) : Options() } fun createProtocolParametersExcludingSignature( clientIdentifier: String, temporaryOrTokenIdentifier: String?, options: Options, additionalProtocolParameters: List<ProtocolParameter<*>>? ) = ProtocolParameterSet.Builder().apply { add(ProtocolParameter.ConsumerKey(clientIdentifier)) when (options) { is Options.PlaintextSigning -> { add(ProtocolParameter.SignatureMethod.Plaintext) options.nonce?.let { add(ProtocolParameter.Nonce(it)) } options.timestamp?.let { add(ProtocolParameter.Timestamp(it)) } } is Options.HmcSha1Signing -> { add(ProtocolParameter.SignatureMethod.HmacSha1) add(ProtocolParameter.Nonce(options.nonce)) add(ProtocolParameter.Timestamp(options.timestamp)) } } temporaryOrTokenIdentifier?.let { add(ProtocolParameter.Token(it)) } additionalProtocolParameters?.let { add(it) } }.build() fun createProtocolParametersExcludingSignatureForTemporaryCredentialRequest( clientCredentials: OAuthCredentials, options: Options, callbackUrl: String? = null, additionalProtocolParameters: List<ProtocolParameter<*>>? = null ): ProtocolParameterSet = createProtocolParametersExcludingSignature( clientCredentials.identifier, null, options, mutableListOf<ProtocolParameter<*>>().apply { additionalProtocolParameters?.let { addAll(it) } callbackUrl?.let { add(ProtocolParameter.Callback(it)) } } ) fun createProtocolParametersForTokenCredentialRequest( clientCredentials: OAuthCredentials, temporaryCredentials: OAuthCredentials, options: Options, verifier: String, additionalProtocolParameters: List<ProtocolParameter<*>>? = null ): ProtocolParameterSet = createProtocolParametersExcludingSignature( clientCredentials.identifier, temporaryCredentials.identifier, options, mutableListOf<ProtocolParameter<*>>().apply { additionalProtocolParameters?.let { addAll(it) } add(ProtocolParameter.Verifier(verifier)) } ) }
core/src/main/kotlin/info/vividcode/oauth/OAuthProtocolParameters.kt
2385445604
package com.ruuvi.station.settings.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.ruuvi.station.app.preferences.Preferences import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch class AppSettingsGraphViewModel(private val preferences: Preferences) : ViewModel() { private val pointInterval = Channel<Int>(1) private val viewPeriod = Channel<Int>(1) private val showAllPoints = MutableStateFlow<Boolean>(preferences.graphShowAllPoint) val showAllPointsFlow: StateFlow<Boolean> = showAllPoints init { viewModelScope.launch { pointInterval.send(preferences.graphPointInterval) viewPeriod.send(preferences.graphViewPeriod) } } fun observePointInterval(): Flow<Int> = pointInterval.receiveAsFlow() fun observeViewPeriod(): Flow<Int> = viewPeriod.receiveAsFlow() fun setPointInterval(newInterval: Int) { preferences.graphPointInterval = newInterval } fun setViewPeriod(newPeriod: Int) { preferences.graphViewPeriod = newPeriod } fun setShowAllPoints(checked: Boolean) { preferences.graphShowAllPoint = checked showAllPoints.value = checked } }
app/src/main/java/com/ruuvi/station/settings/ui/AppSettingsGraphViewModel.kt
4143925354
// 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 git4idea.ignore import com.intellij.dvcs.ignore.VcsIgnoredFilesHolderBase import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.ChangesViewRefresher import com.intellij.openapi.vcs.changes.VcsIgnoredFilesHolder import git4idea.GitVcs import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager class GitIgnoredFilesHolder(val project: Project, val manager: GitRepositoryManager) : VcsIgnoredFilesHolderBase<GitRepository>(manager) { override fun getHolder(repository: GitRepository) = repository.ignoredFilesHolder override fun copy() = GitIgnoredFilesHolder(project, manager) class Provider(val project: Project) : VcsIgnoredFilesHolder.Provider, ChangesViewRefresher { private val gitVcs = GitVcs.getInstance(project) private val manager = GitRepositoryManager.getInstance(project) override fun getVcs() = gitVcs override fun createHolder() = GitIgnoredFilesHolder(project, manager) override fun refresh(project: Project) { manager.repositories.forEach { r -> r.ignoredFilesHolder.startRescan() } } } }
plugins/git4idea/src/git4idea/ignore/GitIgnoredFilesHolder.kt
1284043065
package slatekit.server.ktor import io.ktor.application.ApplicationCall import io.ktor.request.uri import slatekit.requests.Request object KtorRequests { /** * Gets all the parts of the uri path * @sample "/api/account/signup" * @return ["api", "account", "signup"] */ fun getPathParts(req: Request): List<String> { val kreq = req as KtorRequest? return kreq?.call?.let { getPathParts(it) } ?: listOf() } /** * Gets all the parts of the uri path * @sample "/api/account/signup" * @return ["api", "account", "signup"] */ fun getPathParts(call: ApplicationCall): List<String> { val rawUri = call.request.uri // E.g. app/users/recent?count=20 // Only get up until "?" val uri = if (rawUri.contains("?")) { rawUri.substring(0, rawUri.indexOf("?")) } else { rawUri } val parts = uri.split('/') return parts } }
src/lib/kotlin/slatekit-server/src/main/kotlin/slatekit/server/ktor/KtorRequests.kt
230460525
package org.purescript.psi.typeconstructor import com.intellij.testFramework.fixtures.BasePlatformTestCase import org.purescript.* class TypeConstructorReferenceTest : BasePlatformTestCase() { fun `test resolves local data declarations`() { myFixture.configureByText( "Foo.purs", """ module Foo where data Bar q :: Bar """.trimIndent() ).run { assertEquals(getDataDeclaration(), getTypeConstructor().reference.resolve()) } } fun `test resolves imported data declarations`() { val dataDeclaration = myFixture.configureByText( "Bar.purs", """ module Bar where data Qux """.trimIndent() ).getDataDeclaration() val typeConstructor = myFixture.configureByText( "Foo.purs", """ module Foo where import Bar a :: Qux """.trimIndent() ).getTypeConstructor() assertEquals(dataDeclaration, typeConstructor.reference.resolve()) } fun `test completes data declarations`() { myFixture.configureByText( "Bar.purs", """ module Bar where data Qux """.trimIndent() ) myFixture.configureByText( "Foo.purs", """ module Foo where import Bar data Bum a :: <caret> """.trimIndent() ) myFixture.testCompletionVariants("Foo.purs", "Qux", "Bum") } fun `test finds usages from local data declarations`() { myFixture.configureByText( "Main.purs", """ module Data where data B = B data <caret>A = A func :: A -> A func a = a """.trimIndent() ) val usageInfo = myFixture.testFindUsages("Main.purs") assertEquals(2, usageInfo.size) } fun `test finds usages from imported data declarations`() { val dataDeclaration = myFixture.configureByText( "Bar.purs", """ module Bar where data Qux """.trimIndent() ).getDataDeclaration() val typeConstructor = myFixture.configureByText( "Foo.purs", """ module Foo where import Bar a :: Qux """.trimIndent() ).getTypeConstructor() val usageInfo = myFixture.findUsages(dataDeclaration).single() assertEquals(typeConstructor, usageInfo.element) } fun `test resolves local newtype declarations`() { myFixture.configureByText( "Foo.purs", """ module Foo where newtype Bar = Bar a q :: Bar """.trimIndent() ).run { assertEquals(getNewTypeDeclaration(), getTypeConstructor().reference.resolve()) } } fun `test resolves imported newtype declarations`() { val newtypeDeclaration = myFixture.configureByText( "Bar.purs", """ module Bar where newtype Qux = Qux a """.trimIndent() ).getNewTypeDeclaration() val typeConstructor = myFixture.configureByText( "Foo.purs", """ module Foo where import Bar a :: Qux """.trimIndent() ).getTypeConstructor() assertEquals(newtypeDeclaration, typeConstructor.reference.resolve()) } fun `test completes newtype declarations`() { myFixture.configureByText( "Bar.purs", """ module Bar where newtype Qux = Qux a """.trimIndent() ) myFixture.configureByText( "Foo.purs", """ module Foo where import Bar newtype Bum = Bum a a :: <caret> """.trimIndent() ) myFixture.testCompletionVariants("Foo.purs", "Qux", "Bum") } fun `test finds usages from local newtype declarations`() { myFixture.configureByText( "Main.purs", """ module Data where newtype B = B a newtype <caret>A = A a func :: A -> A func a = a """.trimIndent() ) val usageInfo = myFixture.testFindUsages("Main.purs") assertEquals(2, usageInfo.size) } fun `test finds usages from imported newtype declarations`() { val newtypeDeclaration = myFixture.configureByText( "Bar.purs", """ module Bar where newtype Qux = Qux a """.trimIndent() ).getNewTypeDeclaration() val typeConstructor = myFixture.configureByText( "Foo.purs", """ module Foo where import Bar a :: Qux """.trimIndent() ).getTypeConstructor() val usageInfo = myFixture.findUsages(newtypeDeclaration).single() assertEquals(typeConstructor, usageInfo.element) } fun `test resolves local type synonym declarations`() { myFixture.configureByText( "Foo.purs", """ module Foo where type Bar a = a q :: Bar """.trimIndent() ).run { assertEquals(getTypeSynonymDeclaration(), getTypeConstructor().reference.resolve()) } } fun `test resolves imported type synonym declarations`() { val typeSynonymDeclaration = myFixture.configureByText( "Bar.purs", """ module Bar where type Qux = Int """.trimIndent() ).getTypeSynonymDeclaration() val typeConstructor = myFixture.configureByText( "Foo.purs", """ module Foo where import Bar a :: Qux """.trimIndent() ).getTypeConstructor() assertEquals(typeSynonymDeclaration, typeConstructor.reference.resolve()) } fun `test resolves alias imported type synonym declarations`() { val typeSynonymDeclaration = myFixture.configureByText( "Bar.purs", """ module Bar where type Qux = Int """.trimIndent() ).getTypeSynonymDeclaration() val typeConstructor = myFixture.configureByText( "Foo.purs", """ module Foo where import Bar as Bar a :: Bar.Qux """.trimIndent() ).getTypeConstructor() assertEquals(typeSynonymDeclaration, typeConstructor.reference.resolve()) } fun `test resolves alias imported type synonym declarations with same name`() { val typeSynonymDeclaration = myFixture.configureByText( "Bar.purs", """ module Bar where type Qux = Int """.trimIndent() ).getTypeSynonymDeclaration() val typeConstructor = myFixture.configureByText( "Foo.purs", """ module Foo where import Bar as Bar type Qux = Bar.Qux """.trimIndent() ).getTypeConstructor() assertEquals(typeSynonymDeclaration, typeConstructor.reference.resolve()) } fun `test completes type synonym declarations`() { myFixture.configureByText( "Bar.purs", """ module Bar where type Qux = Int """.trimIndent() ) myFixture.configureByText( "Foo.purs", """ module Foo where import Bar type Bum = Int a :: <caret> """.trimIndent() ) myFixture.testCompletionVariants("Foo.purs", "Qux", "Bum") } fun `test finds usages from local type synonym declarations`() { myFixture.configureByText( "Main.purs", """ module Data where type B = Int type <caret>A = Int func :: A -> A func a = a """.trimIndent() ) val usageInfo = myFixture.testFindUsages("Main.purs") assertEquals(2, usageInfo.size) } fun `test finds usages from imported type synonym declarations`() { val typeSynonymDeclaration = myFixture.configureByText( "Bar.purs", """ module Bar where type Qux = Int """.trimIndent() ).getTypeSynonymDeclaration() val typeConstructor = myFixture.configureByText( "Foo.purs", """ module Foo where import Bar a :: Qux """.trimIndent() ).getTypeConstructor() val usageInfo = myFixture.findUsages(typeSynonymDeclaration).single() assertEquals(typeConstructor, usageInfo.element) } fun `test resolves local foreign data declarations`() { val file = myFixture.configureByText( "Foo.purs", """ module Foo where foreign import data Bar :: Type q :: Bar """.trimIndent() ) val foreignDataDeclaration = file.getForeignDataDeclaration() val typeConstructor = file.getTypeConstructors()[1] assertEquals("Bar", typeConstructor.name) assertEquals(foreignDataDeclaration, typeConstructor.reference.resolve()) } fun `test resolves imported foreign data declarations`() { val foreignDataDeclaration = myFixture.configureByText( "Bar.purs", """ module Bar where foreign import data Qux :: Type """.trimIndent() ).getForeignDataDeclaration() val typeConstructor = myFixture.configureByText( "Foo.purs", """ module Foo where import Bar a :: Qux """.trimIndent() ).getTypeConstructor() assertEquals(foreignDataDeclaration, typeConstructor.reference.resolve()) } fun `test completes foreign data declarations`() { myFixture.configureByText( "Bar.purs", """ module Bar where foreign import data Qux :: Type """.trimIndent() ) myFixture.configureByText( "Foo.purs", """ module Foo where import Bar foreign import data Bum :: Type a :: <caret> """.trimIndent() ) myFixture.testCompletionVariants("Foo.purs", "Qux", "Bum") } fun `test finds usages from local foreign data declarations`() { myFixture.configureByText( "Main.purs", """ module Data where foreign import data B :: Type foreign import data <caret>A :: Type func :: A -> A func a = a """.trimIndent() ) val usageInfo = myFixture.testFindUsages("Main.purs") assertEquals(2, usageInfo.size) } fun `test finds usages from imported foreign data declarations`() { val foreignDataDeclaration = myFixture.configureByText( "Bar.purs", """ module Bar where foreign import data Qux :: Type """.trimIndent() ).getForeignDataDeclaration() val typeConstructor = myFixture.configureByText( "Foo.purs", """ module Foo where import Bar a :: Qux """.trimIndent() ).getTypeConstructor() val usageInfo = myFixture.findUsages(foreignDataDeclaration).single() assertEquals(typeConstructor, usageInfo.element) } }
src/test/kotlin/org/purescript/psi/typeconstructor/TypeConstructorReferenceTest.kt
3185631930
package org.http4k.server import com.sun.net.httpserver.HttpExchange import com.sun.net.httpserver.HttpServer import org.http4k.core.Body import org.http4k.core.HttpHandler import org.http4k.core.Method import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Uri import java.net.InetSocketAddress import java.nio.ByteBuffer import java.nio.channels.Channels data class SunHttp(val port: Int = 8000) : ServerConfig { override fun toServer(handler: HttpHandler): Http4kServer { return object : Http4kServer { private val server = HttpServer.create(InetSocketAddress(port), 0) override fun start(): Http4kServer { server.createContext("/") { try { it.populate(handler(it.toRequest())) } catch (e: Exception) { it.sendResponseHeaders(500, 0) } it.close() } server.start() return this } override fun stop() = server.stop(0) } } } private fun HttpExchange.populate(httpResponse: Response) { httpResponse.headers.forEach { (key, value) -> responseHeaders.add(key, value) } sendResponseHeaders(httpResponse.status.code, 0) Channels.newChannel(responseBody).write(httpResponse.body.payload) } private fun HttpExchange.toRequest(): Request { val uri = requestURI.rawQuery?.let { Uri.of(requestURI.rawPath).query(requestURI.rawQuery) } ?: Uri.of(requestURI.rawPath) Request(Method.valueOf(requestMethod), uri) .body(Body(ByteBuffer.wrap(requestBody.readBytes()))).let { return requestHeaders.toList().fold(it) { memo, (name, values) -> values.fold(memo) { memo2, value -> memo2.header(name, value) } } } }
http4k-core/src/main/kotlin/org/http4k/server/SunHttp.kt
1745640613
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME // FILE: B.java public class B<E> extends A<E> { @Override public <T> T[] toArray(T[] a) { return a; } } // FILE: main.kt open class A<T> : Collection<T> { override val size: Int get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. override fun contains(element: T): Boolean { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun containsAll(elements: Collection<T>): Boolean { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun isEmpty(): Boolean { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun iterator(): Iterator<T> { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } } fun box() = B<String>().toArray(arrayOf("OK"))[0]
backend.native/tests/external/codegen/box/collections/toArrayInJavaClass.kt
968536564
/* * Copyright 2010-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. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotlin.text.regex /** * A node representing a '^' sign. * Note: In Kotlin we use only the "anchoring bounds" mode when "^" matches beginning of a match region. * See: http://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#useAnchoringBounds-boolean- */ internal class SOLSet(val lt: AbstractLineTerminator, val multiline: Boolean = false) : SimpleSet() { override fun matches(startIndex: Int, testString: CharSequence, matchResult: MatchResultImpl): Int { if (!multiline) { if (startIndex == 0) { return next.matches(startIndex, testString, matchResult) } } else { if (startIndex != testString.length && (startIndex == 0 || lt.isAfterLineTerminator(testString[startIndex - 1], testString[startIndex]))) { return next.matches(startIndex, testString, matchResult) } } return -1 } override fun hasConsumed(matchResult: MatchResultImpl): Boolean = false override val name: String get() = "^" }
runtime/src/main/kotlin/kotlin/text/regex/sets/SOLSet.kt
1660711982
// TARGET_BACKEND: JVM // FULL_JDK import java.net.* fun String.decodeURI(encoding : String) : String? = try { URLDecoder.decode(this, encoding) } catch (e : Throwable) { null } fun box() : String { return if("hhh".decodeURI("") == null) "OK" else "fail" }
backend.native/tests/external/codegen/box/fullJdk/kt434.kt
2221364567
package foo import bar.<caret>barbar fun foofoo(): Int { return barbar() }
plugins/kotlin/idea/tests/testData/fir/lazyResolve/import/foo/main.kt
1166800250
package dependency1 fun Any.xxx(): Int = 1
plugins/kotlin/completion/tests/testData/basic/multifile/PreferMoreSpecificExtension3/PreferMoreSpecificExtension3.dependency1.kt
2863479063
@Suppress("INTERFACE_WITH_SUPERCLASS") interface T : A object O1 : A() {} object O2 : T {}
plugins/kotlin/idea/tests/testData/findUsages/java/findJavaClassUsages/JKClassDerivedObjects.1.kt
3269083984
/* * 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 /** * Uast operator base interface. * * @see [UastPrefixOperator], [UastPostfixOperator], [UastBinaryOperator] */ interface UastOperator { /** * Returns the operator text to render in [UElement.asRenderString]. */ val text: String }
uast/uast-common/src/org/jetbrains/uast/kinds/UastOperator.kt
1741561470
// 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.search.refIndex import com.intellij.compiler.server.BuildManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.SmartList import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.containers.MultiMap import com.intellij.util.indexing.UnindexedFilesUpdater import com.intellij.util.io.CorruptedException import com.intellij.util.io.EnumeratorStringDescriptor import com.intellij.util.io.PersistentHashMap import org.jetbrains.annotations.TestOnly import org.jetbrains.jps.builders.impl.BuildDataPathsImpl import org.jetbrains.jps.builders.java.JavaModuleBuildTargetType import org.jetbrains.jps.builders.storage.BuildDataPaths import org.jetbrains.kotlin.config.SettingConstants import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.incremental.KOTLIN_CACHE_DIRECTORY_NAME import org.jetbrains.kotlin.incremental.storage.BasicMapsOwner import org.jetbrains.kotlin.incremental.storage.CollectionExternalizer import org.jetbrains.kotlin.name.FqName import java.nio.file.Path import java.util.concurrent.Future import kotlin.io.path.* import kotlin.system.measureTimeMillis class KotlinCompilerReferenceIndexStorage private constructor( kotlinDataContainerPath: Path, private val lookupStorageReader: LookupStorageReader, ) { companion object { /** * [org.jetbrains.kotlin.incremental.AbstractIncrementalCache.Companion.SUBTYPES] */ private val SUBTYPES_STORAGE_NAME = "subtypes.${BasicMapsOwner.CACHE_EXTENSION}" private val STORAGE_INDEXING_EXECUTOR = AppExecutorUtil.createBoundedApplicationPoolExecutor( "Kotlin compiler references indexing", UnindexedFilesUpdater.getMaxNumberOfIndexingThreads() ) private val LOG = logger<KotlinCompilerReferenceIndexStorage>() fun open(project: Project): KotlinCompilerReferenceIndexStorage? { val projectPath = runReadAction { project.takeUnless(Project::isDisposed)?.basePath } ?: return null val buildDataPaths = project.buildDataPaths val kotlinDataContainerPath = buildDataPaths?.kotlinDataContainer ?: kotlin.run { LOG.warn("${SettingConstants.KOTLIN_DATA_CONTAINER_ID} is not found") return null } val lookupStorageReader = LookupStorageReader.create(kotlinDataContainerPath, projectPath) ?: kotlin.run { LOG.warn("LookupStorage not found or corrupted") return null } val storage = KotlinCompilerReferenceIndexStorage(kotlinDataContainerPath, lookupStorageReader) if (!storage.initialize(buildDataPaths)) return null return storage } fun close(storage: KotlinCompilerReferenceIndexStorage?) { storage?.close().let { LOG.info("KCRI storage is closed" + if (it == null) " (didn't exist)" else "") } } fun hasIndex(project: Project): Boolean = LookupStorageReader.hasStorage(project) @TestOnly fun initializeForTests( buildDataPaths: BuildDataPaths, destination: ClassOneToManyStorage, ) = initializeSubtypeStorage(buildDataPaths, destination) internal val Project.buildDataPaths: BuildDataPaths? get() = BuildManager.getInstance().getProjectSystemDirectory(this)?.let(::BuildDataPathsImpl) internal val BuildDataPaths.kotlinDataContainer: Path? get() = targetsDataRoot?.toPath() ?.resolve(SettingConstants.KOTLIN_DATA_CONTAINER_ID) ?.takeIf { it.exists() && it.isDirectory() } ?.listDirectoryEntries("${SettingConstants.KOTLIN_DATA_CONTAINER_ID}*") ?.firstOrNull() private fun initializeSubtypeStorage(buildDataPaths: BuildDataPaths, destination: ClassOneToManyStorage): Boolean { var wasCorrupted = false val destinationMap = MultiMap.createConcurrentSet<String, String>() val futures = mutableListOf<Future<*>>() val timeOfFilling = measureTimeMillis { visitSubtypeStorages(buildDataPaths) { storagePath -> futures += STORAGE_INDEXING_EXECUTOR.submit { try { initializeStorage(destinationMap, storagePath) } catch (e: CorruptedException) { wasCorrupted = true LOG.warn("KCRI storage was corrupted", e) } } } try { for (future in futures) { future.get() } } catch (e: InterruptedException) { LOG.warn("KCRI initialization was interrupted") throw e } } if (wasCorrupted) return false val timeOfFlush = measureTimeMillis { for ((key, values) in destinationMap.entrySet()) { destination.put(key, values) } } LOG.info("KCRI storage is opened: took ${timeOfFilling + timeOfFlush} ms for ${futures.size} storages (filling map: $timeOfFilling ms, flush to storage: $timeOfFlush ms)") return true } private fun visitSubtypeStorages(buildDataPaths: BuildDataPaths, processor: (Path) -> Unit) { for (buildTargetType in JavaModuleBuildTargetType.ALL_TYPES) { val buildTargetPath = buildDataPaths.getTargetTypeDataRoot(buildTargetType).toPath() if (buildTargetPath.notExists() || !buildTargetPath.isDirectory()) continue buildTargetPath.forEachDirectoryEntry { targetDataRoot -> val workingPath = targetDataRoot.takeIf { it.isDirectory() } ?.resolve(KOTLIN_CACHE_DIRECTORY_NAME) ?.resolve(SUBTYPES_STORAGE_NAME) ?.takeUnless { it.notExists() } ?: return@forEachDirectoryEntry processor(workingPath) } } } } private val subtypesStorage = ClassOneToManyStorage(kotlinDataContainerPath.resolve(SUBTYPES_STORAGE_NAME)) /** * @return true if initialization was successful */ private fun initialize(buildDataPaths: BuildDataPaths): Boolean = initializeSubtypeStorage(buildDataPaths, subtypesStorage) private fun close() { lookupStorageReader.close() subtypesStorage.closeAndClean() } fun getUsages(fqName: FqName): List<VirtualFile> = lookupStorageReader[fqName].mapNotNull { VfsUtil.findFile(it, true) } fun getSubtypesOf(fqName: FqName, deep: Boolean): Sequence<FqName> = subtypesStorage[fqName, deep] } private fun initializeStorage(destinationMap: MultiMap<String, String>, subtypesSourcePath: Path) { createKotlinDataReader(subtypesSourcePath).use { source -> source.processKeys { key -> source[key]?.let { values -> destinationMap.putValues(key, values) } true } } } private fun createKotlinDataReader(storagePath: Path): PersistentHashMap<String, Collection<String>> = openReadOnlyPersistentHashMap( storagePath, EnumeratorStringDescriptor.INSTANCE, CollectionExternalizer<String>(EnumeratorStringDescriptor.INSTANCE, ::SmartList), )
plugins/kotlin/refIndex/src/org/jetbrains/kotlin/idea/search/refIndex/KotlinCompilerReferenceIndexStorage.kt
2344825564
// "Add remaining branches with * import" "true" // WITH_STDLIB enum class Foo { A, B, C } class Test { fun foo(e: Foo) { when<caret> (e) { } } }
plugins/kotlin/idea/tests/testData/quickfix/when/addRemainingBranchesEnumImport1.kt
3629131027
// "Create object 'RED'" "true" enum class SampleEnum {} fun usage() { SampleEnum.RED<caret> }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/referenceExpression/objectForEnum.kt
839853553
fun <caret>foo(p2: Int, p1: Int, filter: (Int) -> Boolean, p3: Int = 0){} fun bar() { foo(2, 1, { true }) }
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/DefaultAfterLambdaAfter.kt
1032325411
fun main(args: Array<String>) { val b: Base = Derived() <caret>val a = 1 } open class Base { fun funInBase() {} open fun funWithOverride() { } open fun funWithoutOverride() { } fun funInBoth() { } } open class Intermediate : Base() { fun funInIntermediate(){} } class Derived : Intermediate() { fun funInDerived() { } override fun funWithOverride() { } fun funInBoth(p: Int) { } } // INVOCATION_COUNT: 1 // EXIST: { itemText: "funInBase", tailText: "()", attributes: "bold" } // EXIST: { itemText: "funWithOverride", tailText: "()", attributes: "bold" } // EXIST: { itemText: "funWithoutOverride", tailText: "()", attributes: "bold" } // EXIST: { itemText: "funInDerived", tailText: "()", attributes: "bold" } // EXIST: { itemText: "funInBoth", tailText: "()", attributes: "bold" } // EXIST: { itemText: "funInBoth", tailText: "(p: Int)", attributes: "bold" } // EXIST: { itemText: "funInIntermediate", tailText: "()", attributes: "" } // NOTHING_ELSE // RUNTIME_TYPE: Derived
plugins/kotlin/completion/tests/testData/basic/codeFragments/runtimeType/runtimeCast.kt
3821300684
// SET_TRUE: USE_TAB_CHARACTER // SET_INT: TAB_SIZE=4 // SET_INT: INDENT_SIZE=4 object A { val a = """blah<caret> blah""" } // IGNORE_FORMATTER
plugins/kotlin/idea/tests/testData/editor/enterHandler/multilineString/withTabs/tabs4/EnterInsideText.kt
1263372033
package suspendFunctionsWithContext // ATTACH_LIBRARY: maven(org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2) import kotlinx.coroutines.yield import kotlinx.coroutines.runBlocking suspend fun one(): Int { yield() return 1 } suspend fun two(): Int { yield() return 2 } suspend fun three(): Int { yield() return 3 } fun main(args: Array<String>) = runBlocking { // EXPRESSION: one() + two() + three() // RESULT: 6: I //Breakpoint! println("") }
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/coroutines/suspendFunctionsWithContext.kt
1205168365
// 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.statistics import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin open class KotlinFUSLogger { companion object { private val context = FeatureUsageData().addData("plugin_version", KotlinIdePlugin.version) private val logger = FUCounterUsageLogger.getInstance() fun log(group: FUSEventGroups, event: String) { logger.logEvent(group.GROUP_ID, event, context) } fun log(group: FUSEventGroups, event: String, eventData: Map<String, String>) { val localContext = context.copy() for (entry in eventData) { localContext.addData(entry.key, entry.value) } logger.logEvent(group.GROUP_ID, event, localContext) } } }
plugins/kotlin/base/statistics/src/org/jetbrains/kotlin/idea/statistics/KotlinFUSLogger.kt
1878241568
// 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.tools.projectWizard.cli import org.jetbrains.kotlin.idea.codeInsight.gradle.KotlinGradlePluginVersions import org.jetbrains.kotlin.tools.projectWizard.Versions import org.jetbrains.kotlin.tools.projectWizard.core.service.EapVersionDownloader import org.jetbrains.kotlin.tools.projectWizard.core.service.WizardKotlinVersion import org.jetbrains.kotlin.tools.projectWizard.core.service.KotlinVersionProviderService import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.* import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version class KotlinVersionProviderTestWizardService : KotlinVersionProviderService(), TestWizardService { override fun getKotlinVersion(projectKind: ProjectKind): WizardKotlinVersion = if (projectKind == ProjectKind.COMPOSE) { kotlinVersionWithDefaultValues(Versions.KOTLIN_VERSION_FOR_COMPOSE) } else { val repositories = listOf( Repositories.JETBRAINS_KOTLIN_BOOTSTRAP, getKotlinVersionRepository(TEST_KOTLIN_VERSION), DefaultRepository.MAVEN_LOCAL ) WizardKotlinVersion( TEST_KOTLIN_VERSION, getKotlinVersionKind(TEST_KOTLIN_VERSION), repositories, getBuildSystemPluginRepository( getKotlinVersionKind(TEST_KOTLIN_VERSION), repositories ), ) } companion object { val TEST_KOTLIN_VERSION by lazy { Version(KotlinGradlePluginVersions.latest.toString()) } } }
plugins/kotlin/project-wizard/tests/test/org/jetbrains/kotlin/tools/projectWizard/cli/KotlinVersionProviderTestWizardService.kt
1019969017
package info.nightscout.androidaps.danars.di import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.danars.comm.* @Module @Suppress("unused") abstract class DanaRSCommModule { @ContributesAndroidInjector abstract fun contributesDanaRS_Packet(): DanaRS_Packet @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(): DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Get_Basal_Rate(): DanaRS_Packet_Basal_Get_Basal_Rate @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Get_Profile_Basal_Rate(): DanaRS_Packet_Basal_Get_Profile_Basal_Rate @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Get_Profile_Number(): DanaRS_Packet_Basal_Get_Profile_Number @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Set_Basal_Rate(): DanaRS_Packet_Basal_Set_Basal_Rate @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Set_Profile_Basal_Rate(): DanaRS_Packet_Basal_Set_Profile_Basal_Rate @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Set_Profile_Number(): DanaRS_Packet_Basal_Set_Profile_Number @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Set_Suspend_Off(): DanaRS_Packet_Basal_Set_Suspend_Off @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Set_Suspend_On(): DanaRS_Packet_Basal_Set_Suspend_On @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Set_Temporary_Basal(): DanaRS_Packet_Basal_Set_Temporary_Basal @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Get_Temporary_Basal_State(): DanaRS_Packet_Basal_Get_Temporary_Basal_State @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Bolus_Option(): DanaRS_Packet_Bolus_Get_Bolus_Option @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Initial_Bolus(): DanaRS_Packet_Bolus_Get_Initial_Bolus @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Calculation_Information(): DanaRS_Packet_Bolus_Get_Calculation_Information @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information(): DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_CIR_CF_Array(): DanaRS_Packet_Bolus_Get_CIR_CF_Array @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_24_CIR_CF_Array(): DanaRS_Packet_Bolus_Get_24_CIR_CF_Array @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Dual_Bolus(): DanaRS_Packet_Bolus_Get_Dual_Bolus @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Extended_Bolus(): DanaRS_Packet_Bolus_Get_Extended_Bolus @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Extended_Bolus_State(): DanaRS_Packet_Bolus_Get_Extended_Bolus_State @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Extended_Menu_Option_State(): DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Step_Bolus_Information(): DanaRS_Packet_Bolus_Get_Step_Bolus_Information @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_Bolus_Option(): DanaRS_Packet_Bolus_Set_Bolus_Option @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_Initial_Bolus(): DanaRS_Packet_Bolus_Set_Initial_Bolus @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_CIR_CF_Array(): DanaRS_Packet_Bolus_Set_CIR_CF_Array @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_24_CIR_CF_Array(): DanaRS_Packet_Bolus_Set_24_CIR_CF_Array @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_Dual_Bolus(): DanaRS_Packet_Bolus_Set_Dual_Bolus @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_Extended_Bolus(): DanaRS_Packet_Bolus_Set_Extended_Bolus @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel(): DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_Step_Bolus_Start(): DanaRS_Packet_Bolus_Set_Step_Bolus_Start @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_Step_Bolus_Stop(): DanaRS_Packet_Bolus_Set_Step_Bolus_Stop @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Etc_Keep_Connection(): DanaRS_Packet_Etc_Keep_Connection @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Etc_Set_History_Save(): DanaRS_Packet_Etc_Set_History_Save @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Delivery_Status(): DanaRS_Packet_General_Delivery_Status @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Get_Password(): DanaRS_Packet_General_Get_Password @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Initial_Screen_Information(): DanaRS_Packet_General_Initial_Screen_Information @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Notify_Alarm(): DanaRS_Packet_Notify_Alarm @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Notify_Delivery_Complete(): DanaRS_Packet_Notify_Delivery_Complete @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Notify_Delivery_Rate_Display(): DanaRS_Packet_Notify_Delivery_Rate_Display @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Notify_Missed_Bolus_Alarm(): DanaRS_Packet_Notify_Missed_Bolus_Alarm @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Option_Get_Pump_Time(): DanaRS_Packet_Option_Get_Pump_Time @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Option_Get_User_Option(): DanaRS_Packet_Option_Get_User_Option @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Option_Set_Pump_Time(): DanaRS_Packet_Option_Set_Pump_Time @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Option_Set_User_Option(): DanaRS_Packet_Option_Set_User_Option @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_(): DanaRS_Packet_History_ @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Alarm(): DanaRS_Packet_History_Alarm @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_All_History(): DanaRS_Packet_History_All_History @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Basal(): DanaRS_Packet_History_Basal @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Blood_Glucose(): DanaRS_Packet_History_Blood_Glucose @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Bolus(): DanaRS_Packet_History_Bolus @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Review_Bolus_Avg(): DanaRS_Packet_Review_Bolus_Avg @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Carbohydrate(): DanaRS_Packet_History_Carbohydrate @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Daily(): DanaRS_Packet_History_Daily @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Get_More_Information(): DanaRS_Packet_General_Get_More_Information @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Get_Pump_Check(): DanaRS_Packet_General_Get_Pump_Check @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Get_Shipping_Information(): DanaRS_Packet_General_Get_Shipping_Information @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Get_Today_Delivery_Total(): DanaRS_Packet_General_Get_Today_Delivery_Total @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Get_User_Time_Change_Flag(): DanaRS_Packet_General_Get_User_Time_Change_Flag @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Prime(): DanaRS_Packet_History_Prime @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Refill(): DanaRS_Packet_History_Refill @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Set_History_Upload_Mode(): DanaRS_Packet_General_Set_History_Upload_Mode @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Set_User_Time_Change_Flag_Clear(): DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Suspend(): DanaRS_Packet_History_Suspend @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Temporary(): DanaRS_Packet_History_Temporary @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_APS_Basal_Set_Temporary_Basal(): DanaRS_Packet_APS_Basal_Set_Temporary_Basal @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_APS_History_Events(): DanaRS_Packet_APS_History_Events @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_APS_Set_Event_History(): DanaRS_Packet_APS_Set_Event_History @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Get_Shipping_Version(): DanaRS_Packet_General_Get_Shipping_Version @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Review_Get_Pump_Dec_Ratio(): DanaRS_Packet_Review_Get_Pump_Dec_Ratio @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone(): DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone(): DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone }
danars/src/main/java/info/nightscout/androidaps/danars/di/DanaRSCommModule.kt
504879760
val v = 1 fun f() = 2 object HashMap fun foo() { val v = HashMap<<caret> } // EXIST: String // EXIST: kotlin // EXIST: v // EXIST: f
plugins/kotlin/completion/tests/testData/basic/common/typeArgsOrNot/LessThan.kt
1052754471
// 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.highlighter import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.testFramework.LightProjectDescriptor import org.jetbrains.kotlin.config.KotlinFacetSettingsProvider import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts import org.jetbrains.kotlin.idea.stubs.createFacet import org.jetbrains.kotlin.idea.test.* import org.jetbrains.kotlin.load.java.ReportLevel import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.test.TestMetadata import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @TestRoot("idea/tests") @TestMetadata("testData/highlighterJsr305/project") @RunWith(JUnit38ClassRunner::class) class Jsr305HighlightingTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor { val foreignAnnotationsJar = TestKotlinArtifacts.jsr305 check(foreignAnnotationsJar.exists()) { "${foreignAnnotationsJar.path} does not exist" } val libraryJar = KotlinCompilerStandalone( listOf(IDEA_TEST_DATA_DIR.resolve("highlighterJsr305/library")), classpath = listOf(foreignAnnotationsJar) ).compile() return object : KotlinJdkAndLibraryProjectDescriptor(listOf(TestKotlinArtifacts.kotlinStdlib, foreignAnnotationsJar, libraryJar)) { override fun configureModule(module: Module, model: ModifiableRootModel) { super.configureModule(module, model) module.createFacet(JvmPlatforms.jvm8) val facetSettings = KotlinFacetSettingsProvider.getInstance(module.project)?.getInitializedSettings(module) facetSettings?.apply { val jsrStateByTestName = ReportLevel.findByDescription(getTestName(true)) ?: return@apply compilerSettings!!.additionalArguments += " -Xjsr305=${jsrStateByTestName.description}" updateMergedArguments() } } } } fun testIgnore() { doTest() } fun testWarn() { doTest() } fun testStrict() { doTest() } fun testDefault() { doTest() } private fun doTest() { myFixture.configureByFile("${getTestName(false)}.kt") myFixture.checkHighlighting() } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/highlighter/Jsr305HighlightingTest.kt
4050943353
package acr.browser.lightning.browser import acr.browser.lightning.AppTheme import acr.browser.lightning.R import acr.browser.lightning.ThemableBrowserActivity import acr.browser.lightning.animation.AnimationUtils import acr.browser.lightning.browser.bookmark.BookmarkRecyclerViewAdapter import acr.browser.lightning.browser.color.ColorAnimator import acr.browser.lightning.browser.image.ImageLoader import acr.browser.lightning.browser.keys.KeyEventAdapter import acr.browser.lightning.browser.menu.MenuItemAdapter import acr.browser.lightning.browser.search.IntentExtractor import acr.browser.lightning.browser.search.SearchListener import acr.browser.lightning.browser.ui.BookmarkConfiguration import acr.browser.lightning.browser.ui.TabConfiguration import acr.browser.lightning.browser.ui.UiConfiguration import acr.browser.lightning.browser.search.StyleRemovingTextWatcher import acr.browser.lightning.constant.HTTP import acr.browser.lightning.database.Bookmark import acr.browser.lightning.database.HistoryEntry import acr.browser.lightning.database.SearchSuggestion import acr.browser.lightning.database.WebPage import acr.browser.lightning.database.downloads.DownloadEntry import acr.browser.lightning.databinding.BrowserActivityBinding import acr.browser.lightning.browser.di.injector import acr.browser.lightning.browser.tab.DesktopTabRecyclerViewAdapter import acr.browser.lightning.browser.tab.DrawerTabRecyclerViewAdapter import acr.browser.lightning.browser.tab.TabPager import acr.browser.lightning.browser.tab.TabViewHolder import acr.browser.lightning.browser.tab.TabViewState import acr.browser.lightning.dialog.BrowserDialog import acr.browser.lightning.dialog.DialogItem import acr.browser.lightning.dialog.LightningDialogBuilder import acr.browser.lightning.search.SuggestionsAdapter import acr.browser.lightning.ssl.createSslDrawableForState import acr.browser.lightning.utils.ProxyUtils import acr.browser.lightning.utils.value import android.content.Intent import android.content.pm.ActivityInfo import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.inputmethod.InputMethodManager import android.widget.AdapterView import android.widget.ImageView import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.DrawableRes import androidx.annotation.MenuRes import androidx.appcompat.app.AlertDialog import androidx.core.view.isVisible import androidx.drawerlayout.widget.DrawerLayout import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.SimpleItemAnimator import acr.browser.lightning.browser.view.targetUrl.LongPress import acr.browser.lightning.extensions.color import acr.browser.lightning.extensions.drawable import acr.browser.lightning.extensions.resizeAndShow import acr.browser.lightning.extensions.takeIfInstance import acr.browser.lightning.extensions.tint import android.view.Gravity import android.view.KeyEvent import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.view.WindowManager import javax.inject.Inject /** * The base browser activity that governs the browsing experience for both default and incognito * browsers. */ abstract class BrowserActivity : ThemableBrowserActivity() { private lateinit var binding: BrowserActivityBinding private lateinit var tabsAdapter: ListAdapter<TabViewState, TabViewHolder> private lateinit var bookmarksAdapter: BookmarkRecyclerViewAdapter private var menuItemShare: MenuItem? = null private var menuItemCopyLink: MenuItem? = null private var menuItemAddToHome: MenuItem? = null private var menuItemAddBookmark: MenuItem? = null private var menuItemReaderMode: MenuItem? = null private val defaultColor by lazy { color(R.color.primary_color) } private val backgroundDrawable by lazy { ColorDrawable(defaultColor) } private var customView: View? = null @Suppress("ConvertLambdaToReference") private val launcher = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { presenter.onFileChooserResult(it) } @Inject internal lateinit var imageLoader: ImageLoader @Inject internal lateinit var keyEventAdapter: KeyEventAdapter @Inject internal lateinit var menuItemAdapter: MenuItemAdapter @Inject internal lateinit var inputMethodManager: InputMethodManager @Inject internal lateinit var presenter: BrowserPresenter @Inject internal lateinit var tabPager: TabPager @Inject internal lateinit var intentExtractor: IntentExtractor @Inject internal lateinit var lightningDialogBuilder: LightningDialogBuilder @Inject internal lateinit var uiConfiguration: UiConfiguration @Inject internal lateinit var proxyUtils: ProxyUtils /** * True if the activity is operating in incognito mode, false otherwise. */ abstract fun isIncognito(): Boolean /** * Provide the menu used by the browser instance. */ @MenuRes abstract fun menu(): Int /** * Provide the home icon used by the browser instance. */ @DrawableRes abstract fun homeIcon(): Int override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = BrowserActivityBinding.inflate(LayoutInflater.from(this)) setContentView(binding.root) setSupportActionBar(binding.toolbar) injector.browser2ComponentBuilder() .activity(this) .browserFrame(binding.contentFrame) .toolbarRoot(binding.uiLayout) .toolbar(binding.toolbarLayout) .initialIntent(intent) .incognitoMode(isIncognito()) .build() .inject(this) binding.drawerLayout.addDrawerListener(object : DrawerLayout.SimpleDrawerListener() { override fun onDrawerOpened(drawerView: View) { if (drawerView == binding.tabDrawer) { presenter.onTabDrawerMoved(isOpen = true) } else if (drawerView == binding.bookmarkDrawer) { presenter.onBookmarkDrawerMoved(isOpen = true) } } override fun onDrawerClosed(drawerView: View) { if (drawerView == binding.tabDrawer) { presenter.onTabDrawerMoved(isOpen = false) } else if (drawerView == binding.bookmarkDrawer) { presenter.onBookmarkDrawerMoved(isOpen = false) } } }) binding.bookmarkDrawer.layoutParams = (binding.bookmarkDrawer.layoutParams as DrawerLayout.LayoutParams).apply { gravity = when (uiConfiguration.bookmarkConfiguration) { BookmarkConfiguration.LEFT -> Gravity.START BookmarkConfiguration.RIGHT -> Gravity.END } } binding.tabDrawer.layoutParams = (binding.tabDrawer.layoutParams as DrawerLayout.LayoutParams).apply { gravity = when (uiConfiguration.bookmarkConfiguration) { BookmarkConfiguration.LEFT -> Gravity.END BookmarkConfiguration.RIGHT -> Gravity.START } } binding.homeImageView.isVisible = uiConfiguration.tabConfiguration == TabConfiguration.DESKTOP || isIncognito() binding.homeImageView.setImageResource(homeIcon()) binding.tabCountView.isVisible = uiConfiguration.tabConfiguration == TabConfiguration.DRAWER && !isIncognito() if (uiConfiguration.tabConfiguration == TabConfiguration.DESKTOP) { binding.drawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_LOCKED_CLOSED, binding.tabDrawer ) } if (uiConfiguration.tabConfiguration == TabConfiguration.DRAWER) { tabsAdapter = DrawerTabRecyclerViewAdapter( onClick = presenter::onTabClick, onCloseClick = presenter::onTabClose, onLongClick = presenter::onTabLongClick ) binding.drawerTabsList.isVisible = true binding.drawerTabsList.adapter = tabsAdapter binding.drawerTabsList.layoutManager = LinearLayoutManager(this) binding.desktopTabsList.isVisible = false } else { tabsAdapter = DesktopTabRecyclerViewAdapter( context = this, onClick = presenter::onTabClick, onCloseClick = presenter::onTabClose, onLongClick = presenter::onTabLongClick ) binding.desktopTabsList.isVisible = true binding.desktopTabsList.adapter = tabsAdapter binding.desktopTabsList.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false) binding.desktopTabsList.itemAnimator?.takeIfInstance<SimpleItemAnimator>() ?.supportsChangeAnimations = false binding.drawerTabsList.isVisible = false } bookmarksAdapter = BookmarkRecyclerViewAdapter( onClick = presenter::onBookmarkClick, onLongClick = presenter::onBookmarkLongClick, imageLoader = imageLoader ) binding.bookmarkListView.adapter = bookmarksAdapter binding.bookmarkListView.layoutManager = LinearLayoutManager(this) presenter.onViewAttached(BrowserStateAdapter(this)) val suggestionsAdapter = SuggestionsAdapter(this, isIncognito = isIncognito()).apply { onSuggestionInsertClick = { if (it is SearchSuggestion) { binding.search.setText(it.title) binding.search.setSelection(it.title.length) } else { binding.search.setText(it.url) binding.search.setSelection(it.url.length) } } } binding.search.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> binding.search.clearFocus() presenter.onSearchSuggestionClicked(suggestionsAdapter.getItem(position) as WebPage) inputMethodManager.hideSoftInputFromWindow(binding.root.windowToken, 0) } binding.search.setAdapter(suggestionsAdapter) val searchListener = SearchListener( onConfirm = { presenter.onSearch(binding.search.text.toString()) }, inputMethodManager = inputMethodManager ) binding.search.setOnEditorActionListener(searchListener) binding.search.setOnKeyListener(searchListener) binding.search.addTextChangedListener(StyleRemovingTextWatcher()) binding.search.setOnFocusChangeListener { _, hasFocus -> presenter.onSearchFocusChanged(hasFocus) binding.search.selectAll() } binding.findPrevious.setOnClickListener { presenter.onFindPrevious() } binding.findNext.setOnClickListener { presenter.onFindNext() } binding.findQuit.setOnClickListener { presenter.onFindDismiss() } binding.homeButton.setOnClickListener { presenter.onTabCountViewClick() } binding.actionBack.setOnClickListener { presenter.onBackClick() } binding.actionForward.setOnClickListener { presenter.onForwardClick() } binding.actionHome.setOnClickListener { presenter.onHomeClick() } binding.newTabButton.setOnClickListener { presenter.onNewTabClick() } binding.newTabButton.setOnLongClickListener { presenter.onNewTabLongClick() true } binding.searchRefresh.setOnClickListener { presenter.onRefreshOrStopClick() } binding.actionAddBookmark.setOnClickListener { presenter.onStarClick() } binding.actionPageTools.setOnClickListener { presenter.onToolsClick() } binding.tabHeaderButton.setOnClickListener { presenter.onTabMenuClick() } binding.actionReading.setOnClickListener { presenter.onReadingModeClick() } binding.bookmarkBackButton.setOnClickListener { presenter.onBookmarkMenuClick() } binding.searchSslStatus.setOnClickListener { presenter.onSslIconClick() } tabPager.longPressListener = presenter::onPageLongPress } override fun onNewIntent(intent: Intent?) { intent?.let(intentExtractor::extractUrlFromIntent)?.let(presenter::onNewAction) super.onNewIntent(intent) } override fun onDestroy() { super.onDestroy() presenter.onViewDetached() } override fun onPause() { super.onPause() presenter.onViewHidden() } override fun onBackPressed() { presenter.onNavigateBack() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(menu(), menu) menuItemShare = menu.findItem(R.id.action_share) menuItemCopyLink = menu.findItem(R.id.action_copy) menuItemAddToHome = menu.findItem(R.id.action_add_to_homescreen) menuItemAddBookmark = menu.findItem(R.id.action_add_bookmark) menuItemReaderMode = menu.findItem(R.id.action_reading_mode) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return menuItemAdapter.adaptMenuItem(item)?.let(presenter::onMenuClick)?.let { true } ?: super.onOptionsItemSelected(item) } override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean { return keyEventAdapter.adaptKeyEvent(event)?.let(presenter::onKeyComboClick)?.let { true } ?: super.onKeyUp(keyCode, event) } /** * @see BrowserContract.View.renderState */ fun renderState(viewState: PartialBrowserViewState) { viewState.isBackEnabled?.let { binding.actionBack.isEnabled = it } viewState.isForwardEnabled?.let { binding.actionForward.isEnabled = it } viewState.displayUrl?.let(binding.search::setText) viewState.sslState?.let { binding.searchSslStatus.setImageDrawable(createSslDrawableForState(it)) binding.searchSslStatus.updateVisibilityForDrawable() } viewState.enableFullMenu?.let { menuItemShare?.isVisible = it menuItemCopyLink?.isVisible = it menuItemAddToHome?.isVisible = it menuItemAddBookmark?.isVisible = it menuItemReaderMode?.isVisible = it } viewState.themeColor?.value()?.let(::animateColorChange) viewState.progress?.let { binding.progressView.progress = it } viewState.isRefresh?.let { binding.searchRefresh.setImageResource( if (it) { R.drawable.ic_action_refresh } else { R.drawable.ic_action_delete } ) } viewState.bookmarks?.let(bookmarksAdapter::submitList) viewState.isBookmarked?.let { binding.actionAddBookmark.isSelected = it } viewState.isBookmarkEnabled?.let { binding.actionAddBookmark.isEnabled = it } viewState.isRootFolder?.let { binding.bookmarkBackButton.startAnimation( AnimationUtils.createRotationTransitionAnimation( binding.bookmarkBackButton, if (it) { R.drawable.ic_action_star } else { R.drawable.ic_action_back } ) ) } viewState.findInPage?.let { if (it.isEmpty()) { binding.findBar.isVisible = false } else { binding.findBar.isVisible = true binding.findQuery.text = it } } } /** * @see BrowserContract.View.renderTabs */ fun renderTabs(tabListState: List<TabViewState>) { binding.tabCountView.updateCount(tabListState.size) tabsAdapter.submitList(tabListState) } /** * @see BrowserContract.View.showAddBookmarkDialog */ fun showAddBookmarkDialog(title: String, url: String, folders: List<String>) { lightningDialogBuilder.showAddBookmarkDialog( activity = this, currentTitle = title, currentUrl = url, folders = folders, onSave = presenter::onBookmarkConfirmed ) } /** * @see BrowserContract.View.showBookmarkOptionsDialog */ fun showBookmarkOptionsDialog(bookmark: Bookmark.Entry) { lightningDialogBuilder.showLongPressedDialogForBookmarkUrl( activity = this, onClick = { presenter.onBookmarkOptionClick(bookmark, it) } ) } /** * @see BrowserContract.View.showEditBookmarkDialog */ fun showEditBookmarkDialog(title: String, url: String, folder: String, folders: List<String>) { lightningDialogBuilder.showEditBookmarkDialog( activity = this, currentTitle = title, currentUrl = url, currentFolder = folder, folders = folders, onSave = presenter::onBookmarkEditConfirmed ) } /** * @see BrowserContract.View.showFolderOptionsDialog */ fun showFolderOptionsDialog(folder: Bookmark.Folder) { lightningDialogBuilder.showBookmarkFolderLongPressedDialog( activity = this, onClick = { presenter.onFolderOptionClick(folder, it) } ) } /** * @see BrowserContract.View.showEditFolderDialog */ fun showEditFolderDialog(oldTitle: String) { lightningDialogBuilder.showRenameFolderDialog( activity = this, oldTitle = oldTitle, onSave = presenter::onBookmarkFolderRenameConfirmed ) } /** * @see BrowserContract.View.showDownloadOptionsDialog */ fun showDownloadOptionsDialog(download: DownloadEntry) { lightningDialogBuilder.showLongPressedDialogForDownloadUrl( activity = this, onClick = { presenter.onDownloadOptionClick(download, it) } ) } /** * @see BrowserContract.View.showHistoryOptionsDialog */ fun showHistoryOptionsDialog(historyEntry: HistoryEntry) { lightningDialogBuilder.showLongPressedHistoryLinkDialog( activity = this, onClick = { presenter.onHistoryOptionClick(historyEntry, it) } ) } /** * @see BrowserContract.View.showFindInPageDialog */ fun showFindInPageDialog() { BrowserDialog.showEditText( this, R.string.action_find, R.string.search_hint, R.string.search_hint, presenter::onFindInPage ) } /** * @see BrowserContract.View.showLinkLongPressDialog */ fun showLinkLongPressDialog(longPress: LongPress) { BrowserDialog.show(this, longPress.targetUrl?.replace(HTTP, ""), DialogItem(title = R.string.dialog_open_new_tab) { presenter.onLinkLongPressEvent( longPress, BrowserContract.LinkLongPressEvent.NEW_TAB ) }, DialogItem(title = R.string.dialog_open_background_tab) { presenter.onLinkLongPressEvent( longPress, BrowserContract.LinkLongPressEvent.BACKGROUND_TAB ) }, DialogItem( title = R.string.dialog_open_incognito_tab, isConditionMet = !isIncognito() ) { presenter.onLinkLongPressEvent( longPress, BrowserContract.LinkLongPressEvent.INCOGNITO_TAB ) }, DialogItem(title = R.string.action_share) { presenter.onLinkLongPressEvent(longPress, BrowserContract.LinkLongPressEvent.SHARE) }, DialogItem(title = R.string.dialog_copy_link) { presenter.onLinkLongPressEvent( longPress, BrowserContract.LinkLongPressEvent.COPY_LINK ) }) } /** * @see BrowserContract.View.showImageLongPressDialog */ fun showImageLongPressDialog(longPress: LongPress) { BrowserDialog.show(this, longPress.targetUrl?.replace(HTTP, ""), DialogItem(title = R.string.dialog_open_new_tab) { presenter.onImageLongPressEvent( longPress, BrowserContract.ImageLongPressEvent.NEW_TAB ) }, DialogItem(title = R.string.dialog_open_background_tab) { presenter.onImageLongPressEvent( longPress, BrowserContract.ImageLongPressEvent.BACKGROUND_TAB ) }, DialogItem( title = R.string.dialog_open_incognito_tab, isConditionMet = !isIncognito() ) { presenter.onImageLongPressEvent( longPress, BrowserContract.ImageLongPressEvent.INCOGNITO_TAB ) }, DialogItem(title = R.string.action_share) { presenter.onImageLongPressEvent( longPress, BrowserContract.ImageLongPressEvent.SHARE ) }, DialogItem(title = R.string.dialog_copy_link) { presenter.onImageLongPressEvent( longPress, BrowserContract.ImageLongPressEvent.COPY_LINK ) }, DialogItem(title = R.string.dialog_download_image) { presenter.onImageLongPressEvent( longPress, BrowserContract.ImageLongPressEvent.DOWNLOAD ) }) } /** * @see BrowserContract.View.showCloseBrowserDialog */ fun showCloseBrowserDialog(id: Int) { BrowserDialog.show( this, R.string.dialog_title_close_browser, DialogItem(title = R.string.close_tab) { presenter.onCloseBrowserEvent(id, BrowserContract.CloseTabEvent.CLOSE_CURRENT) }, DialogItem(title = R.string.close_other_tabs) { presenter.onCloseBrowserEvent(id, BrowserContract.CloseTabEvent.CLOSE_OTHERS) }, DialogItem(title = R.string.close_all_tabs, onClick = { presenter.onCloseBrowserEvent(id, BrowserContract.CloseTabEvent.CLOSE_ALL) }) ) } /** * @see BrowserContract.View.openBookmarkDrawer */ fun openBookmarkDrawer() { binding.drawerLayout.closeDrawer(binding.tabDrawer) binding.drawerLayout.openDrawer(binding.bookmarkDrawer) } /** * @see BrowserContract.View.closeBookmarkDrawer */ fun closeBookmarkDrawer() { binding.drawerLayout.closeDrawer(binding.bookmarkDrawer) } /** * @see BrowserContract.View.openTabDrawer */ fun openTabDrawer() { binding.drawerLayout.closeDrawer(binding.bookmarkDrawer) binding.drawerLayout.openDrawer(binding.tabDrawer) } /** * @see BrowserContract.View.closeTabDrawer */ fun closeTabDrawer() { binding.drawerLayout.closeDrawer(binding.tabDrawer) } /** * @see BrowserContract.View.showToolbar */ fun showToolbar() { tabPager.showToolbar() } /** * @see BrowserContract.View.showToolsDialog */ fun showToolsDialog(areAdsAllowed: Boolean, shouldShowAdBlockOption: Boolean) { val whitelistString = if (areAdsAllowed) { R.string.dialog_adblock_enable_for_site } else { R.string.dialog_adblock_disable_for_site } BrowserDialog.showWithIcons( this, getString(R.string.dialog_tools_title), DialogItem( icon = drawable(R.drawable.ic_action_desktop), title = R.string.dialog_toggle_desktop, onClick = presenter::onToggleDesktopAgent ), DialogItem( icon = drawable(R.drawable.ic_block), colorTint = color(R.color.error_red).takeIf { areAdsAllowed }, title = whitelistString, isConditionMet = shouldShowAdBlockOption, onClick = presenter::onToggleAdBlocking ) ) } /** * @see BrowserContract.View.showLocalFileBlockedDialog */ fun showLocalFileBlockedDialog() { AlertDialog.Builder(this) .setCancelable(true) .setTitle(R.string.title_warning) .setMessage(R.string.message_blocked_local) .setNegativeButton(android.R.string.cancel) { _, _ -> presenter.onConfirmOpenLocalFile(allow = false) } .setPositiveButton(R.string.action_open) { _, _ -> presenter.onConfirmOpenLocalFile(allow = true) } .setOnCancelListener { presenter.onConfirmOpenLocalFile(allow = false) } .resizeAndShow() } /** * @see BrowserContract.View.showFileChooser */ fun showFileChooser(intent: Intent) { launcher.launch(intent) } /** * @see BrowserContract.View.showCustomView */ fun showCustomView(view: View) { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE binding.root.addView(view) customView = view setFullscreen(enabled = true, immersive = true) } /** * @see BrowserContract.View.hideCustomView */ fun hideCustomView() { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED customView?.let(binding.root::removeView) customView = null setFullscreen(enabled = false, immersive = false) } /** * @see BrowserContract.View.clearSearchFocus */ fun clearSearchFocus() { binding.search.clearFocus() } // TODO: update to use non deprecated flags private fun setFullscreen(enabled: Boolean, immersive: Boolean) { val window = window val decor = window.decorView if (enabled) { if (immersive) { decor.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) } else { decor.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE } window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) } else { window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) decor.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE } } private fun animateColorChange(color: Int) { if (!userPreferences.colorModeEnabled || userPreferences.useTheme != AppTheme.LIGHT || isIncognito()) { return } val shouldShowTabsInDrawer = userPreferences.showTabsInDrawer val adapter = tabsAdapter as? DesktopTabRecyclerViewAdapter val colorAnimator = ColorAnimator(defaultColor) binding.toolbar.startAnimation(colorAnimator.animateTo( color ) { mainColor, secondaryColor -> if (shouldShowTabsInDrawer) { backgroundDrawable.color = mainColor window.setBackgroundDrawable(backgroundDrawable) } else { adapter?.updateForegroundTabColor(mainColor) } binding.toolbar.setBackgroundColor(mainColor) binding.searchContainer.background?.tint(secondaryColor) }) } private fun ImageView.updateVisibilityForDrawable() { visibility = if (drawable == null) { View.GONE } else { View.VISIBLE } } }
app/src/main/java/acr/browser/lightning/browser/BrowserActivity.kt
1215848806
// 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.ui.tabs.impl import com.intellij.openapi.util.registry.ExperimentalUI import com.intellij.ui.tabs.JBTabsBorder import com.intellij.ui.tabs.JBTabsPosition import java.awt.* class JBEditorTabsBorder(tabs: JBTabsImpl) : JBTabsBorder(tabs) { override val effectiveBorder: Insets get() = Insets(thickness, 0, 0, 0) override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) { g as Graphics2D tabs.tabPainter.paintBorderLine(g, thickness, Point(x, y), Point(x + width, y)) if(tabs.isEmptyVisible || tabs.isHideTabs) return if (JBTabsImpl.NEW_TABS) { val borderLines = tabs.lastLayoutPass.extraBorderLines ?: return for (borderLine in borderLines) { tabs.tabPainter.paintBorderLine(g, thickness, borderLine.from(), borderLine.to()) } } else { val myInfo2Label = tabs.myInfo2Label val firstLabel = myInfo2Label[tabs.visibleInfos[0]] ?: return val startY = firstLabel.y - if (tabs.position == JBTabsPosition.bottom) 0 else thickness when(tabs.position) { JBTabsPosition.top -> { if (!ExperimentalUI.isNewEditorTabs()) { for (eachRow in 0..tabs.lastLayoutPass.rowCount) { val yl = (eachRow * tabs.myHeaderFitSize.height) + startY tabs.tabPainter.paintBorderLine(g, thickness, Point(x, yl), Point(x + width, yl)) } } } JBTabsPosition.bottom -> { tabs.tabPainter.paintBorderLine(g, thickness, Point(x, startY), Point(x + width, startY)) tabs.tabPainter.paintBorderLine(g, thickness, Point(x, y), Point(x + width, y)) } JBTabsPosition.right -> { val lx = firstLabel.x tabs.tabPainter.paintBorderLine(g, thickness, Point(lx, y), Point(lx, y + height)) } JBTabsPosition.left -> { val bounds = firstLabel.bounds val i = bounds.x + bounds.width - thickness tabs.tabPainter.paintBorderLine(g, thickness, Point(i, y), Point(i, y + height)) } } } val selectedLabel = tabs.selectedLabel ?: return tabs.tabPainter.paintUnderline(tabs.position, selectedLabel.bounds, thickness, g, tabs.isActiveTabs(tabs.selectedInfo)) } }
platform/platform-api/src/com/intellij/ui/tabs/impl/JBEditorTabsBorder.kt
1101516807
package uk.co.alt236.btlescan.ui.control import android.app.Activity import android.widget.ExpandableListView import android.widget.SimpleExpandableListAdapter import android.widget.TextView import androidx.core.content.res.ResourcesCompat import uk.co.alt236.bluetoothlelib.resolvers.GattAttributeResolver import uk.co.alt236.bluetoothlelib.util.ByteUtils import uk.co.alt236.btlescan.R import uk.co.alt236.btlescan.kt.ByteArrayExt.toCharString import java.nio.charset.Charset internal class View(activity: Activity) { private val resources = activity.resources private val mGattServicesList: ExpandableListView = activity.findViewById(R.id.gatt_services_list) private var mConnectionState: TextView = activity.findViewById(R.id.connection_state) private var mGattUUID: TextView = activity.findViewById(R.id.uuid) private var mGattUUIDDesc: TextView = activity.findViewById(R.id.description) private var mDataAsString: TextView = activity.findViewById(R.id.data_as_string) private var mDataAsArray: TextView = activity.findViewById(R.id.data_as_array) private var mDataAsChars: TextView = activity.findViewById(R.id.data_as_characters) fun clearUi() { mGattServicesList.setAdapter(null as SimpleExpandableListAdapter?) mGattUUID.setText(R.string.no_data) mGattUUIDDesc.setText(R.string.no_data) mDataAsArray.setText(R.string.no_data) mDataAsString.setText(R.string.no_data) mDataAsChars.setText(R.string.no_data) } fun setConnectionState(state: State) { val colourId: Int val resId: Int when (state) { State.CONNECTED -> { colourId = android.R.color.holo_green_dark resId = R.string.connected } State.DISCONNECTED -> { colourId = android.R.color.holo_red_dark resId = R.string.disconnected } State.CONNECTING -> { colourId = android.R.color.holo_orange_dark resId = R.string.connecting } } mConnectionState.setText(resId) mConnectionState.setTextColor(ResourcesCompat.getColor(resources, colourId, null)) } fun setGattUuid(uuid: String?) { mGattUUID.text = uuid ?: resources.getString(R.string.no_data) mGattUUIDDesc.text = GattAttributeResolver.getAttributeName(uuid, resources.getString(R.string.unknown)) } fun setData(bytes: ByteArray?) { val safeBytes = bytes ?: ByteArray(0) mDataAsArray.text = quoteString(ByteUtils.byteArrayToHexString(safeBytes)) mDataAsString.text = quoteString(safeBytes.toString(Charset.forName("UTF-8"))) mDataAsChars.text = quoteString(safeBytes.toCharString()) } fun setListAdapter(adapter: SimpleExpandableListAdapter) { mGattServicesList.setAdapter(adapter) } fun setListClickListener(listener: ExpandableListView.OnChildClickListener) { mGattServicesList.setOnChildClickListener(listener) } private fun quoteString(string: String): String { return resources.getString(R.string.formatter_single_quoted_string, string); } }
sample_app/src/main/java/uk/co/alt236/btlescan/ui/control/View.kt
3916008023
// WITH_RUNTIME fun List<String>.test() { this.<caret>mapIndexed { index, _ -> index + 42 } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceMapIndexedWithListGenerator/thisReceiver.kt
3246331522
package pl.ches.citybikes.presentation.common.base.host import pl.ches.citybikes.presentation.common.base.host.enums.ToastKind import com.hannesdorfmann.mosby.mvp.MvpView /** * @author Michał Seroczyński <[email protected]> */ interface HostView : MvpView { fun showToast(toastKind: ToastKind) fun showToast(content: String) }
app/src/main/kotlin/pl/ches/citybikes/presentation/common/base/host/HostView.kt
253994181
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.diagnostic import com.intellij.openapi.progress.ProcessCanceledException import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.NonNls import java.util.concurrent.CancellationException inline fun <reified T : Any> @Suppress("unused") T.thisLogger() = Logger.getInstance(T::class.java) inline fun <reified T : Any> logger() = Logger.getInstance(T::class.java) @Deprecated(level = DeprecationLevel.ERROR, message = "Use Logger directly", replaceWith = ReplaceWith("Logger.getInstance(category)")) @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") fun logger(@NonNls category: String) = Logger.getInstance(category) inline fun Logger.debug(e: Exception? = null, lazyMessage: () -> @NonNls String) { if (isDebugEnabled) { debug(lazyMessage(), e) } } inline fun Logger.trace(@NonNls lazyMessage : () -> String) { if (isTraceEnabled) { trace(lazyMessage()) } } /** Consider using [Result.getOrLogException] for more straight-forward API instead. */ inline fun <T> Logger.runAndLogException(runnable: () -> T): T? { return runCatching { runnable() }.getOrLogException(this) } fun <T> Result<T>.getOrLogException(logger: Logger): T? { return onFailure { e -> when (e) { is ProcessCanceledException, is CancellationException -> throw e else -> logger.error(e) } }.getOrNull() }
platform/util/src/com/intellij/openapi/diagnostic/logger.kt
2192023343
// 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.refactoring.changeSignature import org.jetbrains.kotlin.descriptors.DescriptorVisibility class KotlinMutableMethodDescriptor(override val original: KotlinMethodDescriptor) : KotlinMethodDescriptor by original { private val parameters: MutableList<KotlinParameterInfo> = original.parameters override var receiver: KotlinParameterInfo? = original.receiver set(value) { if (value != null && value !in parameters) { parameters.add(value) } field = value } fun addParameter(parameter: KotlinParameterInfo) { parameters.add(parameter) } fun addParameter(index: Int, parameter: KotlinParameterInfo) { parameters.add(index, parameter) } fun removeParameter(index: Int) { val paramInfo = parameters.removeAt(index) if (paramInfo == receiver) { receiver = null } } fun renameParameter(index: Int, newName: String) { parameters[index].name = newName } fun clearNonReceiverParameters() { parameters.clear() receiver?.let { parameters.add(it) } } override fun getVisibility(): DescriptorVisibility = original.visibility }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinMutableMethodDescriptor.kt
2377600384
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin.internal import com.intellij.psi.PsiSubstitutor import com.intellij.psi.ResolveResult import com.intellij.psi.infos.CandidateInfo import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.UMultiResolvable import org.jetbrains.uast.UResolvable @ApiStatus.Internal interface DelegatedMultiResolve : UMultiResolvable, UResolvable { override fun multiResolve(): Iterable<ResolveResult> = listOfNotNull(resolve()?.let { CandidateInfo(it, PsiSubstitutor.EMPTY) }) }
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/internal/DelegatedMultiResolve.kt
1390577227
/* * Copyright 2010-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.kotlin.native.interop.indexer enum class Language(val sourceFileExtension: String) { C("c"), OBJECTIVE_C("m") } interface HeaderInclusionPolicy { /** * Whether unused declarations from given header should be excluded. * * @param headerName header path relative to the appropriate include path element (e.g. `time.h` or `curl/curl.h`), * or `null` for builtin declarations. */ fun excludeUnused(headerName: String?): Boolean } interface HeaderExclusionPolicy { /** * Whether all declarations from this header should be excluded. * * Note: the declarations from such headers can be actually present in the internal representation, * but not included into the root collections. */ fun excludeAll(headerId: HeaderId): Boolean } sealed class NativeLibraryHeaderFilter { class NameBased( val policy: HeaderInclusionPolicy, val excludeDepdendentModules: Boolean ) : NativeLibraryHeaderFilter() class Predefined(val headers: Set<String>) : NativeLibraryHeaderFilter() } interface Compilation { val includes: List<String> val additionalPreambleLines: List<String> val compilerArgs: List<String> val language: Language } data class CompilationWithPCH( override val compilerArgs: List<String>, override val language: Language ) : Compilation { constructor(compilerArgs: List<String>, precompiledHeader: String, language: Language) : this(compilerArgs + listOf("-include-pch", precompiledHeader), language) override val includes: List<String> get() = emptyList() override val additionalPreambleLines: List<String> get() = emptyList() } // TODO: Compilation hierarchy seems to require some refactoring. data class NativeLibrary(override val includes: List<String>, override val additionalPreambleLines: List<String>, override val compilerArgs: List<String>, val headerToIdMapper: HeaderToIdMapper, override val language: Language, val excludeSystemLibs: Boolean, // TODO: drop? val headerExclusionPolicy: HeaderExclusionPolicy, val headerFilter: NativeLibraryHeaderFilter) : Compilation data class IndexerResult(val index: NativeIndex, val compilation: CompilationWithPCH) /** * Retrieves the definitions from given C header file using given compiler arguments (e.g. defines). */ fun buildNativeIndex(library: NativeLibrary, verbose: Boolean): IndexerResult = buildNativeIndexImpl(library, verbose) /** * This class describes the IR of definitions from C header file(s). */ abstract class NativeIndex { abstract val structs: Collection<StructDecl> abstract val enums: Collection<EnumDef> abstract val objCClasses: Collection<ObjCClass> abstract val objCProtocols: Collection<ObjCProtocol> abstract val objCCategories: Collection<ObjCCategory> abstract val typedefs: Collection<TypedefDef> abstract val functions: Collection<FunctionDecl> abstract val macroConstants: Collection<ConstantDef> abstract val wrappedMacros: Collection<WrappedMacroDef> abstract val globals: Collection<GlobalDecl> abstract val includedHeaders: Collection<HeaderId> } /** * The (contents-based) header id. * Its [value] remains valid across different runs of the indexer and the process, * and thus can be used to 'serialize' the id. */ data class HeaderId(val value: String) data class Location(val headerId: HeaderId) interface TypeDeclaration { val location: Location } sealed class StructMember(val name: String, val type: Type) { abstract val offset: Long? } /** * C struct field. */ class Field(name: String, type: Type, override val offset: Long, val typeSize: Long, val typeAlign: Long) : StructMember(name, type) val Field.isAligned: Boolean get() = offset % (typeAlign * 8) == 0L class BitField(name: String, type: Type, override val offset: Long, val size: Int) : StructMember(name, type) class IncompleteField(name: String, type: Type) : StructMember(name, type) { override val offset: Long? get() = null } /** * C struct declaration. */ abstract class StructDecl(val spelling: String) : TypeDeclaration { abstract val def: StructDef? } /** * C struct definition. * * @param hasNaturalLayout must be `false` if the struct has unnatural layout, e.g. it is `packed`. * May be `false` even if the struct has natural layout. */ abstract class StructDef(val size: Long, val align: Int, val decl: StructDecl) { enum class Kind { STRUCT, UNION } abstract val members: List<StructMember> abstract val kind: Kind val fields: List<Field> get() = members.filterIsInstance<Field>() val bitFields: List<BitField> get() = members.filterIsInstance<BitField>() } /** * C enum value. */ class EnumConstant(val name: String, val value: Long, val isExplicitlyDefined: Boolean) /** * C enum definition. */ abstract class EnumDef(val spelling: String, val baseType: Type) : TypeDeclaration { abstract val constants: List<EnumConstant> } sealed class ObjCContainer { abstract val protocols: List<ObjCProtocol> abstract val methods: List<ObjCMethod> abstract val properties: List<ObjCProperty> } sealed class ObjCClassOrProtocol(val name: String) : ObjCContainer(), TypeDeclaration { abstract val isForwardDeclaration: Boolean } data class ObjCMethod( val selector: String, val encoding: String, val parameters: List<Parameter>, private val returnType: Type, val isVariadic: Boolean, val isClass: Boolean, val nsConsumesSelf: Boolean, val nsReturnsRetained: Boolean, val isOptional: Boolean, val isInit: Boolean, val isExplicitlyDesignatedInitializer: Boolean ) { fun returnsInstancetype(): Boolean = returnType is ObjCInstanceType fun getReturnType(container: ObjCClassOrProtocol): Type = if (returnType is ObjCInstanceType) { when (container) { is ObjCClass -> ObjCObjectPointer(container, returnType.nullability, protocols = emptyList()) is ObjCProtocol -> ObjCIdType(returnType.nullability, protocols = listOf(container)) } } else { returnType } } data class ObjCProperty(val name: String, val getter: ObjCMethod, val setter: ObjCMethod?) { fun getType(container: ObjCClassOrProtocol): Type = getter.getReturnType(container) } abstract class ObjCClass(name: String) : ObjCClassOrProtocol(name) { abstract val binaryName: String? abstract val baseClass: ObjCClass? } abstract class ObjCProtocol(name: String) : ObjCClassOrProtocol(name) abstract class ObjCCategory(val name: String, val clazz: ObjCClass) : ObjCContainer() /** * C function parameter. */ data class Parameter(val name: String?, val type: Type, val nsConsumed: Boolean) /** * C function declaration. */ class FunctionDecl(val name: String, val parameters: List<Parameter>, val returnType: Type, val binaryName: String, val isDefined: Boolean, val isVararg: Boolean) /** * C typedef definition. * * ``` * typedef $aliased $name; * ``` */ class TypedefDef(val aliased: Type, val name: String, override val location: Location) : TypeDeclaration abstract class MacroDef(val name: String) abstract class ConstantDef(name: String, val type: Type): MacroDef(name) class IntegerConstantDef(name: String, type: Type, val value: Long) : ConstantDef(name, type) class FloatingConstantDef(name: String, type: Type, val value: Double) : ConstantDef(name, type) class StringConstantDef(name: String, type: Type, val value: String) : ConstantDef(name, type) class WrappedMacroDef(name: String, val type: Type) : MacroDef(name) class GlobalDecl(val name: String, val type: Type, val isConst: Boolean) /** * C type. */ interface Type interface PrimitiveType : Type object CharType : PrimitiveType open class BoolType: PrimitiveType object CBoolType : BoolType() object ObjCBoolType : BoolType() // We omit `const` qualifier for IntegerType and FloatingType to make `CBridgeGen` simpler. // See KT-28102. data class IntegerType(val size: Int, val isSigned: Boolean, val spelling: String) : PrimitiveType // TODO: floating type is not actually defined entirely by its size. data class FloatingType(val size: Int, val spelling: String) : PrimitiveType data class VectorType(val elementType: Type, val elementCount: Int, val spelling: String) : PrimitiveType object VoidType : Type data class RecordType(val decl: StructDecl) : Type data class EnumType(val def: EnumDef) : Type data class PointerType(val pointeeType: Type, val pointeeIsConst: Boolean = false) : Type // TODO: refactor type representation and support type modifiers more generally. data class FunctionType(val parameterTypes: List<Type>, val returnType: Type) : Type interface ArrayType : Type { val elemType: Type } data class ConstArrayType(override val elemType: Type, val length: Long) : ArrayType data class IncompleteArrayType(override val elemType: Type) : ArrayType data class VariableArrayType(override val elemType: Type) : ArrayType data class Typedef(val def: TypedefDef) : Type sealed class ObjCPointer : Type { enum class Nullability { Nullable, NonNull, Unspecified } abstract val nullability: Nullability } sealed class ObjCQualifiedPointer : ObjCPointer() { abstract val protocols: List<ObjCProtocol> } data class ObjCObjectPointer( val def: ObjCClass, override val nullability: Nullability, override val protocols: List<ObjCProtocol> ) : ObjCQualifiedPointer() data class ObjCClassPointer( override val nullability: Nullability, override val protocols: List<ObjCProtocol> ) : ObjCQualifiedPointer() data class ObjCIdType( override val nullability: Nullability, override val protocols: List<ObjCProtocol> ) : ObjCQualifiedPointer() data class ObjCInstanceType(override val nullability: Nullability) : ObjCPointer() data class ObjCBlockPointer( override val nullability: Nullability, val parameterTypes: List<Type>, val returnType: Type ) : ObjCPointer() object UnsupportedType : Type
Interop/Indexer/src/main/kotlin/org/jetbrains/kotlin/native/interop/indexer/NativeIndex.kt
3407181816
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.compiler.plugins.kotlin import org.jetbrains.kotlin.analyzer.AnalysisResult import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.cli.jvm.compiler.NoScopeRecordCliBindingTrace import org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.AnalyzingUtils object JvmResolveUtil { fun analyzeAndCheckForErrors( environment: KotlinCoreEnvironment, files: Collection<KtFile> ): AnalysisResult { for (file in files) { try { AnalyzingUtils.checkForSyntacticErrors(file) } catch (e: Exception) { throw TestsCompilerError(e) } } return analyze(environment, files).apply { try { AnalyzingUtils.throwExceptionOnErrors(bindingContext) } catch (e: Exception) { throw TestsCompilerError(e) } } } fun analyze(environment: KotlinCoreEnvironment, files: Collection<KtFile>): AnalysisResult = TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( environment.project, files, NoScopeRecordCliBindingTrace(), environment.configuration, environment::createPackagePartProvider ) }
compose/compiler/compiler-hosted/integration-tests/src/test/java/androidx/compose/compiler/plugins/kotlin/JvmResolveUtil.kt
3183824665
/* * 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.tv.material import androidx.compose.animation.animateColorAsState import androidx.compose.foundation.focusable import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.semantics /** * Material Design tab. * * A default Tab, also known as a Primary Navigation Tab. Tabs organize content across different * screens, data sets, and other interactions. * * This should typically be used inside of a [TabRow], see the corresponding documentation for * example usage. * * @param selected whether this tab is selected or not * @param onSelect called when this tab is selected (when in focus). Doesn't trigger if the tab is * already selected * @param modifier the [Modifier] to be applied to this tab * @param enabled controls the enabled state of this tab. When `false`, this component will not * respond to user input, and it will appear visually disabled and disabled to accessibility * services. * @param colors these will be used by the tab when in different states (focused, * selected, etc.) * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this tab. You can create and pass in your own `remember`ed instance to observe [Interaction]s * and customize the appearance / behavior of this tab in different states. * @param content content of the [Tab] */ @Composable fun Tab( selected: Boolean, onSelect: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, colors: TabColors = TabDefaults.pillIndicatorTabColors(), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable RowScope.() -> Unit ) { val contentColor by animateColorAsState( getTabContentColor( colors = colors, anyTabFocused = LocalTabRowHasFocus.current, selected = selected, enabled = enabled, ) ) CompositionLocalProvider(LocalContentColor provides contentColor) { Row( modifier = modifier .semantics { this.selected = selected this.role = Role.Tab } .onFocusChanged { if (it.isFocused && !selected) { onSelect() } } .focusable(enabled, interactionSource), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, content = content ) } } /** * Represents the colors used in a tab in different states. * * - See [TabDefaults.pillIndicatorTabColors] for the default colors used in a [Tab] when using a * Pill indicator. * - See [TabDefaults.underlinedIndicatorTabColors] for the default colors used in a [Tab] when * using an Underlined indicator */ class TabColors internal constructor( private val activeContentColor: Color, private val selectedContentColor: Color, private val focusedContentColor: Color, private val disabledActiveContentColor: Color, private val disabledSelectedContentColor: Color, ) { /** * Represents the content color for this tab, depending on whether it is inactive and [enabled] * * [Tab] is inactive when the [TabRow] is not focused * * @param enabled whether the button is enabled */ internal fun inactiveContentColor(enabled: Boolean): Color { return if (enabled) activeContentColor.copy(alpha = 0.4f) else disabledActiveContentColor.copy(alpha = 0.4f) } /** * Represents the content color for this tab, depending on whether it is active and [enabled] * * [Tab] is active when some other [Tab] is focused * * @param enabled whether the button is enabled */ internal fun activeContentColor(enabled: Boolean): Color { return if (enabled) activeContentColor else disabledActiveContentColor } /** * Represents the content color for this tab, depending on whether it is selected and [enabled] * * [Tab] is selected when the current [Tab] is selected and not focused * * @param enabled whether the button is enabled */ internal fun selectedContentColor(enabled: Boolean): Color { return if (enabled) selectedContentColor else disabledSelectedContentColor } /** * Represents the content color for this tab, depending on whether it is focused * * * [Tab] is focused when the current [Tab] is selected and focused */ internal fun focusedContentColor(): Color { return focusedContentColor } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is TabColors) return false if (activeContentColor != other.activeContentColor(true)) return false if (selectedContentColor != other.selectedContentColor(true)) return false if (focusedContentColor != other.focusedContentColor()) return false if (disabledActiveContentColor != other.activeContentColor(false)) return false if (disabledSelectedContentColor != other.selectedContentColor(false)) return false return true } override fun hashCode(): Int { var result = activeContentColor.hashCode() result = 31 * result + selectedContentColor.hashCode() result = 31 * result + focusedContentColor.hashCode() result = 31 * result + disabledActiveContentColor.hashCode() result = 31 * result + disabledSelectedContentColor.hashCode() return result } } object TabDefaults { /** * [Tab]'s content colors to in conjunction with underlined indicator */ // TODO: get selected & focused values from theme @Composable fun underlinedIndicatorTabColors( activeContentColor: Color = LocalContentColor.current, selectedContentColor: Color = Color(0xFFC9C2E8), focusedContentColor: Color = Color(0xFFC9BFFF), disabledActiveContentColor: Color = activeContentColor, disabledSelectedContentColor: Color = selectedContentColor, ): TabColors = TabColors( activeContentColor = activeContentColor, selectedContentColor = selectedContentColor, focusedContentColor = focusedContentColor, disabledActiveContentColor = disabledActiveContentColor, disabledSelectedContentColor = disabledSelectedContentColor, ) /** * [Tab]'s content colors to in conjunction with pill indicator */ // TODO: get selected & focused values from theme @Composable fun pillIndicatorTabColors( activeContentColor: Color = LocalContentColor.current, selectedContentColor: Color = Color(0xFFE5DEFF), focusedContentColor: Color = Color(0xFF313033), disabledActiveContentColor: Color = activeContentColor, disabledSelectedContentColor: Color = selectedContentColor, ): TabColors = TabColors( activeContentColor = activeContentColor, selectedContentColor = selectedContentColor, focusedContentColor = focusedContentColor, disabledActiveContentColor = disabledActiveContentColor, disabledSelectedContentColor = disabledSelectedContentColor, ) } /** Returns the [Tab]'s content color based on focused/selected state */ private fun getTabContentColor( colors: TabColors, anyTabFocused: Boolean, selected: Boolean, enabled: Boolean, ): Color = when { anyTabFocused && selected -> colors.focusedContentColor() selected -> colors.selectedContentColor(enabled) anyTabFocused -> colors.activeContentColor(enabled) else -> colors.inactiveContentColor(enabled) }
tv/tv-material/src/main/java/androidx/tv/material/Tab.kt
1980457119
/* * 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.runtime import android.annotation.SuppressLint import android.os.Parcel import android.os.Parcelable @SuppressLint("BanParcelableUsage") internal class ParcelableSnapshotMutableState<T>( value: T, policy: SnapshotMutationPolicy<T> ) : SnapshotMutableStateImpl<T>(value, policy), Parcelable { override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeValue(value) parcel.writeInt( when (policy) { neverEqualPolicy<Any?>() -> PolicyNeverEquals structuralEqualityPolicy<Any?>() -> PolicyStructuralEquality referentialEqualityPolicy<Any?>() -> PolicyReferentialEquality else -> throw IllegalStateException( "Only known types of MutableState's SnapshotMutationPolicy are supported" ) } ) } override fun describeContents(): Int { return 0 } companion object { private const val PolicyNeverEquals = 0 private const val PolicyStructuralEquality = 1 private const val PolicyReferentialEquality = 2 @Suppress("unused") @JvmField val CREATOR: Parcelable.Creator<ParcelableSnapshotMutableState<Any?>> = object : Parcelable.ClassLoaderCreator<ParcelableSnapshotMutableState<Any?>> { override fun createFromParcel( parcel: Parcel, loader: ClassLoader? ): ParcelableSnapshotMutableState<Any?> { val value = parcel.readValue(loader ?: javaClass.classLoader) val policyIndex = parcel.readInt() return ParcelableSnapshotMutableState( value, when (policyIndex) { PolicyNeverEquals -> neverEqualPolicy() PolicyStructuralEquality -> structuralEqualityPolicy() PolicyReferentialEquality -> referentialEqualityPolicy() else -> throw IllegalStateException( "Unsupported MutableState policy $policyIndex was restored" ) } ) } override fun createFromParcel(parcel: Parcel) = createFromParcel(parcel, null) override fun newArray(size: Int) = arrayOfNulls<ParcelableSnapshotMutableState<Any?>?>(size) } } }
compose/runtime/runtime/src/androidMain/kotlin/androidx/compose/runtime/ParcelableSnapshotMutableState.kt
1844366315
package org.jetbrains.protocolModelGenerator import org.jetbrains.jsonProtocol.ItemDescriptor import org.jetbrains.jsonProtocol.ProtocolMetaModel import org.jetbrains.protocolReader.TextOutput internal class TypeDescriptor(val type: BoxableType, private val descriptor: ItemDescriptor, private val asRawString: Boolean = false) { private val optional = descriptor is ItemDescriptor.Named && descriptor.optional fun writeAnnotations(out: TextOutput) { val default = (descriptor as? ProtocolMetaModel.Parameter)?.default if (default != null) { out.append("@Optional").append("(\"").append(default).append("\")").newLine() } if (asRawString) { out.append("@org.jetbrains.jsonProtocol.JsonField(") if (asRawString) { out.append("allowAnyPrimitiveValue=true") } out.append(")").newLine() } } val isNullableType: Boolean get() = !isPrimitive && (optional || asRawString) val isPrimitive: Boolean get() = type == BoxableType.BOOLEAN || type == BoxableType.INT || type == BoxableType.LONG || type == BoxableType.NUMBER }
platform/script-debugger/protocol/protocol-model-generator/src/TypeDescriptor.kt
3484374116
package com.intellij.cce.interpreter import com.intellij.cce.core.Lookup import com.intellij.cce.core.Session import com.intellij.cce.core.TokenProperties import com.intellij.cce.util.ListSizeRestriction import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project class DelegationCompletionInvoker(private val invoker: CompletionInvoker, project: Project) : CompletionInvoker { private val applicationListenersRestriction = ListSizeRestriction.applicationListeners() private val dumbService = DumbService.getInstance(project) override fun moveCaret(offset: Int) = onEdt { invoker.moveCaret(offset) } override fun callCompletion(expectedText: String, prefix: String?): Lookup { return readActionWaitingForSize { invoker.callCompletion(expectedText, prefix) } } override fun finishCompletion(expectedText: String, prefix: String) = readAction { invoker.finishCompletion(expectedText, prefix) } override fun printText(text: String) = writeAction { invoker.printText(text) } override fun deleteRange(begin: Int, end: Int) = writeAction { invoker.deleteRange(begin, end) } override fun emulateUserSession(expectedText: String, nodeProperties: TokenProperties, offset: Int): Session { return readActionWaitingForSize { invoker.emulateUserSession(expectedText, nodeProperties, offset) } } override fun emulateCompletionGolfSession(expectedLine: String, offset: Int, nodeProperties: TokenProperties): Session { return readActionWaitingForSize { invoker.emulateCompletionGolfSession(expectedLine, offset, nodeProperties) } } override fun openFile(file: String): String = readAction { invoker.openFile(file) } override fun closeFile(file: String) = onEdt { invoker.closeFile(file) } override fun isOpen(file: String) = readAction { invoker.isOpen(file) } override fun save() = writeAction { invoker.save() } override fun getText(): String = readAction { invoker.getText() } private fun <T> readActionWaitingForSize(size: Int = 100, action: () -> T): T { applicationListenersRestriction.waitForSize(size) return readAction(action) } private fun <T> readAction(runnable: () -> T): T { var result: T? = null ApplicationManager.getApplication().invokeAndWait { result = dumbService.runReadActionInSmartMode<T>(runnable) } return result!! } private fun writeAction(action: () -> Unit) { ApplicationManager.getApplication().invokeAndWait { ApplicationManager.getApplication().runWriteAction(action) } } private fun onEdt(action: () -> Unit) = ApplicationManager.getApplication().invokeAndWait { action() } }
plugins/evaluation-plugin/src/com/intellij/cce/interpreter/DelegationCompletionInvoker.kt
4210120574
// 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.uast import com.intellij.ide.plugins.DynamicPluginListener import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.lang.Language import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.util.containers.CollectionFactory import com.intellij.util.containers.map2Array import org.jetbrains.annotations.Contract import org.jetbrains.uast.util.ClassSet import org.jetbrains.uast.util.ClassSetsWrapper import org.jetbrains.uast.util.emptyClassSet import java.util.* @Deprecated("use UastFacade or UastLanguagePlugin instead", ReplaceWith("UastFacade")) class UastContext(val project: Project) : UastLanguagePlugin by UastFacade { fun findPlugin(element: PsiElement): UastLanguagePlugin? = UastFacade.findPlugin(element) fun getMethod(method: PsiMethod): UMethod = convertWithParent(method)!! fun getVariable(variable: PsiVariable): UVariable = convertWithParent(variable)!! fun getClass(clazz: PsiClass): UClass = convertWithParent(clazz)!! } /** * The main entry point to uast-conversions. * * In the most cases you could use [toUElement] or [toUElementOfExpectedTypes] extension methods instead of using the `UastFacade` directly */ object UastFacade : UastLanguagePlugin { override val language: Language = object : Language("UastContextLanguage") {} override val priority: Int get() = 0 val languagePlugins: Collection<UastLanguagePlugin> get() = UastLanguagePlugin.getInstances() private var cachedLastPlugin: UastLanguagePlugin = this fun findPlugin(element: PsiElement): UastLanguagePlugin? = findPlugin(element.language) fun findPlugin(language: Language): UastLanguagePlugin? { val cached = cachedLastPlugin if (language === cached.language) return cached val plugin = languagePlugins.firstOrNull { it.language === language } if (plugin != null) cachedLastPlugin = plugin return plugin } override fun isFileSupported(fileName: String): Boolean = languagePlugins.any { it.isFileSupported(fileName) } override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? { return findPlugin(element)?.convertElement(element, parent, requiredType) } override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? { if (element is PsiWhiteSpace) { return null } return findPlugin(element)?.convertElementWithParent(element, requiredType) } override fun getMethodCallExpression( element: PsiElement, containingClassFqName: String?, methodName: String ): UastLanguagePlugin.ResolvedMethod? { return findPlugin(element)?.getMethodCallExpression(element, containingClassFqName, methodName) } override fun getConstructorCallExpression( element: PsiElement, fqName: String ): UastLanguagePlugin.ResolvedConstructor? { return findPlugin(element)?.getConstructorCallExpression(element, fqName) } override fun isExpressionValueUsed(element: UExpression): Boolean { val language = element.getLanguage() return findPlugin(language)?.isExpressionValueUsed(element) ?: false } private tailrec fun UElement.getLanguage(): Language { sourcePsi?.language?.let { return it } val containingElement = this.uastParent ?: throw IllegalStateException("At least UFile should have a language") return containingElement.getLanguage() } override fun <T : UElement> convertElementWithParent(element: PsiElement, requiredTypes: Array<out Class<out T>>): T? = findPlugin(element)?.convertElementWithParent(element, requiredTypes) override fun <T : UElement> convertToAlternatives(element: PsiElement, requiredTypes: Array<out Class<out T>>): Sequence<T> = findPlugin(element)?.convertToAlternatives(element, requiredTypes) ?: emptySequence() private interface UastPluginListener { fun onPluginsChanged() } private val exposedListeners = Collections.newSetFromMap(CollectionFactory.createConcurrentWeakIdentityMap<UastPluginListener, Boolean>()) init { ApplicationManager.getApplication().getMessageBus().simpleConnect().subscribe(DynamicPluginListener.TOPIC, object: DynamicPluginListener { override fun pluginUnloaded(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) { // avoid Language mem-leak on its plugin unload cachedLastPlugin = this@UastFacade } }) UastLanguagePlugin.extensionPointName.addChangeListener({ exposedListeners.forEach(UastPluginListener::onPluginsChanged) }, null) } override fun getPossiblePsiSourceTypes(vararg uastTypes: Class<out UElement>): ClassSet<PsiElement> = object : ClassSet<PsiElement>, UastPluginListener { fun initInner(): ClassSetsWrapper<PsiElement> = ClassSetsWrapper(languagePlugins.map2Array { it.getPossiblePsiSourceTypes(*uastTypes) }) private var inner: ClassSetsWrapper<PsiElement> = initInner() override fun onPluginsChanged() { inner = initInner() } override fun isEmpty(): Boolean = inner.isEmpty() override fun contains(element: Class<out PsiElement>): Boolean = inner.contains(element) override fun toList(): List<Class<out PsiElement>> = inner.toList() }.also { exposedListeners.add(it) } } /** * Converts the element to UAST. */ fun PsiElement?.toUElement(): UElement? = if (this == null) null else UastFacade.convertElementWithParent(this, null) /** * Converts the element to an UAST element of the given type. Returns null if the PSI element type does not correspond * to the given UAST element type. */ @Suppress("UNCHECKED_CAST") @Contract("null, _ -> null") fun <T : UElement> PsiElement?.toUElement(cls: Class<out T>): T? = if (this == null) null else UastFacade.convertElementWithParent(this, cls) as T? @Suppress("UNCHECKED_CAST") @SafeVarargs fun <T : UElement> PsiElement?.toUElementOfExpectedTypes(vararg classes: Class<out T>): T? = this?.let { if (classes.isEmpty()) { UastFacade.convertElementWithParent(this, UElement::class.java) as T? } else if (classes.size == 1) { UastFacade.convertElementWithParent(this, classes[0]) as T? } else { UastFacade.convertElementWithParent(this, classes) } } inline fun <reified T : UElement> PsiElement?.toUElementOfType(): T? = toUElement(T::class.java) /** * Finds an UAST element of a given type at the given [offset] in the specified file. Returns null if there is no UAST * element of the given type at the given offset. */ fun <T : UElement> PsiFile.findUElementAt(offset: Int, cls: Class<out T>): T? { val element = findElementAt(offset) ?: return null val uElement = element.toUElement() ?: return null @Suppress("UNCHECKED_CAST") return uElement.withContainingElements.firstOrNull { cls.isInstance(it) } as T? } /** * Finds an UAST element of the given type among the parents of the given PSI element. */ @JvmOverloads fun <T : UElement> PsiElement?.getUastParentOfType(cls: Class<out T>, strict: Boolean = false): T? = this?.run { val firstUElement = getFirstUElement(this, strict) ?: return null @Suppress("UNCHECKED_CAST") return firstUElement.withContainingElements.firstOrNull { cls.isInstance(it) } as T? } /** * Finds an UAST element of any given type among the parents of the given PSI element. */ @JvmOverloads fun PsiElement?.getUastParentOfTypes(classes: Array<Class<out UElement>>, strict: Boolean = false): UElement? = this?.run { val firstUElement = getFirstUElement(this, strict) ?: return null return firstUElement.withContainingElements.firstOrNull { uElement -> classes.any { cls -> cls.isInstance(uElement) } } } inline fun <reified T : UElement> PsiElement?.getUastParentOfType(strict: Boolean = false): T? = getUastParentOfType(T::class.java, strict) @JvmField val DEFAULT_TYPES_LIST: Array<Class<out UElement>> = arrayOf(UElement::class.java) @JvmField val DEFAULT_EXPRESSION_TYPES_LIST: Array<Class<out UExpression>> = arrayOf(UExpression::class.java) /** * @return types of possible source PSI elements of [language], which instances in principle * can be converted to at least one of the specified [uastTypes] * (or to [UElement] if no type was specified) * * @see UastFacade.getPossiblePsiSourceTypes */ fun getPossiblePsiSourceTypes(language: Language, vararg uastTypes: Class<out UElement>): ClassSet<PsiElement> = UastFacade.findPlugin(language)?.getPossiblePsiSourceTypes(*uastTypes) ?: emptyClassSet() private fun getFirstUElement(psiElement: PsiElement, strict: Boolean = false): UElement? { val startingElement = if (strict) psiElement.parent else psiElement val parentSequence = generateSequence(startingElement, PsiElement::getParent) return parentSequence.mapNotNull { it.toUElement() }.firstOrNull() }
uast/uast-common/src/org/jetbrains/uast/UastContext.kt
3842607286
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packagedetails import com.intellij.openapi.util.NlsSafe import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import org.jetbrains.annotations.Nls import java.net.MalformedURLException import java.net.URL internal sealed class InfoLink( @Nls open val displayName: String, @Nls open val displayNameCapitalized: String ) { abstract val url: String fun hasBrowsableUrl(): Boolean = try { val parsedUrl = URL(url) parsedUrl.protocol.equals("http", ignoreCase = true) || parsedUrl.protocol.equals("https", ignoreCase = true) } catch (e: MalformedURLException) { false } data class ProjectWebsite( @NlsSafe override val url: String ) : InfoLink( PackageSearchBundle.message("packagesearch.ui.toolwindow.link.projectSite"), PackageSearchBundle.message("packagesearch.ui.toolwindow.link.projectSite.capitalized") ) data class Documentation( @NlsSafe override val url: String ) : InfoLink( PackageSearchBundle.message("packagesearch.ui.toolwindow.link.documentation"), PackageSearchBundle.message("packagesearch.ui.toolwindow.link.documentation.capitalized") ) data class Readme( @NlsSafe override val url: String ) : InfoLink( PackageSearchBundle.message("packagesearch.ui.toolwindow.link.readme"), PackageSearchBundle.message("packagesearch.ui.toolwindow.link.readme.capitalized") ) data class License( @NlsSafe override val url: String, @NlsSafe val licenseName: String? ) : InfoLink( PackageSearchBundle.message("packagesearch.ui.toolwindow.link.license"), PackageSearchBundle.message("packagesearch.ui.toolwindow.link.license.capitalized") ) sealed class ScmRepository( @Nls override val displayName: String, @Nls override val displayNameCapitalized: String ) : InfoLink(displayName, displayNameCapitalized) { data class GitHub( override val url: String, val stars: Int? ) : ScmRepository( PackageSearchBundle.message("packagesearch.ui.toolwindow.link.github"), PackageSearchBundle.message("packagesearch.ui.toolwindow.link.github.capitalized") ) data class Generic( override val url: String ) : ScmRepository( PackageSearchBundle.message("packagesearch.ui.toolwindow.link.scm"), PackageSearchBundle.message("packagesearch.ui.toolwindow.link.scm.capitalized") ) } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packagedetails/InfoLink.kt
3918081986
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("KlibCompatibilityInfoUtils") package org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.roots.impl.libraries.LibraryEx import org.jetbrains.kotlin.backend.common.serialization.metadata.KlibMetadataVersion import org.jetbrains.kotlin.backend.common.serialization.metadata.metadataVersion import org.jetbrains.kotlin.idea.base.util.asKotlinLogger import org.jetbrains.kotlin.konan.file.File import org.jetbrains.kotlin.library.* import org.jetbrains.kotlin.platform.TargetPlatform /** * Whether a certain KLIB is compatible for the purposes of IDE: indexation, resolve, etc. */ sealed class KlibCompatibilityInfo(val isCompatible: Boolean) { object Compatible : KlibCompatibilityInfo(true) object Pre14Layout : KlibCompatibilityInfo(false) class IncompatibleMetadata(val isOlder: Boolean) : KlibCompatibilityInfo(false) } abstract class AbstractKlibLibraryInfo internal constructor(project: Project, library: LibraryEx, val libraryRoot: String) : LibraryInfo(project, library) { val resolvedKotlinLibrary: KotlinLibrary = resolveSingleFileKlib( libraryFile = File(libraryRoot), logger = LOG, strategy = ToolingSingleFileKlibResolveStrategy ) val compatibilityInfo: KlibCompatibilityInfo by lazy { resolvedKotlinLibrary.compatibilityInfo } final override fun getLibraryRoots() = listOf(libraryRoot) abstract override val platform: TargetPlatform // must override val uniqueName: String? by lazy { resolvedKotlinLibrary.safeRead(null) { uniqueName } } val isInterop: Boolean by lazy { resolvedKotlinLibrary.safeRead(false) { isInterop } } companion object { private val LOG = Logger.getInstance(AbstractKlibLibraryInfo::class.java).asKotlinLogger() } } val KotlinLibrary.compatibilityInfo: KlibCompatibilityInfo get() { val hasPre14Manifest = safeRead(false) { has_pre_1_4_manifest } if (hasPre14Manifest) return KlibCompatibilityInfo.Pre14Layout val metadataVersion = safeRead(null) { metadataVersion } return when { metadataVersion == null -> { // Too old KLIB format, even doesn't have metadata version KlibCompatibilityInfo.IncompatibleMetadata(true) } !metadataVersion.isCompatible() -> { val isOlder = metadataVersion.isAtLeast(KlibMetadataVersion.INSTANCE) KlibCompatibilityInfo.IncompatibleMetadata(!isOlder) } else -> KlibCompatibilityInfo.Compatible } }
plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/moduleInfo/KlibCompatibilityInfo.kt
3312885525
package six.ca.custom.json import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.moshi.MoshiConverterFactory /** * @author hellenxu * @date 2019-09-29 * Copyright 2019 Six. All rights reserved. */ object NetClient { fun getInstance(): Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(getMoshiConverter()) .build() } private fun getMoshiConverter(): MoshiConverterFactory { return MoshiConverterFactory.create( Moshi.Builder().add(Wrap.ADAPTER_FACTORY) .add(KotlinJsonAdapterFactory()).build() ) } const val BASE_URL = "http://mocky.io" }
Custom/app/src/main/java/six/ca/custom/json/NetClient.kt
2014058872
package io.github.fvasco.pinpoi.importer import android.util.Log import io.github.fvasco.pinpoi.util.ZipGuardInputStream import java.io.IOException import java.io.InputStream import java.util.* import java.util.zip.ZipEntry import java.util.zip.ZipInputStream /** * Import ZIP collection and KMZ file * @author Francesco Vasco */ class ZipImporter : AbstractImporter() { @Throws(IOException::class) override fun importImpl(inputStream: InputStream) { val zipInputStream = ZipInputStream(inputStream) var zipEntry: ZipEntry? = zipInputStream.nextEntry while (zipEntry != null) { val entryName = zipEntry.name val filename = entryName.substringAfterLast('/') val extension = filename.substringAfterLast('.').lowercase() if (!zipEntry.isDirectory && !filename.startsWith(".") && (fileFormatFilter == FileFormatFilter.NONE || extension in fileFormatFilter.validExtensions) ) { val importer = ImporterFacade.createImporter(entryName, null, fileFormatFilter) if (importer != null) { Log.d(ZipImporter::class.java.simpleName, "Import entry $entryName") importer.configureFrom(this) importer.importImpl(ZipGuardInputStream(zipInputStream)) } } zipEntry = zipInputStream.nextEntry } } }
app/src/main/java/io/github/fvasco/pinpoi/importer/ZipImporter.kt
1435386275
// 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.vcs.log.data import com.github.benmanes.caffeine.cache.Caffeine import com.intellij.diagnostic.telemetry.TraceManager import com.intellij.diagnostic.telemetry.computeWithSpan import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.UIUtil import com.intellij.vcs.log.* import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl import com.intellij.vcs.log.util.SequentialLimitedLifoExecutor import org.jetbrains.annotations.CalledInAny import java.awt.EventQueue /** * Provides capabilities to asynchronously calculate "contained in branches" information. */ class ContainingBranchesGetter internal constructor(private val logData: VcsLogData, parentDisposable: Disposable) { private val taskExecutor: SequentialLimitedLifoExecutor<CachingTask> // other fields accessed only from EDT private val loadingFinishedListeners: MutableList<Runnable> = ArrayList() private val cache = Caffeine.newBuilder() .maximumSize(2000) .build<CommitId, List<String>>() private val conditionsCache: CurrentBranchConditionCache private var currentBranchesChecksum = 0 init { conditionsCache = CurrentBranchConditionCache(logData, parentDisposable) taskExecutor = SequentialLimitedLifoExecutor(parentDisposable, 10, CachingTask::run) logData.addDataPackChangeListener { dataPack: DataPack -> val checksum = dataPack.refsModel.branches.hashCode() if (currentBranchesChecksum != checksum) { // clear cache if branches set changed after refresh clearCache() } currentBranchesChecksum = checksum } } @RequiresEdt private fun cache(commitId: CommitId, branches: List<String>, branchesChecksum: Int) { if (branchesChecksum == currentBranchesChecksum) { cache.put(commitId, branches) notifyListeners() } } @RequiresEdt private fun clearCache() { cache.invalidateAll() taskExecutor.clear() conditionsCache.clear() // re-request containing branches information for the commit user (possibly) currently stays on ApplicationManager.getApplication().invokeLater { notifyListeners() } } /** * This task will be executed each time the calculating process completes. */ fun addTaskCompletedListener(runnable: Runnable) { LOG.assertTrue(EventQueue.isDispatchThread()) loadingFinishedListeners.add(runnable) } fun removeTaskCompletedListener(runnable: Runnable) { LOG.assertTrue(EventQueue.isDispatchThread()) loadingFinishedListeners.remove(runnable) } private fun notifyListeners() { LOG.assertTrue(EventQueue.isDispatchThread()) for (listener in loadingFinishedListeners) { listener.run() } } /** * Returns the alphabetically sorted list of branches containing the specified node, if this information is ready; * if it is not available, starts calculating in the background and returns null. */ fun requestContainingBranches(root: VirtualFile, hash: Hash): List<String>? { LOG.assertTrue(EventQueue.isDispatchThread()) val refs = getContainingBranchesFromCache(root, hash) if (refs == null) { taskExecutor.queue(CachingTask(createTask(root, hash, logData.dataPack), currentBranchesChecksum)) } return refs } fun getContainingBranchesFromCache(root: VirtualFile, hash: Hash): List<String>? { LOG.assertTrue(EventQueue.isDispatchThread()) return cache.getIfPresent(CommitId(hash, root)) } @CalledInAny fun getContainingBranchesQuickly(root: VirtualFile, hash: Hash): List<String>? { val cachedBranches = cache.getIfPresent(CommitId(hash, root)) if (cachedBranches != null) return cachedBranches val dataPack = logData.dataPack val commitIndex = logData.getCommitIndex(hash, root) val pg = dataPack.permanentGraph if (pg is PermanentGraphImpl<Int>) { val nodeId = pg.permanentCommitsInfo.getNodeId(commitIndex) if (nodeId < 10000 && canUseGraphForComputation(logData.getLogProvider(root))) { return getContainingBranchesSynchronously(dataPack, root, hash) } } return BackgroundTaskUtil.tryComputeFast({ return@tryComputeFast getContainingBranchesSynchronously(dataPack, root, hash) }, 100) } @CalledInAny fun getContainedInCurrentBranchCondition(root: VirtualFile) = conditionsCache.getContainedInCurrentBranchCondition(root) @CalledInAny fun getContainingBranchesSynchronously(root: VirtualFile, hash: Hash): List<String> { return getContainingBranchesSynchronously(logData.dataPack, root, hash) } @CalledInAny private fun getContainingBranchesSynchronously(dataPack: DataPack, root: VirtualFile, hash: Hash): List<String> { return CachingTask(createTask(root, hash, dataPack), dataPack.refsModel.branches.hashCode()).run() } private fun createTask(root: VirtualFile, hash: Hash, dataPack: DataPack): Task { val provider = logData.getLogProvider(root) return if (canUseGraphForComputation(provider)) { GraphTask(provider, root, hash, dataPack) } else ProviderTask(provider, root, hash) } private abstract class Task(private val myProvider: VcsLogProvider, val myRoot: VirtualFile, val myHash: Hash) { @Throws(VcsException::class) fun getContainingBranches(): List<String> { return computeWithSpan(TraceManager.getTracer("vcs"), "get containing branches") { try { getContainingBranches(myProvider, myRoot, myHash) } catch (e: VcsException) { LOG.warn(e) emptyList() } } } @Throws(VcsException::class) protected abstract fun getContainingBranches(provider: VcsLogProvider, root: VirtualFile, hash: Hash): List<String> } private inner class GraphTask constructor(provider: VcsLogProvider, root: VirtualFile, hash: Hash, dataPack: DataPack) : Task(provider, root, hash) { private val graph = dataPack.permanentGraph private val refs = dataPack.refsModel override fun getContainingBranches(provider: VcsLogProvider, root: VirtualFile, hash: Hash): List<String> { val commitIndex = logData.getCommitIndex(hash, root) return graph.getContainingBranches(commitIndex) .map(::getBranchesRefs) .flatten() .sortedWith(provider.referenceManager.labelsOrderComparator) .map(VcsRef::getName) } private fun getBranchesRefs(branchIndex: Int) = refs.refsToCommit(branchIndex).filter { it.type.isBranch } } private class ProviderTask(provider: VcsLogProvider, root: VirtualFile, hash: Hash) : Task(provider, root, hash) { @Throws(VcsException::class) override fun getContainingBranches(provider: VcsLogProvider, root: VirtualFile, hash: Hash) = provider.getContainingBranches(root, hash).sorted() } private inner class CachingTask(private val delegate: Task, private val branchesChecksum: Int) { fun run(): List<String> { val branches = delegate.getContainingBranches() val commitId = CommitId(delegate.myHash, delegate.myRoot) UIUtil.invokeLaterIfNeeded { cache(commitId, branches, branchesChecksum) } return branches } } companion object { private val LOG = Logger.getInstance(ContainingBranchesGetter::class.java) private fun canUseGraphForComputation(logProvider: VcsLogProvider) = VcsLogProperties.LIGHTWEIGHT_BRANCHES.getOrDefault(logProvider) } }
platform/vcs-log/impl/src/com/intellij/vcs/log/data/ContainingBranchesGetter.kt
3366174262
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 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. * * econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01.flourprod import cc.altruix.econsimtr01.* import cc.altruix.econsimtr01.ch0202.SimResRow import cc.altruix.econsimtr01.ch03.AgriculturalSimulationAccountant import cc.altruix.econsimtr01.ch03.AgriculturalSimulationRowField import cc.altruix.econsimtr01.ch03.Shack import org.joda.time.DateTime import org.slf4j.LoggerFactory import java.util.* /** * @author Dmitri Pisarenko ([email protected]) * @version $Id$ * @since 1.0 */ open class FlourProductionSimulationAccountant( resultsStorage: MutableMap<DateTime, SimResRow<FlourProductionSimRowField>>, scenarioName: String, val asacc:AgriculturalSimulationAccountant = AgriculturalSimulationAccountant( resultsStorage = HashMap<DateTime, SimResRow<AgriculturalSimulationRowField>>(), scenarioName = "" ) ) : AbstractAccountant2<FlourProductionSimRowField>( resultsStorage, scenarioName ) { val LOGGER = LoggerFactory.getLogger( FlourProductionSimulationAccountant::class.java ) override fun timeToMeasure(time: DateTime): Boolean = time.evenHourAndMinute(0, 0) override fun saveRowData( agents: List<IAgent>, target: MutableMap<FlourProductionSimRowField, Double>) { target.put(FlourProductionSimRowField.SEEDS_IN_SHACK, asacc.calculateSeedsInShack(agents)) target.put(FlourProductionSimRowField.FIELD_AREA_WITH_SEEDS, asacc.calculateFieldAreaWithSeeds(agents)) target.put(FlourProductionSimRowField.EMPTY_FIELD_AREA, asacc.calculateEmptyFieldArea(agents)) target.put(FlourProductionSimRowField.FIELD_AREA_WITH_CROP, asacc.calculateFieldAreaWithCrop(agents)) target.put(FlourProductionSimRowField.FLOUR_IN_SHACK, calculateFieldInShack(agents)) } open internal fun calculateFieldInShack(agents: List<IAgent>): Double { val shack = findAgent(Shack.ID, agents) as DefaultAgent if (shack == null) { LOGGER.error("Can't find the shack") return 0.0 } return shack.amount(FlourProductionSimulationParametersProvider .RESOURCE_FLOUR.id) } }
src/main/java/cc/altruix/econsimtr01/flourprod/FlourProductionSimulationAccountant.kt
2657773603
// FIR_IDENTICAL // FIR_COMPARISON class Some fun <T> Some.filter(predicate : (T) -> Boolean) = throw UnsupportedOperationException() fun main(args: Array<String>) { Some().fil<caret> } // ELEMENT: filter // CHAR: ' '
plugins/kotlin/completion/tests/testData/handlers/basic/highOrderFunctions/FunctionLiteralInsertOnSpace.kt
1413359718
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.plugins.templates import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.PluginSettingsOwner import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase import org.jetbrains.kotlin.tools.projectWizard.templates.SimpleJsClientTemplate class JsTemplatesPlugin(context: Context) : TemplatePlugin(context) { override val path = pluginPath override val pipelineTasks: List<PipelineTask> = super.pipelineTasks + listOf( addTemplate, ) companion object : PluginSettingsOwner() { override val pluginPath = "template.jsTemplates" val addTemplate by pipelineTask(GenerationPhase.PREPARE) { withAction { TemplatesPlugin.addTemplate.execute(SimpleJsClientTemplate) } } } }
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/templates/JsTemplatesPlugin.kt
220404337
// OUT_OF_CODE_BLOCK: TRUE // ERROR: Unresolved reference: apri // SKIP_ANALYZE_CHECK class Test { val a : () -> Int = { <caret>pri } }
plugins/kotlin/idea/tests/testData/codeInsight/outOfBlock/InPropertyWithFunctionLiteral.kt
944769610
var x: String = "" set(param: <caret>String) { field = "$param " }
plugins/kotlin/code-insight/inspections-shared/tests/testData/inspectionsLocal/removeSetterParameterType/simple.kt
2421675833
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.k2.codeinsight.structureView import com.intellij.ide.structureView.StructureViewTreeElement import com.intellij.ide.structureView.impl.common.PsiTreeElementBase import com.intellij.navigation.ItemPresentation import com.intellij.openapi.project.DumbService import com.intellij.openapi.ui.Queryable import com.intellij.psi.NavigatablePsiElement import com.intellij.psi.PsiElement import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.symbols.KtSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithVisibility import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer import org.jetbrains.kotlin.descriptors.Visibilities import org.jetbrains.kotlin.idea.structureView.AbstractKotlinStructureViewElement import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.psi.* import javax.swing.Icon import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty class KotlinFirStructureViewElement( override val element: NavigatablePsiElement, ktElement : KtElement, private val isInherited: Boolean = false ) : PsiTreeElementBase<NavigatablePsiElement>(element), AbstractKotlinStructureViewElement, Queryable { private var kotlinPresentation by AssignableLazyProperty { KotlinFirStructureElementPresentation(isInherited, element, ktElement, createSymbolAndThen { it.createPointer() }) } private var visibility by AssignableLazyProperty { analyze(ktElement) { Visibility(createSymbolAndThen { it }) } } /** * @param element represents node element, can be in current file or from super class (e.g. java) * @param inheritElement represents element in the current kotlin file */ constructor(element: NavigatablePsiElement, inheritElement: KtElement, descriptor: KtSymbolPointer<*>, isInherited: Boolean) : this(element, inheritElement, isInherited) { if (element !is KtElement) { // Avoid storing descriptor in fields kotlinPresentation = KotlinFirStructureElementPresentation(isInherited, element, inheritElement, descriptor) analyze(inheritElement) { visibility = Visibility(descriptor.restoreSymbol()) } } } override val accessLevel: Int? get() = visibility.accessLevel override val isPublic: Boolean get() = visibility.isPublic override fun getPresentation(): ItemPresentation = kotlinPresentation override fun getLocationString(): String? = kotlinPresentation.locationString override fun getIcon(open: Boolean): Icon? = kotlinPresentation.getIcon(open) override fun getPresentableText(): String? = kotlinPresentation.presentableText @TestOnly override fun putInfo(info: MutableMap<in String, in String?>) { // Sanity check for API consistency assert(presentation.presentableText == presentableText) { "Two different ways of getting presentableText" } assert(presentation.locationString == locationString) { "Two different ways of getting locationString" } info["text"] = presentableText info["location"] = locationString } override fun getChildrenBase(): Collection<StructureViewTreeElement> { val children = when (val element = element) { is KtFile -> element.declarations is KtClass -> element.getStructureDeclarations() is KtClassOrObject -> element.declarations is KtFunction, is KtClassInitializer, is KtProperty -> element.collectLocalDeclarations() else -> emptyList() } return children.map { KotlinFirStructureViewElement(it, it, isInherited = false) } } private fun PsiElement.collectLocalDeclarations(): List<KtDeclaration> { val result = mutableListOf<KtDeclaration>() acceptChildren(object : KtTreeVisitorVoid() { override fun visitClassOrObject(classOrObject: KtClassOrObject) { result.add(classOrObject) } override fun visitNamedFunction(function: KtNamedFunction) { result.add(function) } }) return result } private fun <T> createSymbolAndThen(modifier : (KtSymbol) -> T): T? { val element = element return when { !element.isValid -> null element !is KtDeclaration -> null element is KtAnonymousInitializer -> null else -> runReadAction { if (!DumbService.isDumb(element.getProject())) { analyze(element) { modifier.invoke(element.getSymbol()) } } else null } } } class Visibility(symbol: KtSymbol?) { private val visibility: org.jetbrains.kotlin.descriptors.Visibility? = (symbol as? KtSymbolWithVisibility)?.visibility val isPublic: Boolean get() = visibility == Visibilities.Public val accessLevel: Int? get() = when { visibility == Visibilities.Public -> 1 visibility == Visibilities.Internal -> 2 visibility == Visibilities.Protected -> 3 visibility?.let { Visibilities.isPrivate(it) } == true -> 4 else -> null } } } private class AssignableLazyProperty<in R, T : Any>(val init: () -> T) : ReadWriteProperty<R, T> { private var _value: T? = null override fun getValue(thisRef: R, property: KProperty<*>): T { return _value ?: init().also { _value = it } } override fun setValue(thisRef: R, property: KProperty<*>, value: T) { _value = value } } fun KtClassOrObject.getStructureDeclarations() = buildList { primaryConstructor?.let { add(it) } primaryConstructorParameters.filterTo(this) { it.hasValOrVar() } addAll(declarations) }
plugins/kotlin/code-insight/kotlin.code-insight.k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/structureView/KotlinFirStructureViewElement.kt
650223292
// 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 git4idea.ui import com.intellij.codeInsight.AutoPopupController import com.intellij.codeInsight.completion.CompletionType import com.intellij.openapi.actionSystem.CustomShortcutSet import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.editor.SpellCheckingEditorCustomizationProvider import com.intellij.openapi.editor.event.BulkAwareDocumentListener import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileTypes.PlainTextLanguage import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.ui.ComboBoxCompositeEditor import com.intellij.ui.EditorTextField import com.intellij.ui.LanguageTextField import com.intellij.ui.TextFieldWithAutoCompletion.installCompletion import com.intellij.ui.TextFieldWithAutoCompletionListProvider import org.jetbrains.annotations.Nls import javax.swing.ComboBoxModel import javax.swing.JComponent import javax.swing.JLabel import javax.swing.event.ListDataEvent import javax.swing.event.ListDataListener class ComboBoxWithAutoCompletion<E>(model: ComboBoxModel<E>, private val project: Project) : ComboBox<E>(model) { private val autoPopupController = AutoPopupController.getInstance(project) private val completionProvider = object : TextFieldWithAutoCompletionListProvider<E>(emptyList()) { override fun getLookupString(item: E) = item.toString() } private var myEditor: EditorEx? = null private var myEditableComponent: EditorTextField? = null private var selectingItem = false @Nls private var myPlaceHolder: String? = null init { isEditable = true initEditor() subscribeForModelChange(model) } override fun setSelectedItem(anObject: Any?) { selectingItem = true super.setSelectedItem(anObject) editor.item = anObject selectingItem = false } override fun getSelectedItem(): Any? { val text = getText() return if (selectingItem || text.isNullOrEmpty()) super.getSelectedItem() else getItems().find { item -> item.toString() == text } } override fun requestFocus() { myEditableComponent?.requestFocus() } @Nls fun getText(): String? { return myEditor?.document?.text } fun updatePreserving(update: () -> Unit) { val oldItem = item if (oldItem != null) { update() item = oldItem return } val editorField = myEditableComponent val editor = editorField?.editor if (editor != null) { val oldText = editorField.text val offset = editor.caretModel.offset val selectionStart = editor.selectionModel.selectionStart val selectionStartPosition = editor.selectionModel.selectionStartPosition val selectionEnd = editor.selectionModel.selectionEnd val selectionEndPosition = editor.selectionModel.selectionEndPosition update() editorField.text = oldText editor.caretModel.moveToOffset(offset) editor.selectionModel.setSelection(selectionStartPosition, selectionStart, selectionEndPosition, selectionEnd) return } update() } fun setPlaceholder(@Nls placeHolder: String) { myPlaceHolder = placeHolder myEditor?.apply { setPlaceholder(myPlaceHolder) } } fun selectAll() { myEditableComponent?.selectAll() } fun addDocumentListener(listener: DocumentListener) { myEditableComponent?.addDocumentListener(listener) } fun removeDocumentListener(listener: DocumentListener) { myEditableComponent?.removeDocumentListener(listener) } private fun initEditor() { val editableComponent = createEditableComponent() myEditableComponent = editableComponent editableComponent.document.addDocumentListener(object : BulkAwareDocumentListener.Simple { override fun documentChanged(e: DocumentEvent) { if (!selectingItem && !isValueReplaced(e)) { showCompletion() } } }) editor = ComboBoxCompositeEditor<String, EditorTextField>(editableComponent, JLabel()) installCompletion(editableComponent.document, project, completionProvider, true) installForceCompletionShortCut(editableComponent) } private fun installForceCompletionShortCut(editableComponent: JComponent) { val completionShortcutSet = getCompletionShortcuts().firstOrNull()?.let { CustomShortcutSet(it) } ?: return DumbAwareAction.create { showCompletion() }.registerCustomShortcutSet(completionShortcutSet, editableComponent) } private fun showCompletion() { if (myEditor != null) { hidePopup() autoPopupController.scheduleAutoPopup(myEditor!!, CompletionType.BASIC) { true } } } private fun getCompletionShortcuts() = KeymapManager.getInstance().activeKeymap.getShortcuts(IdeActions.ACTION_CODE_COMPLETION) private fun createEditableComponent() = object : LanguageTextField(PlainTextLanguage.INSTANCE, project, "") { override fun createEditor(): EditorEx { myEditor = super.createEditor().apply { setShowPlaceholderWhenFocused(true) setPlaceholder(myPlaceHolder) SpellCheckingEditorCustomizationProvider.getInstance().disabledCustomization?.customize(this) } return myEditor!! } } private fun subscribeForModelChange(model: ComboBoxModel<E>) { model.addListDataListener(object : ListDataListener { override fun intervalAdded(e: ListDataEvent?) { completionProvider.setItems(collectItems()) } override fun intervalRemoved(e: ListDataEvent?) { completionProvider.setItems(collectItems()) } override fun contentsChanged(e: ListDataEvent?) { completionProvider.setItems(collectItems()) } private fun collectItems(): List<E> { val items = mutableListOf<E>() for (i in 0 until model.size) { items += model.getElementAt(i) } return items } }) } private fun isValueReplaced(e: DocumentEvent) = e.isWholeTextReplaced || isFieldCleared(e) || isItemSelected(e) private fun isFieldCleared(e: DocumentEvent) = e.oldLength != 0 && getCurrentText(e).isEmpty() private fun isItemSelected(e: DocumentEvent) = e.oldLength == 0 && getCurrentText(e).isNotEmpty() && getCurrentText(e) in getItems().map { it.toString() } private fun getCurrentText(e: DocumentEvent) = getText() ?: e.newFragment private fun getItems() = (0 until itemCount).map { getItemAt(it) } }
plugins/git4idea/src/git4idea/ui/ComboBoxWithAutoCompletion.kt
2013094201
val <caret>a = 1 // EXPECTED: a // EXPECTED_LEGACY: val a = 1
plugins/kotlin/jvm-debugger/test/testData/selectExpression/propertyDeclaration.kt
462629367
package androidx.lifecycle internal fun <T : Any> ViewModel.setTagIfAbsent(key: String, value: T?): T? = setTagIfAbsent(key, value)
gto-support-androidx-lifecycle/src/main/kotlin/androidx/lifecycle/ViewModelInternals.kt
2298215352
package com.jetbrains.python.psi.resolve object IPythonBuiltinConstants { const val DISPLAY = "display" const val GET_IPYTHON = "get_ipython" const val IN = "In" const val OUT = "Out" const val IPYTHON_PACKAGE = "IPython" const val CORE_PACKAGE = "core" const val HISTORY_MANAGER = "HistoryManager" const val OUT_HIST_DICT = "output_hist" const val IN_HIST_DICT = "input_hist_parsed" const val DISPLAY_DOTTED_PATH = "IPython.core.display.display" const val GET_IPYTHON_DOTTED_PATH = "IPython.core.getipython.get_ipython" const val HISTORY_MANAGER_DOTTED_PATH = "IPython.core.history.HistoryManager" const val DOUBLE_UNDERSCORE = "__" const val TRIPLE_UNDERSCORE = "___" }
python/python-psi-impl/src/com/jetbrains/python/psi/resolve/IPythonBuiltinConstants.kt
3935050988
fun test() { val r = 12 r<caret> } // ORDER: r, return
plugins/kotlin/completion/tests/testData/weighers/basic/LocalsBeforeKeywords.kt
3986002382
fun foo() { val a = "some" val b = "text" val bar = "$a <caret>+ $b" }
plugins/kotlin/idea/tests/testData/android/resourceIntention/kotlinAndroidAddStringResource/stringTemplate/main.kt
3311356927
/** * @see Foo.ba<caret>r */ fun xyzzy() { } class Foo { fun bar() { } } // REF: (in Foo).bar()
plugins/kotlin/idea/tests/testData/kdoc/resolve/SeeReference.kt
293785611
val i = false
plugins/kotlin/j2k/new/tests/testData/newJ2k/boxedType/boolean.kt
2571159987
// "Replace with 'addA(d(createDummy, dummyParam1, initDummy = initDummy), dummyParam)'" "true" // WITH_STDLIB typealias NewDummyRef<V> = (Any) -> V inline fun <A : Any> Any.d( createDummy: NewDummyRef<A>, dummyParam1: Int = 0, dummyParam2: Int = 0, initDummy: A.() -> Unit = {} ) = createDummy(this).also(initDummy).also { dummyParam1 + dummyParam2 } @Deprecated("Use d instead", ReplaceWith("addA(d(createDummy, dummyParam1, initDummy = initDummy), dummyParam)")) inline fun <A : Any> MutableList<A>.addA( createDummy: NewDummyRef<A>, dummyParam1: Int = 0, dummyParam: Unit, initDummy: A.() -> Unit = {} ) = createDummy(this).also(initDummy).also { dummyParam1 }.also { add(it) } @Deprecated("Use d instead", ReplaceWith("addA(d(createDummy, dummyParam1, dummyParam2, initDummy), dummyParam)")) inline fun <A : Any> MutableList<A>.addA( createDummy: NewDummyRef<A>, dummyParam1: Int = 0, dummyParam2: Int = 0, dummyParam: Unit, initDummy: A.() -> Unit = {} ) = createDummy(this).also(initDummy).also { dummyParam1 + dummyParam2 }.also { add(it) } @Suppress("NOTHING_TO_INLINE") inline fun <A : Any> MutableList<A>.addA(a: A, dummyParam: Unit): A = a.also { add(a) } fun createHi(any: Any) = "Hi $any" val unDeprecateMe = mutableListOf("Hello").apply { addA<caret>(::createHi, 1, Unit) { // Run the quick fix from the IDE and watch it produce broken code. println("Yo") } }
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/optionalParameters/optionalParameterAndLambdaComplex.kt
1968623880
/* * * * Apache License * * * * Copyright [2017] Sinyuk * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.sinyuk.fanfou.util.linkfy import android.content.res.ColorStateList import android.os.Build import android.support.annotation.ColorInt import android.text.* import android.text.style.URLSpan import android.widget.TextView /** * Utility methods for working with HTML. */ object HtmlUtils { /** * Work around some 'features' of TextView and URLSpans. i.e. vanilla URLSpans do not react to * touch so we replace them with our own [TouchableUrlSpan] * & [LinkTouchMovementMethod] to fix this. * * * Setting a custom MovementMethod on a TextView also alters touch handling (see * TextView#fixFocusableAndClickableSettings) so we need to correct this. * * @param textView the text view * @param input the input */ fun setTextWithNiceLinks(textView: TextView, input: CharSequence) { textView.text = input textView.movementMethod = LinkTouchMovementMethod.getInstance() textView.isFocusable = false textView.isClickable = false textView.isLongClickable = false } /** * Parse the given input using [TouchableUrlSpan]s rather than vanilla [URLSpan]s * so that they respond to touch. * * @param input the input * @param linkTextColor the link text color * @param linkHighlightColor the link highlight color * @return the spannable string builder */ fun parseHtml(input: String, linkTextColor: ColorStateList, @ColorInt linkHighlightColor: Int): SpannableStringBuilder { var spanned = fromHtml(input) // strip any trailing newlines while (spanned[spanned.length - 1] == '\n') { spanned = spanned.delete(spanned.length - 1, spanned.length) } return linkifyPlainLinks(spanned, linkTextColor, linkHighlightColor) } /** * Parse and set text. * * @param textView the text view * @param input the input */ fun parseAndSetText(textView: TextView, input: String) { if (TextUtils.isEmpty(input)) return setTextWithNiceLinks(textView, parseHtml(input, textView.linkTextColors, textView.highlightColor)) } /** * 把[URLSpan]转换成[TouchableUrlSpan] * * @param input the input * @param linkTextColor the link text color * @param linkHighlightColor the link highlight color * @return the spannable string builder */ fun linkifyPlainLinks(input: CharSequence, linkTextColor: ColorStateList, @ColorInt linkHighlightColor: Int): SpannableStringBuilder { val plainLinks = SpannableString(input) // copy of input // Linkify doesn't seem to work as expected on M+ // TODO: figure out why // Linkify.addLinks(plainLinks, Linkify.WEB_URLS); val urlSpans = plainLinks.getSpans(0, plainLinks.length, URLSpan::class.java) // add any plain links to the output val ssb = SpannableStringBuilder(input) for (urlSpan in urlSpans) { ssb.removeSpan(urlSpan) ssb.setSpan(TouchableUrlSpan( urlSpan.url, linkTextColor, linkHighlightColor), plainLinks.getSpanStart(urlSpan), plainLinks.getSpanEnd(urlSpan), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } return ssb } /** * From html spannable string builder. * * @param input the input * @return the spannable string builder */ fun fromHtml(input: String): SpannableStringBuilder { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.fromHtml(input, Html.FROM_HTML_MODE_LEGACY) as SpannableStringBuilder } else { Html.fromHtml(input) as SpannableStringBuilder } } }
presentation/src/main/java/com/sinyuk/fanfou/util/linkfy/HtmlUtils.kt
3711870786
package fr.free.nrw.commons.explore.depictions.media import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import fr.free.nrw.commons.media.MediaClient import io.reactivex.Single import org.junit.Assert import org.junit.Test class PageableDepictedMediaDataSourceTest{ @Test fun `loadFunction loads Media`() { val mediaClient = mock<MediaClient>() whenever(mediaClient.fetchImagesForDepictedItem("test",0,1)) .thenReturn(Single.just(emptyList())) val pageableDepictedMediaDataSource = PageableDepictedMediaDataSource(mock(), mediaClient) pageableDepictedMediaDataSource.onQueryUpdated("test") Assert.assertEquals(pageableDepictedMediaDataSource.loadFunction(0,1), emptyList<String>()) } }
app/src/test/kotlin/fr/free/nrw/commons/explore/depictions/media/PageableDepictedMediaDataSourceTest.kt
1995895088
package com.ipmus /** * Created by mozturk on 7/26/2017. */ import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.KotlinModule import com.ipmus.filter.AuthFilter import com.ipmus.filter.CORSResponseFilter import com.ipmus.resources.* import com.ipmus.util.DigestPassword import org.glassfish.jersey.server.ResourceConfig import org.slf4j.LoggerFactory import java.io.File import javax.ws.rs.ApplicationPath import javax.ws.rs.ext.ContextResolver @ApplicationPath("/") class JerseyApp : ResourceConfig(setOf(ItemResource::class.java, CustomerResource::class.java, BrokerResource::class.java, VesselResource::class.java, VendorResource::class.java, DesignResource::class.java, DesignColorResource::class.java, ShipmentTypeResource::class.java, ShipmentResource::class.java, ContainerResource::class.java, PurchaseOrderResource::class.java, OurPurchaseOrderResource::class.java, VendorInvoiceResource::class.java, LoginResource::class.java, OurInvoiceResource::class.java)) { private val logger = LoggerFactory.getLogger(JerseyApp::class.java) init { register(AuthFilter::class.java) register(CORSResponseFilter::class.java) register(ContextResolver<ObjectMapper> { ObjectMapper().registerModule(KotlinModule()) }) val opsys = System.getProperty("os.name").toLowerCase() logger.info("JerseyApp init $opsys") val userFile = if (opsys.contains("windows")) { "c:/temp/users.txt" } else { "/home/ubuntu/users.txt" } initUsers(userFile) } private fun initUsers(filename: String) { val userType = "User" val es = GenericResource.entityStore val done = es.computeInReadonlyTransaction { txn -> val loadedUsers = txn.getAll(userType) if (!loadedUsers.isEmpty) { logger.info("Users exist. Doing nothing") true } else { false } } if (done) { return } logger.info("Users not initialized, initializing") val users = File(filename).readLines() users.forEach { val tokens = it.split("\t") if (tokens.size == 3) { logger.info("Adding user ${tokens[1]}") es.executeInTransaction { txn -> val user = txn.newEntity(userType) user.setProperty("email", tokens[0]) user.setProperty("name", tokens[1]) user.setProperty("pass", DigestPassword.doWork(tokens[2])) } } } } }
src/main/kotlin/com/ipmus/JerseyApp.kt
637887324
package com.worldexplorerblog.stravaintervall.layouts import android.content.Context import android.util.AttributeSet import android.widget.Checkable import android.widget.RelativeLayout class CheckableRelativeLayout : RelativeLayout, Checkable { private var checkedLayout = false constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) override fun onCreateDrawableState(extraSpace: Int): IntArray? { val drawableState = super.onCreateDrawableState(extraSpace + 1) if (checkedLayout) { mergeDrawableStates(drawableState, intArrayOf(android.R.attr.state_checked)) } return drawableState } override fun toggle() { checkedLayout = !checkedLayout } override fun isChecked(): Boolean { return checkedLayout } override fun setChecked(checked: Boolean) { if (checkedLayout != checked) { checkedLayout = checked refreshDrawableState() } } }
strava-intervall/src/main/kotlin/com/worldexplorerblog/stravaintervall/layouts/CheckableRelativeLayout.kt
126922780
package pt.joaomneto.titancompanion.adventurecreation import android.app.AlertDialog import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.View import android.widget.EditText import android.widget.TextView import java.io.BufferedWriter import java.io.File import java.io.FileWriter import java.io.IOException import pt.joaomneto.titancompanion.BaseFragmentActivity import pt.joaomneto.titancompanion.GamebookSelectionActivity import pt.joaomneto.titancompanion.LoadAdventureActivity import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.adventurecreation.impl.fragments.VitalStatisticsFragment import pt.joaomneto.titancompanion.consts.Constants import pt.joaomneto.titancompanion.consts.FightingFantasyGamebook import pt.joaomneto.titancompanion.util.AdventureFragmentRunner import pt.joaomneto.titancompanion.util.DiceRoller abstract class AdventureCreation( override val fragmentConfiguration: Array<AdventureFragmentRunner> = DEFAULT_FRAGMENTS ) : BaseFragmentActivity(fragmentConfiguration, R.layout.activity_adventure_creation) { companion object { const val NO_PARAMETERS_TO_VALIDATE = "" val DEFAULT_FRAGMENTS = arrayOf( AdventureFragmentRunner(R.string.title_adventure_creation_vitalstats, VitalStatisticsFragment::class) ) } protected var skill = -1 protected var luck = -1 protected var stamina = -1 protected var adventureName: String? = null var gamebook: FightingFantasyGamebook? = null private set override fun onCreate(savedInstanceState: Bundle?) { gamebook = FightingFantasyGamebook.values()[ intent.getIntExtra( GamebookSelectionActivity.GAMEBOOK_ID, -1 ) ] super.onCreate(savedInstanceState) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.adventure_creation, menu) return true } fun rollStats(view: View) { skill = DiceRoller.rollD6() + 6 luck = DiceRoller.rollD6() + 6 stamina = DiceRoller.roll2D6().sum + 12 rollGamebookSpecificStats(view) val skillValue = findViewById<TextView>(R.id.skillValue) val staminaValue = findViewById<TextView>(R.id.staminaValue) val luckValue = findViewById<TextView>(R.id.luckValue) skillValue?.text = skill.toString() staminaValue?.text = stamina.toString() luckValue?.text = luck.toString() } fun saveAdventure() { try { val et = findViewById<EditText>(R.id.adventureNameInput) adventureName = et.text.toString() try { validateCreationParameters() } catch (e: IllegalArgumentException) { showAlert(e.message!!) return } val relDir = ( "save_" + gamebook!!.initials + "_" + adventureName!!.replace(' ', '-') ) var dir = File(filesDir, "ffgbutil") dir = File(dir, relDir) if (!dir.exists()) { dir.mkdirs() } else { dir.deleteRecursively() } val file = File(dir, "initial.xml") val bw = BufferedWriter(FileWriter(file)) bw.write("gamebook=" + gamebook + "\n") bw.write("name=" + adventureName + "\n") bw.write("initialSkill=" + skill + "\n") bw.write("initialLuck=" + luck + "\n") bw.write("initialStamina=" + stamina + "\n") bw.write("currentSkill=" + skill + "\n") bw.write("currentLuck=" + luck + "\n") bw.write("currentStamina=" + stamina + "\n") bw.write("currentReference=1\n") bw.write("equipment=\n") bw.write("notes=\n") bw.write("gold=0\n") storeAdventureSpecificValuesInFile(bw) bw.close() val intent = Intent( this, Constants .getRunActivity(this, gamebook!!) ) intent.putExtra( LoadAdventureActivity.ADVENTURE_SAVEGAME_CONTENT, File(File(File(filesDir, "ffgbutil"), dir.name), "initial.xml").readText() ) intent.putExtra(LoadAdventureActivity.ADVENTURE_NAME, relDir) startActivity(intent) } catch (e: Exception) { throw IllegalStateException(e) } } fun showAlert(message: String) { val builder = AlertDialog.Builder(this) builder.setTitle(R.string.result).setMessage(message).setCancelable(false) .setNegativeButton(R.string.close) { dialog, _ -> dialog.cancel() } val alert = builder.create() alert.show() } @Throws(IllegalArgumentException::class) private fun validateCreationParameters() { val sb = StringBuilder() var error = false sb.append(getString(R.string.someParametersMIssing)) if (this.stamina < 0) { sb.append(getString(R.string.skill2) + ", " + getString(R.string.stamina2) + " and " + getString(R.string.luck2)) error = true } sb.append(if (error) "; " else "") if (this.adventureName == null || this.adventureName!!.trim { it <= ' ' }.isEmpty()) { sb.append(getString(R.string.adventureName)) error = true } val specificParameters = validateCreationSpecificParameters() if (specificParameters != null && specificParameters.isNotEmpty()) { sb.append(if (error) "; " else "") error = true sb.append(specificParameters) } sb.append(")") if (error) { throw IllegalArgumentException(sb.toString()) } } @Throws(IOException::class) open fun storeAdventureSpecificValuesInFile(bw: BufferedWriter) { } open fun rollGamebookSpecificStats(view: View) {} open fun validateCreationSpecificParameters(): String? { return AdventureCreation.Companion.NO_PARAMETERS_TO_VALIDATE } }
src/main/java/pt/joaomneto/titancompanion/adventurecreation/AdventureCreation.kt
3877571336
package io.kotest.core.extensions /** * What is an extension? - An extension allows your code to interact * with the Kotest Engine, changing the behavior of the engine * at runtime. * * How do they differ from Listeners? - They differ because listeners * are purely "callback only" they are notified of events but they are * unable to change the operation of the Engine. * * Which should I use? - Always use a listener if you can - they are * simpler. Only use an extension if you need to adjust the runtime * behavior of the engine, such as when writing an advanced plugin. */ interface Extension
kotest-framework/kotest-framework-api/src/commonMain/kotlin/io/kotest/core/extensions/Extension.kt
4223095653
package io.kotest.matchers.channels import io.kotest.matchers.Matcher import io.kotest.matchers.MatcherResult import io.kotest.matchers.should import io.kotest.matchers.shouldNot import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay /** * Asserts that this [Channel] is closed * * Opposite of [Channel.shouldBeOpen] * */ @ExperimentalCoroutinesApi fun <T> Channel<T>.shouldBeClosed() = this should beClosed() @ExperimentalCoroutinesApi fun <T> beClosed() = object : Matcher<Channel<T>> { override fun test(value: Channel<T>) = MatcherResult( value.isClosedForSend && value.isClosedForReceive, { "Channel should be closed" }, { "Channel should not be closed" } ) } /** * Asserts that this [Channel] is open * * Opposite of [Channel.shouldBeClosed] * */ @ExperimentalCoroutinesApi fun <T> Channel<T>.shouldBeOpen() = this shouldNot beClosed() /** * Asserts that this [Channel] is empty * */ @ExperimentalCoroutinesApi fun <T> Channel<T>.shouldBeEmpty() = this should beEmpty() @ExperimentalCoroutinesApi fun <T> beEmpty() = object : Matcher<Channel<T>> { override fun test(value: Channel<T>) = MatcherResult( value.isEmpty, { "Channel should be empty" }, { "Channel should not be empty" } ) } /** * Asserts that this [Channel] should receive [n] elements, then is closed. * */ @ExperimentalCoroutinesApi suspend fun <T> Channel<T>.shouldHaveSize(n: Int) { repeat(n) { println("Receiving $it") [email protected]() } [email protected]() } /** * Asserts that this [Channel] should receive at least [n] elements * */ suspend fun <T> Channel<T>.shouldReceiveAtLeast(n: Int) { repeat(n) { [email protected]() } } /** * Asserts that this [Channel] should receive at most [n] elements, then close * */ @ExperimentalCoroutinesApi suspend fun <T> Channel<T>.shouldReceiveAtMost(n: Int) { var count = 0 for (value in this@shouldReceiveAtMost) { count++ if (count == n) break } delay(100) [email protected]() }
kotest-assertions/kotest-assertions-core/src/jvmMain/kotlin/io/kotest/matchers/channels/ChannelMatchers.kt
1791888459
package parrot enum class ParrotTypeEnum { EUROPEAN, AFRICAN, NORWEGIAN_BLUE }
Kotlin/src/main/kotlin/parrot/ParrotTypeEnum.kt
3059042390
package com.claraboia.bibleandroid.helpers /* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context import android.graphics.Rect import android.text.TextUtils import android.view.Gravity import android.view.View import android.widget.Toast /** * Helper class for showing cheat sheets (tooltips) for icon-only UI elements on long-press. This is * already default platform behavior for icon-only [android.app.ActionBar] items and tabs. * This class provides this behavior for any other such UI element. * * Based on the original action bar implementation in [ * ActionMenuItemView.java](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/com/android/internal/view/menu/ActionMenuItemView.java). */ object CheatSheet { /** * The estimated height of a toast, in dips (density-independent pixels). This is used to * determine whether or not the toast should appear above or below the UI element. */ private val ESTIMATED_TOAST_HEIGHT_DIPS = 48 /** * Sets up a cheat sheet (tooltip) for the given view by setting its [ ]. When the view is long-pressed, a [Toast] with * the view's [content description][android.view.View.getContentDescription] will be * shown either above (default) or below the view (if there isn't room above it). * @param view The view to add a cheat sheet for. */ fun setup(view: View) { view.setOnLongClickListener { view -> showCheatSheet(view, view.contentDescription) } } /** * Sets up a cheat sheet (tooltip) for the given view by setting its [ ]. When the view is long-pressed, a [Toast] with * the given text will be shown either above (default) or below the view (if there isn't room * above it). * @param view The view to add a cheat sheet for. * * * @param textResId The string resource containing the text to show on long-press. */ fun setup(view: View, textResId: Int) { view.setOnLongClickListener { view -> showCheatSheet(view, view.context.getString(textResId)) } } /** * Sets up a cheat sheet (tooltip) for the given view by setting its [ ]. When the view is long-pressed, a [Toast] with * the given text will be shown either above (default) or below the view (if there isn't room * above it). * @param view The view to add a cheat sheet for. * * * @param text The text to show on long-press. */ fun setup(view: View, text: CharSequence) { view.setOnLongClickListener { view -> showCheatSheet(view, text) } } /** * Removes the cheat sheet for the given view by removing the view's [ ]. * @param view The view whose cheat sheet should be removed. */ fun remove(view: View) { view.setOnLongClickListener(null) } /** * Internal helper method to show the cheat sheet toast. */ private fun showCheatSheet(view: View, text: CharSequence): Boolean { if (TextUtils.isEmpty(text)) { return false } val screenPos = IntArray(2) // origin is device display val displayFrame = Rect() // includes decorations (e.g. status bar) view.getLocationOnScreen(screenPos) view.getWindowVisibleDisplayFrame(displayFrame) val context = view.context val viewWidth = view.width val viewHeight = view.height val viewCenterX = screenPos[0] + viewWidth / 2 val screenWidth = context.resources.displayMetrics.widthPixels val estimatedToastHeight = (ESTIMATED_TOAST_HEIGHT_DIPS * context.resources.displayMetrics.density).toInt() val cheatSheet = Toast.makeText(context, text, Toast.LENGTH_SHORT) val showBelow = screenPos[1] < estimatedToastHeight if (showBelow) { // Show below // Offsets are after decorations (e.g. status bar) are factored in cheatSheet.setGravity(Gravity.TOP or Gravity.CENTER_HORIZONTAL, viewCenterX - screenWidth / 2, screenPos[1] - displayFrame.top + viewHeight) } else { // Show above // Offsets are after decorations (e.g. status bar) are factored in // NOTE: We can't use Gravity.BOTTOM because when the keyboard is up // its height isn't factored in. cheatSheet.setGravity(Gravity.TOP or Gravity.CENTER_HORIZONTAL, viewCenterX - screenWidth / 2, screenPos[1] - displayFrame.top - estimatedToastHeight) } cheatSheet.show() return true } }
app/src/main/java/com/claraboia/bibleandroid/helpers/CheatSheetHelper.kt
2103113238
package com.github.kerubistan.kerub.jackson import com.fasterxml.jackson.core.JsonParseException import com.fasterxml.jackson.databind.JsonMappingException import com.fasterxml.jackson.databind.exc.InvalidFormatException import com.fasterxml.jackson.module.kotlin.readValue import com.github.kerubistan.kerub.model.dynamic.HostDynamic import com.github.kerubistan.kerub.utils.createObjectMapper import org.junit.Test import org.junit.jupiter.api.assertThrows import java.util.UUID.randomUUID class JacksonRocksIT { data class Something(val listOfNotNulls: List<String> = listOf()) data class DataWithListOfInts(val listOfNotNulls: List<Int> = listOf()) data class DataWithMap(val map: Map<String, Int> = mapOf()) @Test fun nullThroughJackson() { assertThrows<JsonMappingException> { val something = createObjectMapper() .readValue(""" { "listOfNotNulls":["foo","bar",null,"baz"] } """.trimIndent(), Something::class.java) } } @Test fun invalidThroughJackson() { // at least this one is good, we can't inject invalid values assertThrows<InvalidFormatException>("string in an int array") { createObjectMapper() .readValue(""" { "listOfNotNulls":[1, 2,"surprise"] } """.trimIndent(), DataWithListOfInts::class.java) } //this is also good assertThrows<InvalidFormatException>("string as value in map") { createObjectMapper() .readValue(""" { "map": {"A":1, "B":"surprise"} } """.trimIndent(), DataWithMap::class.java) } assertThrows<JsonMappingException> { createObjectMapper() .readValue(""" { "map": {"A":1, "B":null} } """.trimIndent(), DataWithMap::class.java) } assertThrows<JsonMappingException> { createObjectMapper() .readValue(""" { "map": {"A":1, "B":""} } """.trimIndent(), DataWithMap::class.java) } } @Test fun otherProblems() { assertThrows<JsonParseException>("duplicate keys not allowed") { createObjectMapper().readValue<HostDynamic>(""" { "@type": "host-dyn", "id": "${randomUUID()}", "id": "${randomUUID()}", "status": "Up", "status": "Down" } """.trimIndent()) } } }
src/test/kotlin/com/github/kerubistan/kerub/jackson/JacksonRocksIT.kt
2785202487
package koma.gui.view.window.preferences.tab.network import mu.KotlinLogging import java.net.Proxy private val logger = KotlinLogging.logger {} sealed class ProxyOption() { override fun toString(): String { return when(this) { is ExistingProxy -> this.proxy.toAddrStr() is NewProxy -> "Add New Proxy" } } fun isNoProxy(): Boolean { return this is ExistingProxy && this.proxy == Proxy.NO_PROXY } } class ExistingProxy(val proxy: Proxy): ProxyOption() class NewProxy(): ProxyOption() private fun Proxy.toAddrStr(): String { logger.debug { "proxy $this" } return when(this.type()) { Proxy.Type.DIRECT -> "No Proxy" Proxy.Type.SOCKS -> "socks://${this.address()}" Proxy.Type.HTTP -> "http://${this.address()}" null -> this.toString() } }
src/main/kotlin/koma/gui/view/window/preferences/tab/network/select_proxy.kt
1370807711
package com.example.presentation.presenter.main import com.example.domain.dayofweek.entity.Language import com.example.presentation.utils.commons.BasePresenter import com.example.presentation.utils.commons.BaseView interface CleanArchMainContract { interface View : BaseView { } interface Presenter : BasePresenter { fun loadDayOfWeek(language: Language, next: (String) -> Unit) } }
CleanArchExample/presentation/src/main/kotlin/com/example/presentation/presenter/main/CleanArchMainContract.kt
2405436165
package me.devsaki.hentoid.activities import android.os.Bundle import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProvider import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback import me.devsaki.hentoid.R import me.devsaki.hentoid.database.domains.Content import me.devsaki.hentoid.databinding.ActivityDuplicateDetectorBinding import me.devsaki.hentoid.events.CommunicationEvent import me.devsaki.hentoid.fragments.tools.DuplicateDetailsFragment import me.devsaki.hentoid.fragments.tools.DuplicateMainFragment import me.devsaki.hentoid.util.ThemeHelper import me.devsaki.hentoid.viewmodels.DuplicateViewModel import me.devsaki.hentoid.viewmodels.ViewModelFactory import org.greenrobot.eventbus.EventBus class DuplicateDetectorActivity : BaseActivity() { private var binding: ActivityDuplicateDetectorBinding? = null private lateinit var viewPager: ViewPager2 // Viewmodel private lateinit var viewModel: DuplicateViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ThemeHelper.applyTheme(this) binding = ActivityDuplicateDetectorBinding.inflate(layoutInflater) binding?.let { setContentView(it.root) it.toolbar.setNavigationOnClickListener { onBackPressed() } } val vmFactory = ViewModelFactory(application) viewModel = ViewModelProvider(this, vmFactory).get(DuplicateViewModel::class.java) // Cancel any previous worker that might be running TODO CANCEL BUTTON // WorkManager.getInstance(application).cancelAllWorkByTag(DuplicateDetectorWorker.WORKER_TAG) initUI() updateToolbar(0, 0, 0) initSelectionToolbar() } override fun onDestroy() { super.onDestroy() binding = null } private fun initUI() { if (null == binding || null == binding?.duplicatesPager) return viewPager = binding?.duplicatesPager as ViewPager2 // Main tabs viewPager.isUserInputEnabled = false // Disable swipe to change tabs viewPager.registerOnPageChangeCallback(object : OnPageChangeCallback() { override fun onPageSelected(position: Int) { enableCurrentFragment() hideSettingsBar() updateToolbar(0, 0, 0) updateTitle(-1) updateSelectionToolbar() } }) updateDisplay() } fun initFragmentToolbars( toolbarOnItemClicked: Toolbar.OnMenuItemClickListener ) { binding?.toolbar?.setOnMenuItemClickListener(toolbarOnItemClicked) } private fun updateDisplay() { val pagerAdapter: FragmentStateAdapter = DuplicatePagerAdapter(this) viewPager.adapter = pagerAdapter pagerAdapter.notifyDataSetChanged() enableCurrentFragment() } fun goBackToMain() { enableFragment(0) // if (isGroupDisplayed()) return // viewModel.searchGroup(Preferences.getGroupingDisplay(), query, Preferences.getGroupSortField(), Preferences.isGroupSortDesc(), Preferences.getArtistGroupVisibility(), isGroupFavsChecked) viewPager.currentItem = 0 // if (titles.containsKey(0)) toolbar.setTitle(titles.get(0)) } fun showDetailsFor(content: Content) { enableFragment(1) viewModel.setContent(content) viewPager.currentItem = 1 } private fun enableCurrentFragment() { enableFragment(viewPager.currentItem) } private fun enableFragment(fragmentIndex: Int) { EventBus.getDefault().post( CommunicationEvent( CommunicationEvent.EV_ENABLE, if (0 == fragmentIndex) CommunicationEvent.RC_DUPLICATE_MAIN else CommunicationEvent.RC_DUPLICATE_DETAILS, null ) ) EventBus.getDefault().post( CommunicationEvent( CommunicationEvent.EV_DISABLE, if (0 == fragmentIndex) CommunicationEvent.RC_DUPLICATE_DETAILS else CommunicationEvent.RC_DUPLICATE_MAIN, null ) ) } fun updateTitle(count: Int) { binding!!.toolbar.title = if (count > -1) resources.getString( R.string.duplicate_detail_title, count ) else resources.getString(R.string.title_activity_duplicate_detector) } fun updateToolbar(localCount: Int, externalCount: Int, streamedCount: Int) { if (null == binding) return binding!!.toolbar.menu.findItem(R.id.action_settings).isVisible = (0 == viewPager.currentItem) binding!!.toolbar.menu.findItem(R.id.action_merge).isVisible = ( 1 == viewPager.currentItem && ( localCount > 1 && 0 == streamedCount && 0 == externalCount || streamedCount > 1 && 0 == localCount && 0 == externalCount || externalCount > 1 && 0 == localCount && 0 == streamedCount ) ) } private fun initSelectionToolbar() { // TODO } private fun hideSettingsBar() { // TODO } private fun updateSelectionToolbar() { // TODO } /** * ============================== SUBCLASS */ private class DuplicatePagerAdapter constructor(fa: FragmentActivity?) : FragmentStateAdapter(fa!!) { override fun createFragment(position: Int): Fragment { return if (0 == position) { DuplicateMainFragment() } else { DuplicateDetailsFragment() } } override fun getItemCount(): Int { return 2 } } }
app/src/main/java/me/devsaki/hentoid/activities/DuplicateDetectorActivity.kt
3335755077
// Copyright 2014 Cognitect. All Rights Reserved. // Copyright 2015 Benjamin Gudehus (updated code to Kotlin 1.0.0). // // 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. // This is a Kotlin port of https://github.com/cognitect-labs/transducers-java package net.onedaybeard.transducers import java.util.* import java.util.concurrent.ThreadLocalRandom import java.util.concurrent.atomic.AtomicBoolean /** * A reducing step function. * @param [R] Type of first argument and return value * @param [T] Type of input to reduce */ interface StepFunction<R, in T> { /** * Applies the reducing function to the current result and * the new input, returning a new result. * * A reducing function can indicate that no more input * should be processed by setting the value of reduced to * true. This causes the reduction process to complete, * returning the most recent result. * @param result The current result value * @param input New input to process * @param reduced A boolean value which can be set to true * to stop the reduction process * @return A new result value */ fun apply(result: R, input: T, reduced: AtomicBoolean): R } private inline fun <R, T> makeStepFunction(crossinline step: (R, T) -> R): StepFunction<R, T> { return object : StepFunction<R, T> { override fun apply(result: R, input: T, reduced: AtomicBoolean): R { return step.invoke(result, input) } } } /** * A complete reducing function. Extends a single reducing step * function and adds a zero-arity function for initializing a new * result and a single-arity function for processing the final * result after the reduction process has completed. * @param [R] Type of first argument and return value * @param [T] Type of input to reduce */ interface ReducingFunction<R, in T> : StepFunction<R, T> { /** * Returns a newly initialized result. * @return a new result */ fun apply(): R = throw UnsupportedOperationException() /** * Completes processing of a final result. * @param result the final reduction result * @return the completed result */ fun apply(result: R): R = result } /** * Abstract base class for implementing a reducing function that chains to * another reducing function. Zero-arity and single-arity overloads of apply * delegate to the chained reducing function. Derived classes must implement * the three-arity overload of apply, and may implement either of the other * two overloads as required. * @param [R] Type of first argument and return value of the reducing functions * @param [A] Input type of reducing function being chained to * @param [B] Input type of this reducing function */ abstract class ReducingFunctionOn<R, in A, in B>( val rf: ReducingFunction<R, A>) : ReducingFunction<R, B> { override fun apply() = rf.apply() override fun apply(result: R) = rf.apply(result) } /** * A Transducer transforms a reducing function of one type into a * reducing function of another (possibly the same) type, applying * mapping, filtering, flattening, etc. logic as desired. * @param [B] The type of data processed by an input process * @param [C] The type of data processed by the transduced process */ interface Transducer<out B, C> { /** * Transforms a reducing function of B into a reducing function * of C. * @param rf The input reducing function * @param <R> The result type of both the input and the output * reducing functions * @return The transformed reducing function */ fun <R> apply(rf: ReducingFunction<R, B>): ReducingFunction<R, C> /** * Composes a transducer with another transducer, yielding * a new transducer. * * @param right the transducer to compose with this transducer * @param <A> the type of input processed by the reducing function * the composed transducer returns when applied * @return A new composite transducer */ fun <A> comp(right: Transducer<A, in B>): Transducer<A, C> = object : Transducer<A, C> { override fun <R> apply(rf: ReducingFunction<R, A>) = [email protected](right.apply(rf)) } } /** * Applies given reducing function to current result and each T in input, using * the result returned from each reduction step as input to the next step. Returns * final result. * @param f a reducing function * @param result an initial result value * @param input the input to process * @param reduced a boolean flag that can be set to indicate that the reducing process * should stop, even though there is still input to process * @param <R> the type of the result * @param <T> the type of each item in input * @return the final reduced result */ fun <R, T> reduce(f: ReducingFunction<R, T>, result: R, input: Iterable<T>, reduced: AtomicBoolean = AtomicBoolean(), completing: Boolean = true): R { var ret = result for (t in input) { ret = f.apply(ret, t, reduced) if (reduced.get()) break } return if (completing) f.apply(ret) else ret } /** * Converts a [StepFunction] into a complete [ReducingFunction]. If [sf] is already * a `StepFunction`, returns it without modification; otherwise returns a new * `ReducingFunction` with a step function that forwards to [sf]. */ fun <R, T> completing(sf: StepFunction<R, T>): ReducingFunction<R, T> = sf as? ReducingFunction ?: object : ReducingFunction<R, T> { override fun apply(result: R, input: T, reduced: AtomicBoolean) = sf.apply(result, input, reduced) } /** * Reduces input using transformed reducing function. Transforms reducing function by applying * transducer. Reducing function must implement zero-arity apply that returns initial result * to start reducing process. * @param xf a transducer (or composed transducers) that transforms the reducing function * @param rf a reducing function * @param input the input to reduce * @param [R] return type * @param [A] type of input expected by reducing function * @param [B] type of input and type accepted by reducing function returned by transducer * @return result of reducing transformed input */ fun <R, A, B> transduce(xf: Transducer<A, B>, rf: ReducingFunction<R, A>, input: Iterable<B>): R = reduce(xf.apply(rf), rf.apply(), input) /** * Reduces input using transformed reducing function. Transforms reducing function by applying * transducer. Step function is converted to reducing function if necessary. Accepts initial value * for reducing process as argument. * @param xf a transducer (or composed transducers) that transforms the reducing function * @param rf a reducing function * @param init an initial value to start reducing process * @param input the input to reduce * @param [R] return type * @param [A] type expected by reducing function * @param [B] type of input and type accepted by reducing function returned by transducer * @return result of reducing transformed input */ fun <R, A, B> transduce(xf: Transducer<A, B>, rf: StepFunction<R, A>, init: R, input: Iterable<B>): R = reduce(xf.apply(completing(rf)), init, input) fun <R, A, B> transduce(xf: Transducer<A, B>, rf: StepFunction<R, A>, init: R, input: Sequence<B>): R = reduce(xf.apply(completing(rf)), init, input.asIterable()) fun <R, A, B> transduce(xf: Transducer<A, B>, rf: (R, A) -> R, init: R, input: Iterable<B>): R = transduce(xf, makeStepFunction(rf), init, input) fun <R, A, B> transduce(xf: Transducer<A, B>, rf: (R, A) -> R, init: R, input: Sequence<B>): R = transduce(xf, makeStepFunction(rf), init, input) /** * Composes a transducer with another transducer, yielding a new transducer. * @param left left hand transducer * @param right right hand transducer */ fun <A, B, C> compose(left: Transducer<B, C>, right: Transducer<A, B>): Transducer<A, C> = left.comp(right) /** * Creates a transducer that transforms a reducing function by applying a mapping * function to each input. * @param f a mapping function from one type to another (can be the same type) * @param [A] input type of input reducing function * @param [B] input type of output reducing function * @return a new transducer */ fun <A, B> map(f: (B) -> A): Transducer<A, B> = object : Transducer<A, B> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, B>(rf) { override fun apply(result: R, input: B, reduced: AtomicBoolean) = rf.apply(result, f(input), reduced) } } /** * Creates a transducer that transforms a reducing function by applying a * predicate to each input and processing only those inputs for which the * predicate is true. * @param p a predicate function * @param [A] input type of input and output reducing functions * @return a new transducer */ fun <A> filter(p: (A) -> Boolean): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { override fun apply(result: R, input: A, reduced: AtomicBoolean): R { return if (p(input)) rf.apply(result, input, reduced) else result } } } /** * Creates a transducer that transforms a reducing function by accepting * an iterable of the expected input type and reducing it * @param [A] input type of input reducing function * @param [B] input type of output reducing function * @return a new transducer */ fun <A> cat(): Transducer<A, Iterable<A>> = object : Transducer<A, Iterable<A>> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, Iterable<A>>(rf) { override fun apply(result: R, input: Iterable<A>, reduced: AtomicBoolean) = reduce(f = rf, result = result, input = input, reduced = reduced, completing = false) } } /** * Creates a transducer that transforms a reducing function using * a composition of map and cat. * @param f a mapping function from one type to another (can be the same type) * @param [A] input type of input reducing function * @param [B] output type of output reducing function and iterable of input type * of input reducing function * @param [C] input type of output reducing function * @return a new transducer */ fun <A, B : Iterable<A>, C> mapcat(f: (C) -> B): Transducer<A, C> = map(f).comp(cat()) /** * Creates a transducer that transforms a reducing function by applying a * predicate to each input and not processing those inputs for which the * predicate is true. * @param p a predicate function * @param [A] input type of input and output reducing functions * @return a new transducer */ fun <A> remove(p: (A) -> Boolean): Transducer<A, A> = filter { !p(it) } /** * Creates a transducer that transforms a reducing function such that * it only processes n inputs, then the reducing process stops. * @param n the number of inputs to process * @param [A] input type of input and output reducing functions * @return a new transducer */ fun <A> take(n: Int): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { private var taken = 0 override fun apply(result: R, input: A, reduced: AtomicBoolean): R { var ret = result if (taken < n) { ret = rf.apply(result, input, reduced) taken++ } else { reduced.set(true) } return ret } } } /** * Creates a transducer that transforms a reducing function such that * it processes inputs as long as the provided predicate returns true. * If the predicate returns false, the reducing process stops. * @param p a predicate used to test inputs * @param [A] input type of input and output reducing functions * @return a new transducer */ fun <A> takeWhile(p: (A) -> Boolean): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { override fun apply(result: R, input: A, reduced: AtomicBoolean): R { var ret = result if (p(input)) { ret = rf.apply(ret, input, reduced) } else { reduced.set(true) } return ret } } } fun <A> distinct(): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunction<R, A> { val intercepted = mutableSetOf<A>() override fun apply(result: R): R { intercepted.clear() return rf.apply(result) } override fun apply(result: R, input: A, reduced: AtomicBoolean): R { if (intercepted.add(input)) { return rf.apply(result, input, reduced) } else { return result } } override fun apply(): R = rf.apply() } } /** * Creates a transducer that transforms a reducing function such that * it skips n inputs, then processes the rest of the inputs. * @param n the number of inputs to skip * @param [A] input type of input and output reducing functionsi * @return a new transducer */ fun <A> drop(n: Int): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { private var dropped = 0 override fun apply(result: R, input: A, reduced: AtomicBoolean): R { var ret = result if (dropped < n) { dropped++ } else { ret = rf.apply(ret, input, reduced) } return ret } } } /** * Creates a transducer that transforms a reducing function such that * it skips inputs as long as the provided predicate returns true. * Once the predicate returns false, the rest of the inputs are * processed. * @param p a predicate used to test inputs * @param <A> input type of input and output reducing functions * @return a new transducer */ fun <A> dropWhile(p: (A) -> Boolean): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { private var drop = true override fun apply(result: R, input: A, reduced: AtomicBoolean): R { if (drop && p(input)) { return result } drop = false return rf.apply(result, input, reduced) } } } /** * Creates a transducer that transforms a reducing function such that * it processes every nth input. * @param n The frequence of inputs to process (e.g., 3 processes every third input). * @param [A] The input type of the input and output reducing functions * @return a new transducer */ fun <A> takeNth(n: Int): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { private var nth = 0 override fun apply(result: R, input: A, reduced: AtomicBoolean): R { return if ((nth++ % n) == 0) rf.apply(result, input, reduced) else result } } } /** * Creates a transducer that transforms a reducing function such that * inputs that are keys in the provided map are replaced by the corresponding * value in the map. * @param smap a map of replacement values * @param [A] the input type of the input and output reducing functions * @return a new transducer */ fun <A> replace(smap: Map<A, A>): Transducer<A, A> { return map { if (smap.containsKey(it)) smap[it]!! else it } } /** * Creates a transducer that transforms a reducing function by applying a * function to each input and processing the resulting value, ignoring values * that are null. * @param f a function for processing inputs * @param [A] the input type of the input and output reducing functions * @return a new transducer */ fun <A : Any> keep(f: (A) -> A?): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { override fun apply(result: R, input: A, reduced: AtomicBoolean): R { val _input = f(input) return if (_input != null) rf.apply(result, _input, reduced) else result } } } /** * Creates a transducer that transforms a reducing function by applying a * function to each input and processing the resulting value, ignoring values * that are null. * @param f a function for processing inputs * @param <A> the input type of the input and output reducing functions * @return a new transducer */ fun <A : Any> keepIndexed(f: (Int, A) -> A?): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { private var n = 0 override fun apply(result: R, input: A, reduced: AtomicBoolean): R { val _input = f(++n, input) return if (_input != null) rf.apply(result, _input, reduced) else result } } } /** * Creates a transducer that transforms a reducing function such that * consecutive identical input values are removed, only a single value * is processed. * @param [A] the input type of the input and output reducing functions * @return a new transducer */ fun <A : Any> dedupe(): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { var prior: A? = null override fun apply(result: R, input: A, reduced: AtomicBoolean): R { var ret = result if (prior != input) { prior = input ret = rf.apply(ret, input, reduced) } return ret } } } /** * Creates a transducer that transforms a reducing function such that * it has the specified probability of processing each input. * @param prob the probability between expressed as a value between 0 and 1. * @param [A] the input type of the input and output reducing functions * @return a new transducer */ fun <A : Any> randomSample(prob: Double): Transducer<A, A> = filter { ThreadLocalRandom.current().nextDouble() < prob } /** * Creates a transducer that transforms a reducing function that processes * iterables of input into a reducing function that processes individual inputs * by gathering series of inputs for which the provided partitioning function returns * the same value, only forwarding them to the next reducing function when the value * the partitioning function returns for a given input is different from the value * returned for the previous input. * @param f the partitioning function * @param [A] the input type of the input and output reducing functions * @param [P] the type returned by the partitioning function * @return a new transducer */ fun <A, P> partitionBy(f: (A) -> P): Transducer<Iterable<A>, A> = object : Transducer<Iterable<A>, A> { override fun <R> apply(rf: ReducingFunction<R, Iterable<A>>) = object : ReducingFunction<R, A> { val part = ArrayList<A>() val mark: Any = Unit var prior: Any? = mark override fun apply(): R = rf.apply() override fun apply(result: R): R { var ret = result if (part.isNotEmpty()) { ret = rf.apply(result, ArrayList(part), AtomicBoolean()) part.clear() } return rf.apply(ret) } override fun apply(result: R, input: A, reduced: AtomicBoolean): R { val p = f(input) if (prior === mark || prior == p) { prior = p part.add(input) return result } val copy = ArrayList(part) prior = p part.clear() val ret = rf.apply(result, copy, reduced) if (!reduced.get()) { part.add(input) } return ret } } } /** * Creates a transducer that transforms a reducing function that processes * iterables of input into a reducing function that processes individual inputs * by gathering series of inputs into partitions of a given size, only forwarding * them to the next reducing function when enough inputs have been accrued. Processes * any remaining buffered inputs when the reducing process completes. * @param n the size of each partition * @param [A] the input type of the input and output reducing functions * @return a new transducer */ fun <A> partitionAll(n: Int): Transducer<Iterable<A>, A> = object : Transducer<Iterable<A>, A> { override fun <R> apply(rf: ReducingFunction<R, Iterable<A>>) = object : ReducingFunction<R, A> { val part = ArrayList<A>() override fun apply(): R = rf.apply() override fun apply(result: R): R { var ret = result if (part.isNotEmpty()) { ret = rf.apply(result, ArrayList(part), AtomicBoolean()) part.clear() } return rf.apply(ret) } override fun apply(result: R, input: A, reduced: AtomicBoolean): R { part.add(input) return if (n == part.size) { try { rf.apply(result, ArrayList(part), reduced) } finally { part.clear() } } else { result } } } } operator fun <A, B, C> Transducer<B, C>.plus(right: Transducer<A, in B>): Transducer<A, C> = this.comp(right)
src/main/kotlin/net/onedaybeard/transducers/Transducers.kt
3138724948
/* * Copyright 2000-2021 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 jetbrains.buildServer.clouds.azure.arm.connector.tasks import com.microsoft.azure.management.Azure import jetbrains.buildServer.clouds.azure.arm.throttler.AzureThrottlerCacheableTaskBaseImpl import rx.Single data class FetchNetworksTaskNetworkDescriptor(val id: String, val regionName: String, val subnets: List<String>) class FetchNetworksTaskImpl : AzureThrottlerCacheableTaskBaseImpl<Unit, List<FetchNetworksTaskNetworkDescriptor>>() { override fun createQuery(api: Azure, parameter: Unit): Single<List<FetchNetworksTaskNetworkDescriptor>> { return api .networks() .listAsync() .map { FetchNetworksTaskNetworkDescriptor(it.id(), it.regionName(), it.subnets().keys.toList())} .toList() .last() .toSingle() } }
plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/connector/tasks/FetchNetworksTaskImpl.kt
1804997279
package org.evomaster.core.search.algorithms.onemax import com.google.inject.AbstractModule import com.google.inject.TypeLiteral import org.evomaster.core.output.service.NoTestCaseWriter import org.evomaster.core.output.service.TestCaseWriter import org.evomaster.core.search.service.mutator.EmptyStructureMutator import org.evomaster.core.search.service.mutator.StandardMutator import org.evomaster.core.search.service.* import org.evomaster.core.search.service.mutator.Mutator import org.evomaster.core.search.service.mutator.StructureMutator import org.evomaster.core.search.tracer.ArchiveMutationTrackService import org.evomaster.core.search.tracer.TrackService class ManipulatedOneMaxModule : AbstractModule() { override fun configure() { bind(object : TypeLiteral<Sampler<*>>() {}) .to(OneMaxSampler::class.java) .asEagerSingleton() bind(object : TypeLiteral<Sampler<OneMaxIndividual>>() {}) .to(OneMaxSampler::class.java) .asEagerSingleton() bind(OneMaxSampler::class.java) .asEagerSingleton() bind(object : TypeLiteral<FitnessFunction<OneMaxIndividual>>() {}) .to(OneMaxFitness::class.java) .asEagerSingleton() bind(object : TypeLiteral<Mutator<OneMaxIndividual>>() {}) .to(object : TypeLiteral<ManipulatedOneMaxMutator>() {}) .asEagerSingleton() bind(ManipulatedOneMaxMutator::class.java) .asEagerSingleton() bind(object : TypeLiteral<Archive<OneMaxIndividual>>() {}) .asEagerSingleton() bind(object : TypeLiteral<Archive<*>>() {}) .to(object : TypeLiteral<Archive<OneMaxIndividual>>() {}) .asEagerSingleton() bind(StructureMutator::class.java) .to(EmptyStructureMutator::class.java) .asEagerSingleton() bind(TrackService::class.java) .to(ArchiveMutationTrackService::class.java) .asEagerSingleton() bind(ArchiveMutationTrackService::class.java) .asEagerSingleton() bind(TestCaseWriter::class.java) .to(NoTestCaseWriter::class.java) .asEagerSingleton() } }
core/src/test/kotlin/org/evomaster/core/search/algorithms/onemax/ManipulatedOneMaxModule.kt
1587859772
package com.soywiz.dynarek2 import kotlin.reflect.* inline operator fun KFunction<Int>.invoke(vararg args: D2Expr<*>): D2ExprI = D2Expr.Invoke(D2INT, this, *args) val Int.lit get() = D2Expr.ILit(this) operator fun D2ExprI.unaryMinus() = UNOP(this, D2UnOp.NEG) fun BINOP(l: D2ExprI, op: D2IBinOp, r: D2ExprI) = D2Expr.IBinOp(l, op, r) fun COMPOP(l: D2ExprI, op: D2CompOp, r: D2ExprI) = D2Expr.IComOp(l, op, r) fun UNOP(l: D2ExprI, op: D2UnOp) = D2Expr.IUnop(l, op) operator fun D2ExprI.plus(other: D2ExprI) = BINOP(this, D2IBinOp.ADD, other) operator fun D2ExprI.minus(other: D2ExprI) = BINOP(this, D2IBinOp.SUB, other) operator fun D2ExprI.times(other: D2ExprI) = BINOP(this, D2IBinOp.MUL, other) operator fun D2ExprI.div(other: D2ExprI) = BINOP(this, D2IBinOp.DIV, other) operator fun D2ExprI.rem(other: D2ExprI) = BINOP(this, D2IBinOp.REM, other) infix fun D2ExprI.SHL(other: D2ExprI) = BINOP(this, D2IBinOp.SHL, other) infix fun D2ExprI.SHR(other: D2ExprI) = BINOP(this, D2IBinOp.SHR, other) infix fun D2ExprI.USHR(other: D2ExprI) = BINOP(this, D2IBinOp.USHR, other) infix fun D2ExprI.AND(other: D2ExprI) = BINOP(this, D2IBinOp.AND, other) infix fun D2ExprI.OR(other: D2ExprI) = BINOP(this, D2IBinOp.OR, other) infix fun D2ExprI.XOR(other: D2ExprI) = BINOP(this, D2IBinOp.XOR, other) infix fun D2ExprI.EQ(other: D2ExprI) = COMPOP(this, D2CompOp.EQ, other) infix fun D2ExprI.NE(other: D2ExprI) = COMPOP(this, D2CompOp.NE, other) infix fun D2ExprI.LT(other: D2ExprI) = COMPOP(this, D2CompOp.LT, other) infix fun D2ExprI.LE(other: D2ExprI) = COMPOP(this, D2CompOp.LE, other) infix fun D2ExprI.GT(other: D2ExprI) = COMPOP(this, D2CompOp.GT, other) infix fun D2ExprI.GE(other: D2ExprI) = COMPOP(this, D2CompOp.GE, other) private fun Int.mask(): Int = (1 shl this) - 1 fun D2ExprI.EXTRACT(offset: Int, size: Int): D2ExprI = (this SHR offset.lit) AND size.mask().lit fun D2ExprI.INSERT(offset: Int, size: Int, value: D2ExprI): D2ExprI = (this AND (size.mask() shl offset).lit) OR ((value AND size.mask().lit) SHL offset.lit) fun INV(v: D2ExprI) = v XOR (-1).lit
src/commonMain/kotlin/com/soywiz/dynarek2/D2I.kt
1881632395
package com.taylorsloan.jobseer.dagger.component import com.taylorsloan.jobseer.dagger.module.StorageModule import com.taylorsloan.jobseer.dagger.scope.DataScope import com.taylorsloan.jobseer.data.job.repo.JobRepositoryImpl import com.taylorsloan.jobseer.data.job.repo.sources.DataSourceFactory import com.taylorsloan.jobseer.data.job.repo.sources.LocalDataSource import dagger.Component /** * Created by taylorsloan on 10/28/17. */ @Component(modules = arrayOf(StorageModule::class), dependencies = arrayOf(AppComponent::class)) @DataScope interface StorageComponent { fun inject(localDataSource: LocalDataSource) fun inject(dataSourceFactory: DataSourceFactory) fun inject(jobRepositoryImpl: JobRepositoryImpl) }
app/src/main/java/com/taylorsloan/jobseer/dagger/component/StorageComponent.kt
1844136938
// Licensed under the MIT license. See LICENSE file in the project root // for full license information. package net.dummydigit.qbranch.compiler import java.nio.file.Paths import java.io.* import java.nio.file.Path class SourceCodeFileLoader(settings: Settings) : SourceCodeLoader { private val includePaths = settings.includePaths.map { Paths.get(it).toAbsolutePath() } override fun openStream(sourceName : String) : InputStream { return FileInputStream(resolvePathInternal(sourceName).toFile()) } override fun resolvePath(sourceName: String): String { return this.resolvePathInternal(sourceName).toString() } private fun resolvePathInternal(sourceName: String) : Path { val inputFile = Paths.get(sourceName) return when { inputFile.isAbsolute -> inputFile includePaths.isEmpty() -> inputFile.toRealPath() else -> { for (eachPath in includePaths) { try { return eachPath.resolve(sourceName).toRealPath() } catch (e : IOException) { // Try next include path on failure. } } // If all visited but still didn't resolve a path, // then it's an error. throw FileNotFoundException(sourceName) } } } }
compiler/src/main/kotlin/net/dummydigit/qbranch/compiler/SourceCodeFileLoader.kt
343149112
package com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont import com.intellij.psi.tree.IElementType import org.jetbrains.annotations.NonNls /* * 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. */ class BitmapFontElementType(@NonNls debugName: String) : IElementType(debugName, BitmapFontLanguage.INSTANCE)
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/bitmapFont/BitmapFontElementType.kt
3743498600
package com.xwray.groupie.example import com.xwray.groupie.Group import com.xwray.groupie.GroupDataObserver import com.xwray.groupie.Item import java.util.* /** * A simple, non-editable, non-nested group of Items which displays a list as vertical columns. */ class ColumnGroup(items: List<Item<*>>) : Group { private val items = ArrayList<Item<*>>() init { for (i in items.indices) { // Rearrange items so that the adapter appears to arrange them in vertical columns var index: Int if (i % 2 == 0) { index = i / 2 } else { index = (i - 1) / 2 + (items.size / 2f).toInt() // If columns are uneven, we'll put an extra one at the end of the first column, // meaning the second column's indices will all be increased by 1 if (items.size % 2 == 1) index++ } val trackItem = items[index] this.items.add(trackItem) } } override fun registerGroupDataObserver(groupDataObserver: GroupDataObserver) { // no need to do anything here } override fun unregisterGroupDataObserver(groupDataObserver: GroupDataObserver) { // no need to do anything here } override fun getItem(position: Int): Item<*> { return items[position] } override fun getPosition(item: Item<*>): Int { return items.indexOf(item) } override fun getItemCount(): Int { return items.size } }
example/src/main/java/com/xwray/groupie/example/ColumnGroup.kt
1262147478
package com.st.BlueSTSDK.Features.ExtConfiguration import com.google.gson.JsonElement import com.google.gson.annotations.SerializedName //Data class for the Configuration Command data class ExtConfigCommands ( @SerializedName("command") val command: String, @SerializedName("argString") val argString: String?=null, @SerializedName("argNumber") val argNumber: Int?=null, @SerializedName("argJsonElement") val argJsonElement: JsonElement?=null )
BlueSTSDK/src/main/java/com/st/BlueSTSDK/Features/ExtConfiguration/ExtConfigCommands.kt
982288671
package me.proxer.library.enums import com.serjltt.moshi.adapters.FallbackEnum import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import me.proxer.library.entity.info.Entry /** * Enum holding the available languages of an [Entry]. * * @author Ruben Gees */ @JsonClass(generateAdapter = false) @FallbackEnum(name = "OTHER") enum class MediaLanguage { @Json(name = "de") GERMAN, @Json(name = "en") ENGLISH, @Json(name = "gersub") GERMAN_SUB, @Json(name = "gerdub") GERMAN_DUB, @Json(name = "engsub") ENGLISH_SUB, @Json(name = "engdub") ENGLISH_DUB, @Json(name = "misc") OTHER }
library/src/main/kotlin/me/proxer/library/enums/MediaLanguage.kt
2630286200
package com.github.czyzby.setup.data.langs import com.github.czyzby.setup.data.files.SourceDirectory import com.github.czyzby.setup.data.files.path import com.github.czyzby.setup.data.platforms.Android import com.github.czyzby.setup.data.platforms.AndroidGradleFile import com.github.czyzby.setup.data.project.Project import com.github.czyzby.setup.views.JvmLanguage /** * Adds Kotlin support to the project. * @author MJ */ @JvmLanguage class Kotlin : Language { override val id = "kotlin" override val version = "1.4.+" override fun initiate(project: Project) { project.rootGradle.buildDependencies.add("\"org.jetbrains.kotlin:kotlin-gradle-plugin:\$kotlinVersion\"") project.rootGradle.plugins.add(id) project.platforms.values.forEach { project.files.add(SourceDirectory(it.id, path("src", "main", "kotlin"))) } if (project.hasPlatform(Android.ID)) { val gradleFile = project.getGradleFile(Android.ID) as AndroidGradleFile gradleFile.insertLatePlugin() gradleFile.srcFolders.add("'src/main/kotlin'") } addDependency(project, "org.jetbrains.kotlin:kotlin-stdlib:\$kotlinVersion") } }
src/main/kotlin/com/github/czyzby/setup/data/langs/kotlin.kt
973222191
package com.example.myproduct.admin.state object ConfigurationState { val rangeSetting = VersionRangeSetting() }
subprojects/docs/src/samples/templates/structuring-software-projects/state/application-state/src/main/kotlin/com/example/myproduct/admin/state/ConfigurationState.kt
1929994242
package com.texasgamer.zephyr.util import com.texasgamer.zephyr.BuildConfig /** * BuildConfig utilities. */ object BuildConfigUtils { @JvmStatic val versionCode: Int get() = BuildConfig.VERSION_CODE val versionName: String get() = BuildConfig.VERSION_NAME @JvmStatic val packageName: String get() = BuildConfig.APPLICATION_ID val flavor: String get() = BuildConfig.FLAVOR val buildType: String get() = BuildConfig.BUILD_TYPE val isDebug: Boolean get() = BuildConfig.DEBUG }
android/app/src/main/java/com/texasgamer/zephyr/util/BuildConfigUtils.kt
4051840420
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.api import com.google.android.libraries.pcc.chronicle.api.error.ChronicleError import com.google.android.libraries.pcc.chronicle.api.policy.Policy import kotlin.reflect.KClass /** Chronicle is the primary entry point for features when accessing or manipulating data. */ interface Chronicle { /** * Checks policy adherence of the [ConnectionRequest.requester] and the data being requested. * @param isForReading true if the policy will be used in conjunction with a [ReadConnection] */ fun checkPolicy( dataTypeName: String, policy: Policy?, isForReading: Boolean, requester: ProcessorNode ): Result<Unit> /** * Returns the [ConnectionTypes] associated with the provided [dataTypeClass] which are available * via [getConnection]. */ fun getAvailableConnectionTypes(dataTypeClass: KClass<*>): ConnectionTypes /** * Returns the [ConnectionTypes] associated with the provided [dataTypeClass] which are available * via [getConnection]. */ fun getAvailableConnectionTypes(dataTypeClass: Class<*>): ConnectionTypes = getAvailableConnectionTypes(dataTypeClass.kotlin) /** * Returns a [Connection] of type [T] after checking policy adherence of the * [ConnectionRequest.requester] and the data being requested. */ fun <T : Connection> getConnection(request: ConnectionRequest<T>): ConnectionResult<T> /** * A convenience method which calls [getConnection], returning `null` for * [ConnectionResult.Failure] results. An optional [onError] parameter will be called with the * failure result. */ fun <T : Connection> getConnectionOrNull( request: ConnectionRequest<T>, onError: (ChronicleError) -> Unit = {} ): T? { return when (val result = getConnection(request)) { is ConnectionResult.Success<T> -> result.connection is ConnectionResult.Failure<T> -> { onError(result.error) null } } } /** * A convenience method which calls [getConnection], returning `null` for * [ConnectionResult.Failure] results. If a failure occurs, there will be no information provided * about the failure. */ fun <T : Connection> getConnectionOrNull( request: ConnectionRequest<T>, ): T? = getConnectionOrNull(request) {} /** * A convenience method which calls [getConnection], and throws [ChronicleError] for * [ConnectionResult.Failure] results. */ fun <T : Connection> getConnectionOrThrow(request: ConnectionRequest<T>): T { return when (val result = getConnection(request)) { is ConnectionResult.Success<T> -> result.connection is ConnectionResult.Failure<T> -> throw (result.error) } } data class ConnectionTypes( val readConnections: Set<Class<out ReadConnection>>, val writeConnections: Set<Class<out WriteConnection>> ) { companion object { val EMPTY = ConnectionTypes(emptySet(), emptySet()) } } } /** Result container for [Connection] attempts. */ sealed class ConnectionResult<T : Connection> { class Success<T : Connection>(val connection: T) : ConnectionResult<T>() class Failure<T : Connection>(val error: ChronicleError) : ConnectionResult<T>() } /** * A convenience method that will create a [ConnectionRequest] using the class provided as a type * parameter to the call, the provided processor, and provided policy. */ inline fun <reified T : Connection> Chronicle.getConnection( requester: ProcessorNode, policy: Policy? = null ) = getConnection(ConnectionRequest(T::class.java, requester, policy)) /** * A convenience method that will create a [ConnectionRequest] using the class provided as a type * parameter to the call, the provided processor, and provided policy. * * An optional [onError] callback will be called with the [ChronicleError] containing the failure * reason if the connection fails. */ inline fun <reified T : Connection> Chronicle.getConnectionOrNull( requester: ProcessorNode, policy: Policy? = null, noinline onError: (ChronicleError) -> Unit = {} ) = getConnectionOrNull(ConnectionRequest(T::class.java, requester, policy), onError) /** * A convenience method that will create a [ConnectionRequest] using the class provided as a type * parameter to the call, the provided processor, and provided policy. */ inline fun <reified T : Connection> Chronicle.getConnectionOrThrow( requester: ProcessorNode, policy: Policy? = null ) = getConnectionOrThrow(ConnectionRequest(T::class.java, requester, policy))
java/com/google/android/libraries/pcc/chronicle/api/Chronicle.kt
1509710174
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * 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. */ @file:Suppress("UNUSED") package jp.nephy.penicillin.endpoints import jp.nephy.penicillin.core.session.ApiClient import jp.nephy.penicillin.core.session.ApiClientDsl /** * Returns [AccountActivity] endpoint instance. * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/overview) * * @return New [AccountActivity] endpoint instance. * @receiver Current [ApiClient] instance. */ @ApiClientDsl val ApiClient.accountActivity: AccountActivity get() = AccountActivity(this) /** * Collection of api endpoints related to Account Activity API. * * @constructor Creates new [AccountActivity] endpoint instance. * @param client Current [ApiClient] instance. * @see ApiClient.accountActivity */ class AccountActivity(override val client: ApiClient): Endpoint
src/main/kotlin/jp/nephy/penicillin/endpoints/AccountActivity.kt
3157881691