content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package se.barsk.park.analytics /** * Event sent whenever handling dynamic links failed */ class DynamicLinkFailedEvent(exception: String) : AnalyticsEvent() { override val name: String = "dynamic_link_failed" init { parameters.putString(Param.EXCEPTION, exception.substring(0, minOf(100, exception.length))) } }
app/src/main/java/se/barsk/park/analytics/DynamicLinkFailedEvent.kt
3921864606
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.openapi.components.SettingsSavingComponent import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.util.SmartList import com.intellij.util.containers.ContainerUtil import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import java.util.concurrent.atomic.AtomicBoolean // A way to remove obsolete component data. internal val OBSOLETE_STORAGE_EP = ExtensionPointName<ObsoleteStorageBean>("com.intellij.obsoleteStorage") abstract class ComponentStoreWithExtraComponents : ComponentStoreImpl() { @Suppress("DEPRECATION") private val settingsSavingComponents = ContainerUtil.createLockFreeCopyOnWriteList<SettingsSavingComponent>() private val asyncSettingsSavingComponents = ContainerUtil.createLockFreeCopyOnWriteList<com.intellij.configurationStore.SettingsSavingComponent>() // todo do we really need this? private val isSaveSettingsInProgress = AtomicBoolean() override suspend fun save(forceSavingAllSettings: Boolean) { if (!isSaveSettingsInProgress.compareAndSet(false, true)) { LOG.warn("save call is ignored because another save in progress", Throwable()) return } try { super.save(forceSavingAllSettings) } finally { isSaveSettingsInProgress.set(false) } } override fun initComponent(component: Any, isService: Boolean) { @Suppress("DEPRECATION") if (component is com.intellij.configurationStore.SettingsSavingComponent) { asyncSettingsSavingComponents.add(component) } else if (component is SettingsSavingComponent) { settingsSavingComponents.add(component) } super.initComponent(component, isService) } internal suspend fun saveSettingsSavingComponentsAndCommitComponents(result: SaveResult, forceSavingAllSettings: Boolean): SaveSessionProducerManager { coroutineScope { // expects EDT launch(storeEdtCoroutineContext) { @Suppress("Duplicates") val errors = SmartList<Throwable>() for (settingsSavingComponent in settingsSavingComponents) { runAndCollectException(errors) { settingsSavingComponent.save() } } result.addErrors(errors) } launch { val errors = SmartList<Throwable>() for (settingsSavingComponent in asyncSettingsSavingComponents) { runAndCollectException(errors) { settingsSavingComponent.save() } } result.addErrors(errors) } } // SchemeManager (old settingsSavingComponent) must be saved before saving components (component state uses scheme manager in an ipr project, so, we must save it before) // so, call sequentially it, not inside coroutineScope return createSaveSessionManagerAndSaveComponents(result, forceSavingAllSettings) } override fun commitComponents(isForce: Boolean, session: SaveSessionProducerManager, errors: MutableList<Throwable>) { // ensure that this task will not interrupt regular saving LOG.runAndLogException { commitObsoleteComponents(session, false) } super.commitComponents(isForce, session, errors) } internal open fun commitObsoleteComponents(session: SaveSessionProducerManager, isProjectLevel: Boolean) { for (bean in OBSOLETE_STORAGE_EP.extensionList) { if (bean.isProjectLevel != isProjectLevel) { continue } val storage = (storageManager as StateStorageManagerImpl).getOrCreateStorage(bean.file ?: continue) for (componentName in bean.components) { session.getProducer(storage)?.setState(null, componentName, null) } } } } private inline fun <T> runAndCollectException(errors: MutableList<Throwable>, runnable: () -> T): T? { try { return runnable() } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { errors.add(e) return null } }
platform/configuration-store-impl/src/ComponentStoreWithExtraComponents.kt
4188867340
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.actions import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.mcp.McpModuleType import com.demonwav.mcdev.platform.mcp.srg.SrgManager import com.demonwav.mcdev.platform.mixin.util.findFirstShadowTarget import com.demonwav.mcdev.util.ActionData import com.demonwav.mcdev.util.getDataFromActionEvent import com.demonwav.mcdev.util.gotoTargetElement import com.demonwav.mcdev.util.invokeLater import com.demonwav.mcdev.util.qualifiedMemberReference import com.demonwav.mcdev.util.simpleQualifiedMemberReference import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.wm.WindowManager import com.intellij.psi.PsiField import com.intellij.psi.PsiIdentifier import com.intellij.psi.PsiManager import com.intellij.psi.PsiMember import com.intellij.psi.PsiMethod import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.UsageSearchContext import com.intellij.ui.LightColors import com.intellij.ui.awt.RelativePoint class GotoAtEntryAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val data = getDataFromActionEvent(e) ?: return showBalloon(e) if (data.element !is PsiIdentifier) { showBalloon(e) return } val srgManager = data.instance.getModuleOfType(McpModuleType)?.srgManager // Not all ATs are in MCP modules, fallback to this if possible // TODO try to find SRG references for all modules if current module isn't found? ?: SrgManager.findAnyInstance(data.project) ?: return showBalloon(e) srgManager.srgMap.onSuccess { srgMap -> var parent = data.element.parent if (parent is PsiMember) { val shadowTarget = parent.findFirstShadowTarget()?.element if (shadowTarget != null) { parent = shadowTarget } } when (parent) { is PsiField -> { val reference = srgMap.getSrgField(parent) ?: parent.simpleQualifiedMemberReference ?: return@onSuccess showBalloon(e) searchForText(e, data, reference.name) } is PsiMethod -> { val reference = srgMap.getSrgMethod(parent) ?: parent.qualifiedMemberReference ?: return@onSuccess showBalloon( e ) searchForText(e, data, reference.name + reference.descriptor) } else -> showBalloon(e) } } } private fun searchForText(e: AnActionEvent, data: ActionData, text: String) { val manager = ModuleManager.getInstance(data.project) manager.modules.asSequence() .mapNotNull { MinecraftFacet.getInstance(it, McpModuleType) } .flatMap { it.accessTransformers.asSequence() } .forEach { virtualFile -> val file = PsiManager.getInstance(data.project).findFile(virtualFile) ?: return@forEach var found = false PsiSearchHelper.getInstance(data.project) .processElementsWithWord( { element, _ -> gotoTargetElement(element, data.editor, data.file) found = true false }, LocalSearchScope(file), text, UsageSearchContext.ANY, true ) if (found) { return } } showBalloon(e) } private fun showBalloon(e: AnActionEvent) { val balloon = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder("No access transformer entry found", null, LightColors.YELLOW, null) .setHideOnAction(true) .setHideOnClickOutside(true) .setHideOnKeyOutside(true) .createBalloon() val project = e.project ?: return val statusBar = WindowManager.getInstance().getStatusBar(project) invokeLater { balloon.show(RelativePoint.getCenterOf(statusBar.component), Balloon.Position.atRight) } } }
src/main/kotlin/com/demonwav/mcdev/platform/mcp/actions/GotoAtEntryAction.kt
56855536
package redblacktree import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test internal class RBNodeTest { var node: RBNode<Int, Int>? = null var nodeCheck: RBNode<Int, Int>? = null val RBTree = RedBlackTree<Int, Int>() fun checkStructure(rootFirst: RBNode<Int, Int>?, rootSecond: RBNode<Int, Int>?): Boolean { if (rootFirst == null) return rootFirst == rootSecond if (rootFirst.key != rootSecond?.key || rootFirst.colorBlack != rootSecond.colorBlack) return false else return checkStructure(rootFirst.left, rootSecond.left) && checkStructure(rootFirst.right, rootSecond.right) } @Test fun rotateLeftOne() { node = RBNode(1, 1, null) nodeCheck = RBNode(1, 1, null) node?.rotateLeft() assertNotNull(node) assertTrue(checkStructure(node, nodeCheck)) } @Test fun rotateRightOne() { node = RBNode(1, 1, null) nodeCheck = RBNode(1, 1, null) node?.rotateRight() assertNotNull(node) assertTrue(checkStructure(node, nodeCheck)) } @Test fun rotateLeftLeaf() { node = RBNode(1, 1, null) node!!.colorBlack = true node!!.left = RBNode(-1, 1, node) nodeCheck = RBNode(1, 1, null) nodeCheck!!.colorBlack = true nodeCheck!!.left = RBNode(-1, 1, nodeCheck) node!!.left!!.rotateLeft() assertTrue(checkStructure(node, nodeCheck)) } @Test fun rotateRightLeaf() { node = RBNode(1, 1, null) node!!.colorBlack = true node!!.left = RBNode(-1, 1, node) nodeCheck = RBNode(1, 1, null) nodeCheck!!.colorBlack = true nodeCheck!!.left = RBNode(-1, 1, nodeCheck) node!!.left!!.rotateRight() assertTrue(checkStructure(node, nodeCheck)) } @Test fun RotateLeftNormal() { for (i in 1..100) RBTree.insert(i, i) node = RBTree.root!!.right RBTree.root!!.rotateLeft() assertEquals(RBTree.root!!.parent, node) assertEquals(RBTree.root, node?.left) } @Test fun RotateRightNormal() { for (i in 1..100) RBTree.insert(i, i) node = RBTree.root!!.left RBTree.root!!.rotateRight() assertEquals(RBTree.root!!.parent, node) assertEquals(RBTree.root, node?.right) } }
tests/redblacktree/RBNodeTest.kt
1611362717
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.plugins import com.intellij.ide.feedback.kotlinRejecters.state.KotlinRejectersInfoService import com.intellij.ide.plugins.marketplace.statistics.PluginManagerUsageCollector import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.project.Project import org.jetbrains.annotations.ApiStatus import javax.swing.JComponent @ApiStatus.Internal internal class DynamicPluginEnabler : PluginEnabler { override fun isDisabled(pluginId: PluginId): Boolean = PluginEnabler.HEADLESS.isDisabled(pluginId) override fun enable(descriptors: Collection<IdeaPluginDescriptor>): Boolean = enable(descriptors, project = null) fun enable( descriptors: Collection<IdeaPluginDescriptor>, project: Project? = null, ): Boolean { PluginManagerUsageCollector.pluginsStateChanged(descriptors, enable = true, project) PluginEnabler.HEADLESS.enable(descriptors) return DynamicPlugins.loadPlugins(descriptors) } override fun disable(descriptors: Collection<IdeaPluginDescriptor>): Boolean = disable(descriptors, project = null) fun disable( descriptors: Collection<IdeaPluginDescriptor>, project: Project? = null, parentComponent: JComponent? = null, ): Boolean { PluginManagerUsageCollector.pluginsStateChanged(descriptors, enable = false, project) recordKotlinPluginDisabling(descriptors) PluginEnabler.HEADLESS.disable(descriptors) return DynamicPlugins.unloadPlugins(descriptors, project, parentComponent) } private fun recordKotlinPluginDisabling(descriptors: Collection<IdeaPluginDescriptor>) { // Kotlin Plugin + 4 plugin dependency if (descriptors.size <= 5 && descriptors.any { it.pluginId.idString == "org.jetbrains.kotlin" }) { KotlinRejectersInfoService.getInstance().state.showNotificationAfterRestart = true } } }
platform/platform-impl/src/com/intellij/ide/plugins/DynamicPluginEnabler.kt
1065029119
package org.jetbrains.completion.full.line.local.suggest.collector import org.jetbrains.completion.full.line.local.ModelsFiles import org.jetbrains.completion.full.line.local.generation.model.GPT2ModelWrapper import org.jetbrains.completion.full.line.local.tokenizer.FullLineTokenizer import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource import org.mockito.Mockito class IncompleteContextTest { @Test fun `incomplete context - single token parts`() { for (entry in tokenizer.vocab) { if (!specialTokenIds.contains(entry.value) && (entry.key.length < mockedCompletionsGenerator.tokenLengthThreshold)) { val (context, _) = mockedCompletionsGenerator.resolveIncompleteContext( entry.key.substring(0, entry.key.length - 1) ) Assertions.assertEquals("", context, "Wrong on token ${entry.value}: >>>${entry.key}<<<") } } } @ParameterizedTest @CsvSource("cur_node = TrieNo,cur_node = Trie", "value_sou,value_", "df.app,df.", "adfasb.app,adfasb") fun `incomplete context - markers`(context: String, expected: String) { val (prepContext, _) = mockedCompletionsGenerator.resolveIncompleteContext(context) Assertions.assertEquals(expected, prepContext) } companion object { private val tokenizer = FullLineTokenizer(ModelsFiles.gpt2_py_4L_512_83_q_local.tokenizer, nThreads = 2) private val mockModel = Mockito.mock(GPT2ModelWrapper::class.java) private val mockedCompletionsGenerator: FullLineCompletionsGenerator private val specialTokenIds = setOf(0, 1, 2, 3) init { Mockito.`when`(mockModel.maxSeqLen).thenReturn(384) mockedCompletionsGenerator = FullLineCompletionsGenerator(mockModel, tokenizer) } } }
plugins/full-line/local/test/org/jetbrains/completion/full/line/local/suggest/collector/IncompleteContextTest.kt
3994741165
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.io.File import java.io.FileDescriptor import java.io.FileInputStream import java.io.IOException import okhttp3.internal.chooseCharset import okhttp3.internal.commonContentLength import okhttp3.internal.commonIsDuplex import okhttp3.internal.commonIsOneShot import okhttp3.internal.commonToRequestBody import okio.BufferedSink import okio.ByteString import okio.FileSystem import okio.GzipSink import okio.Path import okio.buffer import okio.source actual abstract class RequestBody { actual abstract fun contentType(): MediaType? @Throws(IOException::class) actual open fun contentLength(): Long = commonContentLength() @Throws(IOException::class) actual abstract fun writeTo(sink: BufferedSink) actual open fun isDuplex(): Boolean = commonIsDuplex() actual open fun isOneShot(): Boolean = commonIsOneShot() actual companion object { /** * Returns a new request body that transmits this string. If [contentType] is non-null and lacks * a charset, this will use UTF-8. */ @JvmStatic @JvmName("create") actual fun String.toRequestBody(contentType: MediaType?): RequestBody { val (charset, finalContentType) = contentType.chooseCharset() val bytes = toByteArray(charset) return bytes.toRequestBody(finalContentType, 0, bytes.size) } @JvmStatic @JvmName("create") actual fun ByteString.toRequestBody(contentType: MediaType?): RequestBody = commonToRequestBody(contentType) /** Returns a new request body that transmits this. */ @JvmStatic @JvmName("create") fun FileDescriptor.toRequestBody(contentType: MediaType? = null): RequestBody { return object : RequestBody() { override fun contentType() = contentType override fun isOneShot(): Boolean = true override fun writeTo(sink: BufferedSink) { FileInputStream(this@toRequestBody).use { sink.buffer.writeAll(it.source()) } } } } @JvmOverloads @JvmStatic @JvmName("create") actual fun ByteArray.toRequestBody( contentType: MediaType?, offset: Int, byteCount: Int ): RequestBody = commonToRequestBody(contentType, offset, byteCount) /** Returns a new request body that transmits the content of this. */ @JvmStatic @JvmName("create") fun File.asRequestBody(contentType: MediaType? = null): RequestBody { return object : RequestBody() { override fun contentType() = contentType override fun contentLength() = length() override fun writeTo(sink: BufferedSink) { source().use { source -> sink.writeAll(source) } } } } /** Returns a new request body that transmits the content of this. */ @JvmStatic @JvmName("create") fun Path.asRequestBody(fileSystem: FileSystem, contentType: MediaType? = null): RequestBody { return object : RequestBody() { override fun contentType() = contentType override fun contentLength() = fileSystem.metadata(this@asRequestBody).size ?: -1 override fun writeTo(sink: BufferedSink) { fileSystem.source(this@asRequestBody).use { source -> sink.writeAll(source) } } } } @JvmStatic @Deprecated( message = "Moved to extension function. Put the 'content' argument first to fix Java", replaceWith = ReplaceWith( expression = "content.toRequestBody(contentType)", imports = ["okhttp3.RequestBody.Companion.toRequestBody"] ), level = DeprecationLevel.WARNING) fun create(contentType: MediaType?, content: String): RequestBody = content.toRequestBody(contentType) @JvmStatic @Deprecated( message = "Moved to extension function. Put the 'content' argument first to fix Java", replaceWith = ReplaceWith( expression = "content.toRequestBody(contentType)", imports = ["okhttp3.RequestBody.Companion.toRequestBody"] ), level = DeprecationLevel.WARNING) fun create( contentType: MediaType?, content: ByteString ): RequestBody = content.toRequestBody(contentType) @JvmOverloads @JvmStatic @Deprecated( message = "Moved to extension function. Put the 'content' argument first to fix Java", replaceWith = ReplaceWith( expression = "content.toRequestBody(contentType, offset, byteCount)", imports = ["okhttp3.RequestBody.Companion.toRequestBody"] ), level = DeprecationLevel.WARNING) fun create( contentType: MediaType?, content: ByteArray, offset: Int = 0, byteCount: Int = content.size ): RequestBody = content.toRequestBody(contentType, offset, byteCount) @JvmStatic @Deprecated( message = "Moved to extension function. Put the 'file' argument first to fix Java", replaceWith = ReplaceWith( expression = "file.asRequestBody(contentType)", imports = ["okhttp3.RequestBody.Companion.asRequestBody"] ), level = DeprecationLevel.WARNING) fun create(contentType: MediaType?, file: File): RequestBody= file.asRequestBody(contentType) /** * Returns a gzip version of the RequestBody, with compressed payload. * This is not automatic as not all servers support gzip compressed requests. * * ``` * val request = Request.Builder().url("...") * .addHeader("Content-Encoding", "gzip") * .post(uncompressedBody.gzip()) * .build() * ``` */ @JvmStatic fun RequestBody.gzip(): RequestBody { return object : RequestBody() { override fun contentType(): MediaType? { return [email protected]() } override fun contentLength(): Long { return -1 // We don't know the compressed length in advance! } @Throws(IOException::class) override fun writeTo(sink: BufferedSink) { val gzipSink = GzipSink(sink).buffer() [email protected](gzipSink) gzipSink.close() } override fun isOneShot(): Boolean { return [email protected]() } } } } }
okhttp/src/jvmMain/kotlin/okhttp3/RequestBody.kt
2866901400
package com.kronos.plugin.base import com.android.build.api.transform.TransformInvocation /** * * @Author LiABao * @Since 2021/6/30 * */ class TransformBuilder(val callBack: TransformCallBack) { var transformInvocation: TransformInvocation? = null var single: Boolean = false var filter: ClassNameFilter? = null var simpleScan = false var deleteCallBack: DeleteCallBack? = null fun build(): BaseTransform { val transform = BaseTransform(transformInvocation, callBack, single) transform.also { it.filter = filter } if (simpleScan) { transform.openSimpleScan() } deleteCallBack?.apply { transform.setDeleteCallBack(this) } return transform } }
Plugin/BasePlugin/src/main/java/com/kronos/plugin/base/TransformBuilder.kt
2968144792
package net.muliba.fancyfilepickerlibrary import android.app.Activity import android.content.Intent import android.os.Bundle import com.wugang.activityresult.library.ActivityResult import net.muliba.fancyfilepickerlibrary.ui.FileActivity import net.muliba.fancyfilepickerlibrary.util.Utils /** * Created by fancy on 2017/4/12. */ class FilePicker { companion object { @JvmStatic val FANCY_FILE_PICKER_ARRAY_LIST_RESULT_KEY @JvmName("FANCY_FILE_PICKER_ARRAY_LIST_RESULT_KEY")get() = "fancy_file_picker_array_result" @JvmStatic val FANCY_FILE_PICKER_SINGLE_RESULT_KEY @JvmName("FANCY_FILE_PICKER_SINGLE_RESULT_KEY")get() = "fancy_file_picker_single_result" @JvmStatic val FANCY_REQUEST_CODE @JvmName("FANCY_REQUEST_CODE")get() = 1024 //选择类型 @JvmStatic val CHOOSE_TYPE_MULTIPLE @JvmName("CHOOSE_TYPE_MULTIPLE")get() = 0 @JvmStatic val CHOOSE_TYPE_SINGLE @JvmName("CHOOSE_TYPE_SINGLE")get() = 1 } private var requestCode: Int = FANCY_REQUEST_CODE private var activity: Activity? = null private var chooseType = CHOOSE_TYPE_MULTIPLE //默认多选 private var existingResults = ArrayList<String>() fun withActivity(activity: Activity) : FilePicker { this.activity = activity return this } /** * 设置选择类型 * @param type One of {@link #CHOOSE_TYPE_MULTIPLE}, {@link #CHOOSE_TYPE_SINGLE}. */ fun chooseType(type: Int = CHOOSE_TYPE_MULTIPLE): FilePicker { if (type != CHOOSE_TYPE_SINGLE && type!= CHOOSE_TYPE_MULTIPLE) { throw IllegalArgumentException("chooseType value is illegal , must be one of #FilePicker.CHOOSE_TYPE_MULTIPLE or #FilePicker.CHOOSE_TYPE_SINGLE ") } chooseType = type return this } /** * 定义requestCode * @param requestCode */ @Deprecated(message = "4.0.0开始不再使用,用forResult直接返回结果,不需要onActivityResult接收结果") fun requestCode(requestCode: Int): FilePicker { this.requestCode = requestCode return this } fun existingResults(results:ArrayList<String>): FilePicker { this.existingResults.clear() if (results.isNotEmpty()) { this.existingResults.addAll(results) } return this } /** * 启动选择器 */ @Deprecated(message = "4.0.0开始不再使用,用forResult直接返回结果,不需要onActivityResult接收结果") fun start() { if (activity==null) { throw RuntimeException("not found Activity, Please execute the function 'withActivity' ") } startFilePicker() } /** * 4.0.0 新增 * 返回选择的结果 如果是单选 result[0]获取 * 不再需要到onActivityResult中去接收结果 */ fun forResult(listener: (filePaths: List<String>) -> Unit) { if (activity==null) { throw RuntimeException("not found Activity, Please execute the function 'withActivity' ") } val bundle = Bundle() bundle.putInt(Utils.CHOOSE_TYPE_KEY, chooseType) bundle.putStringArrayList(Utils.MULIT_CHOOSE_BACK_RESULTS_KEY, existingResults) ActivityResult.of(activity!!) .className(FileActivity::class.java) .params(bundle) .greenChannel() .forResult { resultCode, data -> val result = ArrayList<String>() if (resultCode == Activity.RESULT_OK) { if (chooseType == CHOOSE_TYPE_SINGLE) { val filePath = data?.getStringExtra(FANCY_FILE_PICKER_SINGLE_RESULT_KEY) ?: "" if (filePath.isNotEmpty()) { result.add(filePath) } }else { val array = data?.getStringArrayListExtra(FANCY_FILE_PICKER_ARRAY_LIST_RESULT_KEY) if (array !=null && array.isNotEmpty()) { result.addAll(array) } } } listener(result) } } private fun startFilePicker() { val intent = Intent(activity, FileActivity::class.java) intent.putExtra(Utils.CHOOSE_TYPE_KEY, chooseType) intent.putExtra(Utils.MULIT_CHOOSE_BACK_RESULTS_KEY, existingResults) activity?.startActivityForResult(intent, requestCode) } }
fancyfilepickerlibrary/src/main/java/net/muliba/fancyfilepickerlibrary/FilePicker.kt
2773424908
package io.github.chrislo27.rhre3.screen import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.utils.Align import io.github.chrislo27.rhre3.PreferenceKeys import io.github.chrislo27.rhre3.RHRE3 import io.github.chrislo27.rhre3.RHRE3Application import io.github.chrislo27.rhre3.RemixRecovery import io.github.chrislo27.rhre3.editor.Editor import io.github.chrislo27.rhre3.sfxdb.GameMetadata import io.github.chrislo27.rhre3.stage.GenericStage import io.github.chrislo27.rhre3.stage.LoadingIcon import io.github.chrislo27.rhre3.track.Remix import io.github.chrislo27.rhre3.util.* import io.github.chrislo27.toolboks.ToolboksScreen import io.github.chrislo27.toolboks.i18n.Localization import io.github.chrislo27.toolboks.registry.AssetRegistry import io.github.chrislo27.toolboks.registry.ScreenRegistry import io.github.chrislo27.toolboks.ui.ImageLabel import io.github.chrislo27.toolboks.ui.TextLabel import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch class SaveRemixScreen(main: RHRE3Application) : ToolboksScreen<RHRE3Application, SaveRemixScreen>(main) { private val editorScreen: EditorScreen by lazy { ScreenRegistry.getNonNullAsType<EditorScreen>("editor") } private val editor: Editor get() = editorScreen.editor override val stage: GenericStage<SaveRemixScreen> = GenericStage(main.uiPalette, null, main.defaultCamera) @Volatile private var isChooserOpen = false set(value) { field = value stage.backButton.enabled = !isChooserOpen } @Volatile private var isSaving: Boolean = false private val mainLabel: TextLabel<SaveRemixScreen> init { stage.titleIcon.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_saveremix")) stage.titleLabel.text = "screen.save.title" stage.backButton.visible = true stage.onBackButtonClick = { if (!isChooserOpen) { main.screen = ScreenRegistry.getNonNull("editor") } } stage.centreStage.elements += object : LoadingIcon<SaveRemixScreen>(main.uiPalette, stage.centreStage) { override var visible: Boolean = true get() = field && isSaving }.apply { this.renderType = ImageLabel.ImageRendering.ASPECT_RATIO this.location.set(screenHeight = 0.125f, screenY = 0.125f / 2f) } val palette = main.uiPalette stage.centreStage.elements += object : TextLabel<SaveRemixScreen>(palette, stage.centreStage, stage.centreStage) { override fun frameUpdate(screen: SaveRemixScreen) { super.frameUpdate(screen) this.visible = isChooserOpen } }.apply { this.location.set(screenHeight = 0.25f) this.textAlign = Align.center this.isLocalizationKey = true this.text = "closeChooser" this.visible = false } mainLabel = TextLabel(palette, stage.centreStage, stage.centreStage).apply { this.location.set(screenHeight = 0.75f, screenY = 0.25f) this.textAlign = Align.center this.isLocalizationKey = false this.text = "" } stage.centreStage.elements += mainLabel stage.updatePositions() updateLabels(null) } override fun renderUpdate() { super.renderUpdate() if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE) || Gdx.input.isKeyJustPressed(Input.Keys.SPACE)) { stage.onBackButtonClick() } } @Synchronized private fun openPicker() { if (!isChooserOpen) { GlobalScope.launch { isChooserOpen = true val lastSaveFile = editor.lastSaveFile val filter = TinyFDWrapper.FileExtFilter(Localization["screen.save.fileFilter"] + "(.${RHRE3.REMIX_FILE_EXTENSION})", "*.${RHRE3.REMIX_FILE_EXTENSION}") TinyFDWrapper.saveFile(Localization["screen.save.fileChooserTitle"], lastSaveFile?.file() ?: lastSaveFile?.parent()?.file() ?: attemptRememberDirectory(main, PreferenceKeys.FILE_CHOOSER_SAVE) ?: getDefaultDirectory(), filter) { file -> isChooserOpen = false if (file != null) { val newInitialDirectory = if (!file.isDirectory) file.parentFile else file persistDirectory(main, PreferenceKeys.FILE_CHOOSER_SAVE, newInitialDirectory) GlobalScope.launch { try { val correctFile = if (file.extension != RHRE3.REMIX_FILE_EXTENSION) file.parentFile.resolve("${file.name}.${RHRE3.REMIX_FILE_EXTENSION}") else file val remix = editor.remix isSaving = true Remix.saveTo(remix, correctFile, false) val newfh = FileHandle(correctFile) editor.setFileHandles(newfh) RemixRecovery.cacheChecksumOfFile(newfh) mainLabel.text = Localization["screen.save.success"] Gdx.app.postRunnable(GameMetadata::persist) } catch (t: Throwable) { t.printStackTrace() updateLabels(t) } isSaving = false } } else { stage.onBackButtonClick() } } } } } private fun updateLabels(throwable: Throwable? = null) { val label = mainLabel if (throwable == null) { label.text = "" } else { label.text = Localization["screen.save.failed", throwable::class.java.canonicalName] } } override fun show() { super.show() openPicker() updateLabels() isSaving = false } override fun dispose() { } override fun tickUpdate() { } }
core/src/main/kotlin/io/github/chrislo27/rhre3/screen/SaveRemixScreen.kt
870268296
package com.anddevbg.bapp.ui import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.anddevbg.bapp.BarApplication import com.anddevbg.bapp.di.ApplicationComponent /** * Created by teodorpenkov on 5/23/16. */ abstract class BaseFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) injectIntoComponent(BarApplication.graph) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val layout = layoutId() val result = inflater.inflate(layout, container, false) return result } protected abstract fun layoutId(): Int protected open fun onBind(view: View) { } protected open fun onUnbind() { } /** * Workaround for Dagger 2 that works only with concrete classes. Alternative is to use reflection. * @param component */ open fun injectIntoComponent(component: ApplicationComponent) { // Usual implementation will look like this. // component.inject(this); } }
app/src/main/kotlin/com.anddevbg.bapp/ui/BaseFragment.kt
700951146
package no.skatteetaten.aurora.boober.feature import assertk.assertThat import no.skatteetaten.aurora.boober.utils.AbstractFeatureTest import no.skatteetaten.aurora.boober.utils.singleApplicationError import org.junit.jupiter.api.Test class CertificateFeatureDisabledTest : AbstractFeatureTest() { override val feature: Feature get() = CertificateDisabledFeature() @Test fun `get error if trying to create certificate when feature disabled`() { assertThat { generateResources( """{ "certificate" : true, "groupId" : "org.test" }""" ) }.singleApplicationError("STS is not supported") } }
src/test/kotlin/no/skatteetaten/aurora/boober/feature/CertificateFeatureDisabledTest.kt
3613286995
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.plugins import com.netflix.spinnaker.orca.api.simplestage.SimpleStage import com.netflix.spinnaker.orca.api.simplestage.SimpleStageInput import com.netflix.spinnaker.orca.api.simplestage.SimpleStageOutput import org.pf4j.Extension @Extension class SimpleStageExtension : SimpleStage<SimpleStageExtension.Input> { override fun execute(simpleStageInput: SimpleStageInput<Input>): SimpleStageOutput<Any, Any> { return SimpleStageOutput() } override fun getName(): String { return "simpleStage" } class Input { val input: String = "input" } }
orca-plugins-test/src/main/kotlin/com/netflix/spinnaker/orca/plugins/SimpleStageExtension.kt
31489767
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.ide.impl.jps.serialization import com.intellij.openapi.util.JDOMUtil import com.intellij.util.xmlb.SkipDefaultsSerializationFilter import com.intellij.util.xmlb.XmlSerializer import com.intellij.workspaceModel.storage.impl.EntityDataDelegation import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.ide.JpsFileEntitySource import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jdom.Element import org.jetbrains.jps.model.serialization.JDomSerializationUtil import org.jetbrains.jps.model.serialization.artifact.ArtifactPropertiesState import org.jetbrains.jps.model.serialization.artifact.ArtifactState import org.jetbrains.jps.util.JpsPathUtil internal class JpsArtifactsDirectorySerializerFactory(override val directoryUrl: String) : JpsDirectoryEntitiesSerializerFactory<ArtifactEntity> { override val componentName: String get() = ARTIFACT_MANAGER_COMPONENT_NAME override val entityClass: Class<ArtifactEntity> get() = ArtifactEntity::class.java override fun createSerializer(fileUrl: String, entitySource: JpsFileEntitySource.FileInDirectory, virtualFileManager: VirtualFileUrlManager): JpsArtifactEntitiesSerializer { return JpsArtifactEntitiesSerializer(virtualFileManager.fromUrl(fileUrl), entitySource, false, virtualFileManager) } override fun getDefaultFileName(entity: ArtifactEntity): String { return entity.name } } private const val ARTIFACT_MANAGER_COMPONENT_NAME = "ArtifactManager" internal class JpsArtifactsFileSerializer(fileUrl: VirtualFileUrl, entitySource: JpsFileEntitySource, virtualFileManager: VirtualFileUrlManager) : JpsArtifactEntitiesSerializer(fileUrl, entitySource, true, virtualFileManager), JpsFileEntityTypeSerializer<ArtifactEntity> { override val isExternalStorage: Boolean get() = false override val additionalEntityTypes: List<Class<out WorkspaceEntity>> get() = listOf(ArtifactsOrderEntity::class.java) override fun deleteObsoleteFile(fileUrl: String, writer: JpsFileContentWriter) { writer.saveComponent(fileUrl, ARTIFACT_MANAGER_COMPONENT_NAME, null) } } /** * This entity stores order of artifacts in ipr file. This is needed to ensure that artifact tags are saved in the same order to avoid * unnecessary modifications of ipr file. */ @Suppress("unused") internal class ArtifactsOrderEntityData : WorkspaceEntityData<ArtifactsOrderEntity>() { lateinit var orderOfArtifacts: List<String> override fun createEntity(snapshot: WorkspaceEntityStorage): ArtifactsOrderEntity { return ArtifactsOrderEntity(orderOfArtifacts).also { addMetaData(it, snapshot) } } } internal class ArtifactsOrderEntity( val orderOfArtifacts: List<String> ) : WorkspaceEntityBase() internal class ModifiableArtifactsOrderEntity : ModifiableWorkspaceEntityBase<ArtifactsOrderEntity>() { var orderOfArtifacts: List<String> by EntityDataDelegation() } internal open class JpsArtifactEntitiesSerializer(override val fileUrl: VirtualFileUrl, override val internalEntitySource: JpsFileEntitySource, private val preserveOrder: Boolean, private val virtualFileManager: VirtualFileUrlManager) : JpsFileEntitiesSerializer<ArtifactEntity> { override val mainEntityClass: Class<ArtifactEntity> get() = ArtifactEntity::class.java override fun loadEntities(builder: WorkspaceEntityStorageBuilder, reader: JpsFileContentReader, errorReporter: ErrorReporter, virtualFileManager: VirtualFileUrlManager) { val artifactListElement = reader.loadComponent(fileUrl.url, ARTIFACT_MANAGER_COMPONENT_NAME) if (artifactListElement == null) return val source = internalEntitySource val orderOfItems = ArrayList<String>() artifactListElement.getChildren("artifact").forEach { val state = XmlSerializer.deserialize(it, ArtifactState::class.java) val outputUrl = virtualFileManager.fromPath(state.outputPath) val rootElement = loadPackagingElement(state.rootElement, source, builder) val artifactEntity = builder.addArtifactEntity(state.name, state.artifactType, state.isBuildOnMake, outputUrl, rootElement as CompositePackagingElementEntity, source) for (propertiesState in state.propertiesList) { builder.addArtifactPropertiesEntity(artifactEntity, propertiesState.id, JDOMUtil.write(propertiesState.options), source) } orderOfItems += state.name } if (preserveOrder) { val entity = builder.entities(ArtifactsOrderEntity::class.java).firstOrNull() if (entity != null) { builder.modifyEntity(ModifiableArtifactsOrderEntity::class.java, entity) { orderOfArtifacts = orderOfItems } } else { builder.addEntity(ModifiableArtifactsOrderEntity::class.java, source) { orderOfArtifacts = orderOfItems } } } } private fun loadPackagingElement(element: Element, source: EntitySource, builder: WorkspaceEntityStorageBuilder): PackagingElementEntity { fun loadElementChildren() = element.children.mapTo(ArrayList()) { loadPackagingElement(it, source, builder) } fun getAttribute(name: String) = element.getAttributeValue(name)!! fun getOptionalAttribute(name: String) = element.getAttributeValue(name) fun getPathAttribute(name: String) = virtualFileManager.fromPath(element.getAttributeValue(name)!!) return when (val typeId = getAttribute("id")) { "root" -> builder.addArtifactRootElementEntity(loadElementChildren(), source) "directory" -> builder.addDirectoryPackagingElementEntity(getAttribute("name"), loadElementChildren(), source) "archive" -> builder.addArchivePackagingElementEntity(getAttribute("name"), loadElementChildren(), source) "dir-copy" -> builder.addDirectoryCopyPackagingElementEntity(getPathAttribute("path"), source) "file-copy" -> builder.addFileCopyPackagingElementEntity(getPathAttribute("path"), getOptionalAttribute("output-file-name"), source) "extracted-dir" -> builder.addExtractedDirectoryPackagingElementEntity(getPathAttribute("path"), getAttribute("path-in-jar"), source) "artifact" -> builder.addArtifactOutputPackagingElementEntity(ArtifactId(getAttribute("artifact-name")), source) "module-output" -> builder.addModuleOutputPackagingElementEntity(ModuleId(getAttribute("name")), source) "module-test-output" -> builder.addModuleTestOutputPackagingElementEntity(ModuleId(getAttribute("name")), source) "module-source" -> builder.addModuleSourcePackagingElementEntity(ModuleId(getAttribute("name")), source) "library" -> { val moduleName = getOptionalAttribute("module-name") val level = getAttribute("level") val name = getOptionalAttribute("name") val parentId = when { moduleName != null -> LibraryTableId.ModuleLibraryTableId(ModuleId(moduleName)) else -> levelToLibraryTableId(level) } builder.addLibraryFilesPackagingElementEntity(LibraryId(name!!, parentId), source) } else -> builder.addCustomPackagingElementEntity(typeId, JDOMUtil.write(element), source) } } override fun saveEntities(mainEntities: Collection<ArtifactEntity>, entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>, storage: WorkspaceEntityStorage, writer: JpsFileContentWriter) { if (mainEntities.isEmpty()) return val componentTag = JDomSerializationUtil.createComponentElement(ARTIFACT_MANAGER_COMPONENT_NAME) val artifactsByName = mainEntities.groupByTo(HashMap()) { it.name } val orderOfItems = if (preserveOrder) (entities[ArtifactsOrderEntity::class.java]?.firstOrNull() as? ArtifactsOrderEntity?)?.orderOfArtifacts else null orderOfItems?.forEach { name -> val artifacts = artifactsByName.remove(name) artifacts?.forEach { componentTag.addContent(saveArtifact(it)) } } artifactsByName.values.forEach { it.forEach { artifact -> componentTag.addContent(saveArtifact(artifact)) } } writer.saveComponent(fileUrl.url, ARTIFACT_MANAGER_COMPONENT_NAME, componentTag) } private fun saveArtifact(artifact: ArtifactEntity): Element { val artifactState = ArtifactState() artifactState.name = artifact.name artifactState.artifactType = artifact.artifactType artifactState.isBuildOnMake = artifact.includeInProjectBuild artifactState.outputPath = JpsPathUtil.urlToPath(artifact.outputUrl.url) val customProperties = artifact.customProperties.filter { it.entitySource == artifact.entitySource } artifactState.propertiesList = customProperties.mapTo(ArrayList()) { ArtifactPropertiesState().apply { id = it.providerType options = it.propertiesXmlTag?.let { JDOMUtil.load(it) } } } artifactState.rootElement = savePackagingElement(artifact.rootElement) return XmlSerializer.serialize(artifactState, SkipDefaultsSerializationFilter()) } private fun savePackagingElement(element: PackagingElementEntity): Element { val tag = Element("element") fun setId(typeId: String) = tag.setAttribute("id", typeId) fun setAttribute(name: String, value: String) = tag.setAttribute(name, value) fun setPathAttribute(name: String, value: VirtualFileUrl) = tag.setAttribute(name, JpsPathUtil.urlToPath(value.url)) fun saveElementChildren(composite: CompositePackagingElementEntity) { composite.children.forEach { tag.addContent(savePackagingElement(it)) } } when (element) { is ArtifactRootElementEntity -> { setId("root") saveElementChildren(element) } is DirectoryPackagingElementEntity -> { setId("directory") setAttribute("name", element.directoryName) saveElementChildren(element) } is ArchivePackagingElementEntity -> { setId("archive") setAttribute("name", element.fileName) saveElementChildren(element) } is DirectoryCopyPackagingElementEntity -> { setId("dir-copy") setPathAttribute("path", element.directory) } is FileCopyPackagingElementEntity -> { setId("file-copy") setPathAttribute("path", element.file) element.renamedOutputFileName?.let { setAttribute("output-file-name", it) } } is ExtractedDirectoryPackagingElementEntity -> { setId("extracted-dir") setPathAttribute("path", element.archive) setAttribute("path-in-jar", element.pathInArchive) } is ArtifactOutputPackagingElementEntity -> { setId("artifact") setAttribute("artifact-name", element.artifact.name) } is ModuleOutputPackagingElementEntity -> { setId("module-output") setAttribute("name", element.module.name) } is ModuleTestOutputPackagingElementEntity -> { setId("module-test-output") setAttribute("name", element.module.name) } is ModuleSourcePackagingElementEntity -> { setId("module-source") setAttribute("name", element.module.name) } is LibraryFilesPackagingElementEntity -> { setId("library") val tableId = element.library.tableId setAttribute("level", tableId.level) setAttribute("name", element.library.name) if (tableId is LibraryTableId.ModuleLibraryTableId) { setAttribute("module-name", tableId.moduleId.name) } } } return tag } override fun toString(): String = "${javaClass.simpleName.substringAfterLast('.')}($fileUrl)" }
platform/workspaceModel/ide/src/com/intellij/workspaceModel/ide/impl/jps/serialization/JpsArtifactEntitiesSerializer.kt
2084235316
package com.aemtools.test.completion import com.aemtools.test.base.BaseLightTest import com.aemtools.test.completion.model.CompletionTestFixture import com.aemtools.test.completion.model.ICompletionTestFixture import com.aemtools.test.fixture.JdkProjectDescriptor import com.intellij.testFramework.LightProjectDescriptor /** * @author Dmytro Troynikov */ abstract class CompletionBaseLightTest(withUberJar: Boolean = true) : BaseLightTest(withUberJar) { fun completionTest(fixture: ICompletionTestFixture.() -> Unit) { val completionTestFixture = CompletionTestFixture(myFixture).apply { fixture() } completionTestFixture.init() completionTestFixture.test() } override fun getProjectDescriptor(): LightProjectDescriptor { return JdkProjectDescriptor() } }
test-framework/src/main/kotlin/com/aemtools/test/completion/CompletionBaseLightTest.kt
1759872733
/* * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.scheduling import kotlinx.atomicfu.* import kotlinx.coroutines.* import org.junit.Test import kotlin.coroutines.* import kotlin.test.* class LimitingCoroutineDispatcherStressTest : SchedulerTestBase() { init { corePoolSize = 3 } private val blocking = blockingDispatcher(2) private val cpuView = view(2) private val cpuView2 = view(2) private val concurrentWorkers = atomic(0) private val iterations = 25_000 * stressTestMultiplierSqrt @Test fun testCpuLimitNotExtended() = runBlocking<Unit> { val tasks = ArrayList<Deferred<*>>(iterations * 2) repeat(iterations) { tasks += task(cpuView, 3) tasks += task(cpuView2, 3) } tasks.awaitAll() } @Test fun testCpuLimitWithBlocking() = runBlocking<Unit> { val tasks = ArrayList<Deferred<*>>(iterations * 2) repeat(iterations) { tasks += task(cpuView, 4) tasks += task(blocking, 4) } tasks.awaitAll() } private fun task(ctx: CoroutineContext, maxLimit: Int): Deferred<Unit> = GlobalScope.async(ctx) { try { val currentlyExecuting = concurrentWorkers.incrementAndGet() assertTrue(currentlyExecuting <= maxLimit, "Executing: $currentlyExecuting, max limit: $maxLimit") } finally { concurrentWorkers.decrementAndGet() } } }
kotlinx-coroutines-core/jvm/test/scheduling/LimitingCoroutineDispatcherStressTest.kt
2077323606
/* Copyright (c) 2021 DeflatedPickle under the MIT license */ package com.deflatedpickle.quiver.packexport.api /** * A step during exporting that is run on the pack as a whole */ abstract class BulkExportStep : ExportStep { override fun toString(): String = "BulkExportStep( ${getSlug()}: ${getType()} )" }
packexport/src/main/kotlin/com/deflatedpickle/quiver/packexport/api/BulkExportStep.kt
2191619960
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.function.server import org.springframework.core.io.Resource import org.springframework.http.HttpMethod import org.springframework.http.HttpStatus import org.springframework.http.HttpStatusCode import org.springframework.http.MediaType import reactor.core.publisher.Mono import java.net.URI import java.util.function.Supplier /** * Allow to create easily a WebFlux.fn [RouterFunction] with a [Reactive router Kotlin DSL][RouterFunctionDsl]. * * Example: * * ``` * @Configuration * class RouterConfiguration { * * @Bean * fun mainRouter(userHandler: UserHandler) = router { * accept(TEXT_HTML).nest { * (GET("/user/") or GET("/users/")).invoke(userHandler::findAllView) * GET("/users/{login}", userHandler::findViewById) * } * accept(APPLICATION_JSON).nest { * (GET("/api/user/") or GET("/api/users/")).invoke(userHandler::findAll) * POST("/api/users/", userHandler::create) * } * } * * } * ``` * @author Sebastien Deleuze * @see coRouter * @since 5.0 */ fun router(routes: RouterFunctionDsl.() -> Unit) = RouterFunctionDsl(routes).build() /** * Provide a WebFlux.fn [RouterFunction] Reactive Kotlin DSL created by [`router { }`][router] in order to be able to write idiomatic Kotlin code. * * @author Sebastien Deleuze * @author Yevhenii Melnyk * @author Arjen Poutsma * @since 5.0 */ class RouterFunctionDsl internal constructor (private val init: RouterFunctionDsl.() -> Unit) { @PublishedApi internal val builder = RouterFunctions.route() /** * Return a composed request predicate that tests against both this predicate AND * the [other] predicate (String processed as a path predicate). When evaluating the * composed predicate, if this predicate is `false`, then the [other] predicate is not * evaluated. * @see RequestPredicate.and * @see RequestPredicates.path */ infix fun RequestPredicate.and(other: String): RequestPredicate = this.and(path(other)) /** * Return a composed request predicate that tests against both this predicate OR * the [other] predicate (String processed as a path predicate). When evaluating the * composed predicate, if this predicate is `true`, then the [other] predicate is not * evaluated. * @see RequestPredicate.or * @see RequestPredicates.path */ infix fun RequestPredicate.or(other: String): RequestPredicate = this.or(path(other)) /** * Return a composed request predicate that tests against both this predicate (String * processed as a path predicate) AND the [other] predicate. When evaluating the * composed predicate, if this predicate is `false`, then the [other] predicate is not * evaluated. * @see RequestPredicate.and * @see RequestPredicates.path */ infix fun String.and(other: RequestPredicate): RequestPredicate = path(this).and(other) /** * Return a composed request predicate that tests against both this predicate (String * processed as a path predicate) OR the [other] predicate. When evaluating the * composed predicate, if this predicate is `true`, then the [other] predicate is not * evaluated. * @see RequestPredicate.or * @see RequestPredicates.path */ infix fun String.or(other: RequestPredicate): RequestPredicate = path(this).or(other) /** * Return a composed request predicate that tests against both this predicate AND * the [other] predicate. When evaluating the composed predicate, if this * predicate is `false`, then the [other] predicate is not evaluated. * @see RequestPredicate.and */ infix fun RequestPredicate.and(other: RequestPredicate): RequestPredicate = this.and(other) /** * Return a composed request predicate that tests against both this predicate OR * the [other] predicate. When evaluating the composed predicate, if this * predicate is `true`, then the [other] predicate is not evaluated. * @see RequestPredicate.or */ infix fun RequestPredicate.or(other: RequestPredicate): RequestPredicate = this.or(other) /** * Return a predicate that represents the logical negation of this predicate. */ operator fun RequestPredicate.not(): RequestPredicate = this.negate() /** * Route to the given router function if the given request predicate applies. This * method can be used to create *nested routes*, where a group of routes share a * common path (prefix), header, or other request predicate. * @see RouterFunctions.nest */ fun RequestPredicate.nest(init: RouterFunctionDsl.() -> Unit) { builder.nest(this, Supplier { RouterFunctionDsl(init).build() }) } /** * Route to the given router function if the given request predicate (String * processed as a path predicate) applies. This method can be used to create * *nested routes*, where a group of routes share a common path * (prefix), header, or other request predicate. * @see RouterFunctions.nest * @see RequestPredicates.path */ fun String.nest(init: RouterFunctionDsl.() -> Unit) { builder.path(this, Supplier { RouterFunctionDsl(init).build() }) } /** * Adds a route to the given handler function that handles all HTTP `GET` requests. * @since 5.3 */ fun GET(f: (ServerRequest) -> Mono<out ServerResponse>) { builder.GET { f(it).cast(ServerResponse::class.java) } } /** * Adds a route to the given handler function that handles all HTTP `GET` requests * that match the given pattern. * @param pattern the pattern to match to */ fun GET(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.GET(pattern) { f(it).cast(ServerResponse::class.java) } } /** * Adds a route to the given handler function that handles all HTTP `GET` requests * that match the given predicate. * @param predicate predicate to match * @since 5.3 */ fun GET(predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.GET(predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }) } /** * Adds a route to the given handler function that handles all HTTP `GET` requests * that match the given pattern and predicate. * @param pattern the pattern to match to * @param predicate additional predicate to match * @since 5.2 */ fun GET(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.GET(pattern, predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }) } /** * Return a [RequestPredicate] that matches if request's HTTP method is `GET` * and the given `pattern` matches against the request path. * @see RequestPredicates.GET */ fun GET(pattern: String): RequestPredicate = RequestPredicates.GET(pattern) /** * Adds a route to the given handler function that handles all HTTP `HEAD` requests. * @since 5.3 */ fun HEAD(f: (ServerRequest) -> Mono<out ServerResponse>) { builder.HEAD { f(it).cast(ServerResponse::class.java) } } /** * Adds a route to the given handler function that handles all HTTP `HEAD` requests * that match the given pattern. * @param pattern the pattern to match to */ fun HEAD(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.HEAD(pattern) { f(it).cast(ServerResponse::class.java) } } /** * Adds a route to the given handler function that handles all HTTP `HEAD` requests * that match the given predicate. * @param predicate predicate to match * @since 5.3 */ fun HEAD(predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.HEAD(predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }) } /** * Adds a route to the given handler function that handles all HTTP `HEAD` requests * that match the given pattern and predicate. * @param pattern the pattern to match to * @param predicate additional predicate to match * @since 5.2 */ fun HEAD(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.HEAD(pattern, predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }) } /** * Return a [RequestPredicate] that matches if request's HTTP method is `HEAD` * and the given `pattern` matches against the request path. * @see RequestPredicates.HEAD */ fun HEAD(pattern: String): RequestPredicate = RequestPredicates.HEAD(pattern) /** * Adds a route to the given handler function that handles all HTTP `POST` requests. * @since 5.3 */ fun POST(f: (ServerRequest) -> Mono<out ServerResponse>) { builder.POST { f(it).cast(ServerResponse::class.java) } } /** * Adds a route to the given handler function that handles all HTTP `POST` requests * that match the given pattern. * @param pattern the pattern to match to */ fun POST(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.POST(pattern) { f(it).cast(ServerResponse::class.java) } } /** * Adds a route to the given handler function that handles all HTTP `POST` requests * that match the given predicate. * @param predicate predicate to match * @since 5.3 */ fun POST(predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.POST(predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }) } /** * Adds a route to the given handler function that handles all HTTP `POST` requests * that match the given pattern and predicate. * @param pattern the pattern to match to * @param predicate additional predicate to match * @since 5.2 */ fun POST(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.POST(pattern, predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }) } /** * Return a [RequestPredicate] that matches if request's HTTP method is `POST` * and the given `pattern` matches against the request path. * @see RequestPredicates.POST */ fun POST(pattern: String): RequestPredicate = RequestPredicates.POST(pattern) /** * Adds a route to the given handler function that handles all HTTP `PUT` requests. * @since 5.3 */ fun PUT(f: (ServerRequest) -> Mono<out ServerResponse>) { builder.PUT { f(it).cast(ServerResponse::class.java) } } /** * Adds a route to the given handler function that handles all HTTP `PUT` requests * that match the given pattern. * @param pattern the pattern to match to */ fun PUT(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.PUT(pattern) { f(it).cast(ServerResponse::class.java) } } /** * Adds a route to the given handler function that handles all HTTP `PUT` requests * that match the given predicate. * @param predicate predicate to match * @since 5.3 */ fun PUT(predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.PUT(predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }) } /** * Adds a route to the given handler function that handles all HTTP `PUT` requests * that match the given pattern and predicate. * @param pattern the pattern to match to * @param predicate additional predicate to match * @since 5.2 */ fun PUT(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.PUT(pattern, predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }) } /** * Return a [RequestPredicate] that matches if request's HTTP method is `PUT` * and the given `pattern` matches against the request path. * @see RequestPredicates.PUT */ fun PUT(pattern: String): RequestPredicate = RequestPredicates.PUT(pattern) /** * Adds a route to the given handler function that handles all HTTP `PATCH` requests. * @since 5.3 */ fun PATCH(f: (ServerRequest) -> Mono<out ServerResponse>) { builder.PATCH { f(it).cast(ServerResponse::class.java) } } /** * Adds a route to the given handler function that handles all HTTP `PATCH` requests * that match the given pattern. * @param pattern the pattern to match to */ fun PATCH(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.PATCH(pattern) { f(it).cast(ServerResponse::class.java) } } /** * Adds a route to the given handler function that handles all HTTP `PATCH` requests * that match the given predicate. * @param predicate predicate to match * @since 5.3 */ fun PATCH(predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.PATCH(predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }) } /** * Adds a route to the given handler function that handles all HTTP `PATCH` requests * that match the given pattern and predicate. * @param pattern the pattern to match to * @param predicate additional predicate to match * @since 5.2 */ fun PATCH(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.PATCH(pattern, predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }) } /** * Return a [RequestPredicate] that matches if request's HTTP method is `PATCH` * and the given `pattern` matches against the request path. * @param pattern the path pattern to match against * @return a predicate that matches if the request method is `PATCH` and if the given pattern * matches against the request path */ fun PATCH(pattern: String): RequestPredicate = RequestPredicates.PATCH(pattern) /** * Adds a route to the given handler function that handles all HTTP `DELETE` requests. * @since 5.3 */ fun DELETE(f: (ServerRequest) -> Mono<out ServerResponse>) { builder.DELETE { f(it).cast(ServerResponse::class.java) } } /** * Adds a route to the given handler function that handles all HTTP `DELETE` requests * that match the given pattern. * @param pattern the pattern to match to */ fun DELETE(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.DELETE(pattern) { f(it).cast(ServerResponse::class.java) } } /** * Adds a route to the given handler function that handles all HTTP `DELETE` requests * that match the given predicate. * @param predicate predicate to match * @since 5.3 */ fun DELETE(predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.DELETE(predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }) } /** * Adds a route to the given handler function that handles all HTTP `DELETE` requests * that match the given pattern and predicate. * @param pattern the pattern to match to * @param predicate additional predicate to match * @since 5.2 */ fun DELETE(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.DELETE(pattern, predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }) } /** * Return a [RequestPredicate] that matches if request's HTTP method is `DELETE` * and the given `pattern` matches against the request path. * @param pattern the path pattern to match against * @return a predicate that matches if the request method is `DELETE` and if the given pattern * matches against the request path */ fun DELETE(pattern: String): RequestPredicate = RequestPredicates.DELETE(pattern) /** * Adds a route to the given handler function that handles all HTTP `OPTIONS` requests. * @since 5.3 */ fun OPTIONS(f: (ServerRequest) -> Mono<out ServerResponse>) { builder.OPTIONS { f(it).cast(ServerResponse::class.java) } } /** * Adds a route to the given handler function that handles all HTTP `OPTIONS` requests * that match the given pattern. * @param pattern the pattern to match to */ fun OPTIONS(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.OPTIONS(pattern) { f(it).cast(ServerResponse::class.java) } } /** * Adds a route to the given handler function that handles all HTTP `OPTIONS` requests * that match the given predicate. * @param predicate predicate to match * @since 5.3 */ fun OPTIONS(predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.OPTIONS(predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }) } /** * Adds a route to the given handler function that handles all HTTP `OPTIONS` requests * that match the given pattern and predicate. * @param pattern the pattern to match to * @param predicate additional predicate to match * @since 5.2 */ fun OPTIONS(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.OPTIONS(pattern, predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }) } /** * Return a [RequestPredicate] that matches if request's HTTP method is `OPTIONS` * and the given `pattern` matches against the request path. * @param pattern the path pattern to match against * @return a predicate that matches if the request method is `OPTIONS` and if the given pattern * matches against the request path */ fun OPTIONS(pattern: String): RequestPredicate = RequestPredicates.OPTIONS(pattern) /** * Route to the given handler function if the given accept predicate applies. * @see RouterFunctions.route */ fun accept(mediaType: MediaType, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.add(RouterFunctions.route(RequestPredicates.accept(mediaType), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })) } /** * Return a [RequestPredicate] that tests if the request's * [accept][ServerRequest.Headers.accept] header is * [compatible][MediaType.isCompatibleWith] with any of the given media types. * @param mediaTypes the media types to match the request's accept header against * @return a predicate that tests the request's accept header against the given media types */ fun accept(vararg mediaTypes: MediaType): RequestPredicate = RequestPredicates.accept(*mediaTypes) /** * Route to the given handler function if the given contentType predicate applies. * @see RouterFunctions.route */ fun contentType(mediaTypes: MediaType, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.add(RouterFunctions.route(RequestPredicates.contentType(mediaTypes), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })) } /** * Return a [RequestPredicate] that tests if the request's * [content type][ServerRequest.Headers.contentType] is * [included][MediaType.includes] by any of the given media types. * @param mediaTypes the media types to match the request's content type against * @return a predicate that tests the request's content type against the given media types */ fun contentType(vararg mediaTypes: MediaType): RequestPredicate = RequestPredicates.contentType(*mediaTypes) /** * Route to the given handler function if the given headers predicate applies. * @see RouterFunctions.route */ fun headers(headersPredicate: (ServerRequest.Headers) -> Boolean, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.add(RouterFunctions.route(RequestPredicates.headers(headersPredicate), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })) } /** * Return a [RequestPredicate] that tests the request's headers against the given headers predicate. * @param headersPredicate a predicate that tests against the request headers * @return a predicate that tests against the given header predicate */ fun headers(headersPredicate: (ServerRequest.Headers) -> Boolean): RequestPredicate = RequestPredicates.headers(headersPredicate) /** * Route to the given handler function if the given method predicate applies. * @see RouterFunctions.route */ fun method(httpMethod: HttpMethod, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.add(RouterFunctions.route(RequestPredicates.method(httpMethod), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })) } /** * Return a [RequestPredicate] that tests against the given HTTP method. * @param httpMethod the HTTP method to match to * @return a predicate that tests against the given HTTP method */ fun method(httpMethod: HttpMethod): RequestPredicate = RequestPredicates.method(httpMethod) /** * Route to the given handler function if the given path predicate applies. * @see RouterFunctions.route */ fun path(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.add(RouterFunctions.route(RequestPredicates.path(pattern), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })) } /** * Return a [RequestPredicate] that tests the request path against the given path pattern. * @see RequestPredicates.path */ fun path(pattern: String): RequestPredicate = RequestPredicates.path(pattern) /** * Route to the given handler function if the given pathExtension predicate applies. * @see RouterFunctions.route */ fun pathExtension(extension: String, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.add(RouterFunctions.route(RequestPredicates.pathExtension(extension), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })) } /** * Return a [RequestPredicate] that matches if the request's path has the given extension. * @param extension the path extension to match against, ignoring case * @return a predicate that matches if the request's path has the given file extension */ fun pathExtension(extension: String): RequestPredicate = RequestPredicates.pathExtension(extension) /** * Route to the given handler function if the given pathExtension predicate applies. * @see RouterFunctions.route */ fun pathExtension(predicate: (String) -> Boolean, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.add(RouterFunctions.route(RequestPredicates.pathExtension(predicate), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })) } /** * Return a [RequestPredicate] that matches if the request's path matches the given * predicate. * @see RequestPredicates.pathExtension */ fun pathExtension(predicate: (String) -> Boolean): RequestPredicate = RequestPredicates.pathExtension(predicate) /** * Route to the given handler function if the given queryParam predicate applies. * @see RouterFunctions.route */ fun queryParam(name: String, predicate: (String) -> Boolean, f: (ServerRequest) -> Mono<out ServerResponse>) { builder.add(RouterFunctions.route(RequestPredicates.queryParam(name, predicate), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })) } /** * Return a [RequestPredicate] that tests the request's query parameter of the given name * against the given predicate. * @param name the name of the query parameter to test against * @param predicate the predicate to test against the query parameter value * @return a predicate that matches the given predicate against the query parameter of the given name * @see ServerRequest#queryParam(String) */ fun queryParam(name: String, predicate: (String) -> Boolean): RequestPredicate = RequestPredicates.queryParam(name, predicate) /** * Route to the given handler function if the given request predicate applies. * @see RouterFunctions.route */ operator fun RequestPredicate.invoke(f: (ServerRequest) -> Mono<out ServerResponse>) { builder.add(RouterFunctions.route(this, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })) } /** * Route to the given handler function if the given predicate (String * processed as a path predicate) applies. * @see RouterFunctions.route */ operator fun String.invoke(f: (ServerRequest) -> Mono<out ServerResponse>) { builder.add(RouterFunctions.route(RequestPredicates.path(this), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })) } /** * Route requests that match the given pattern to resources relative to the given root location. * @see RouterFunctions.resources */ fun resources(path: String, location: Resource) { builder.resources(path, location) } /** * Route to resources using the provided lookup function. If the lookup function provides a * [Resource] for the given request, it will be it will be exposed using a * [HandlerFunction] that handles GET, HEAD, and OPTIONS requests. */ fun resources(lookupFunction: (ServerRequest) -> Mono<Resource>) { builder.resources(lookupFunction) } /** * Merge externally defined router functions into this one. * @param routerFunction the router function to be added * @since 5.2 */ fun add(routerFunction: RouterFunction<ServerResponse>) { builder.add(routerFunction) } /** * Filters all routes created by this router with the given filter function. Filter * functions are typically used to address cross-cutting concerns, such as logging, * security, etc. * @param filterFunction the function to filter all routes built by this router * @since 5.2 */ fun filter(filterFunction: (ServerRequest, (ServerRequest) -> Mono<ServerResponse>) -> Mono<ServerResponse>) { builder.filter { request, next -> filterFunction(request) { next.handle(it) } } } /** * Filter the request object for all routes created by this builder with the given request * processing function. Filters are typically used to address cross-cutting concerns, such * as logging, security, etc. * @param requestProcessor a function that transforms the request * @since 5.2 */ fun before(requestProcessor: (ServerRequest) -> ServerRequest) { builder.before(requestProcessor) } /** * Filter the response object for all routes created by this builder with the given response * processing function. Filters are typically used to address cross-cutting concerns, such * as logging, security, etc. * @param responseProcessor a function that transforms the response * @since 5.2 */ fun after(responseProcessor: (ServerRequest, ServerResponse) -> ServerResponse) { builder.after(responseProcessor) } /** * Filters all exceptions that match the predicate by applying the given response provider * function. * @param predicate the type of exception to filter * @param responseProvider a function that creates a response * @since 5.2 */ fun onError(predicate: (Throwable) -> Boolean, responseProvider: (Throwable, ServerRequest) -> Mono<ServerResponse>) { builder.onError(predicate, responseProvider) } /** * Filters all exceptions that match the predicate by applying the given response provider * function. * @param E the type of exception to filter * @param responseProvider a function that creates a response * @since 5.2 */ inline fun <reified E : Throwable> onError(noinline responseProvider: (Throwable, ServerRequest) -> Mono<ServerResponse>) { builder.onError({it is E}, responseProvider) } /** * Add an attribute with the given name and value to the last route built with this builder. * @param name the attribute name * @param value the attribute value * @since 6.0 */ fun withAttribute(name: String, value: Any) { builder.withAttribute(name, value) } /** * Manipulate the attributes of the last route built with the given consumer. * * The map provided to the consumer is "live", so that the consumer can be used * to [overwrite][MutableMap.put] existing attributes, * [remove][MutableMap.remove] attributes, or use any of the other * [MutableMap] methods. * @param attributesConsumer a function that consumes the attributes map * @since 6.0 */ fun withAttributes(attributesConsumer: (MutableMap<String, Any>) -> Unit) { builder.withAttributes(attributesConsumer) } /** * Return a composed routing function created from all the registered routes. * @since 5.1 */ internal fun build(): RouterFunction<ServerResponse> { init() return builder.build() } /** * Create a builder with the status code and headers of the given response. * @param other the response to copy the status and headers from * @return the created builder * @since 5.1 */ fun from(other: ServerResponse): ServerResponse.BodyBuilder = ServerResponse.from(other) /** * Create a builder with the given HTTP status. * @param status the response status * @return the created builder * @since 5.1 */ fun status(status: HttpStatusCode): ServerResponse.BodyBuilder = ServerResponse.status(status) /** * Create a builder with the given HTTP status. * @param status the response status * @return the created builder * @since 5.1 */ fun status(status: Int): ServerResponse.BodyBuilder = ServerResponse.status(status) /** * Create a builder with the status set to [200 OK][HttpStatus.OK]. * @return the created builder * @since 5.1 */ fun ok(): ServerResponse.BodyBuilder = ServerResponse.ok() /** * Create a new builder with a [201 Created][HttpStatus.CREATED] status * and a location header set to the given URI. * @param location the location URI * @return the created builder * @since 5.1 */ fun created(location: URI): ServerResponse.BodyBuilder = ServerResponse.created(location) /** * Create a builder with an [202 Accepted][HttpStatus.ACCEPTED] status. * @return the created builder * @since 5.1 */ fun accepted(): ServerResponse.BodyBuilder = ServerResponse.accepted() /** * Create a builder with a [204 No Content][HttpStatus.NO_CONTENT] status. * @return the created builder * @since 5.1 */ fun noContent(): ServerResponse.HeadersBuilder<*> = ServerResponse.noContent() /** * Create a builder with a [303 See Other][HttpStatus.SEE_OTHER] * status and a location header set to the given URI. * @param location the location URI * @return the created builder * @since 5.1 */ fun seeOther(location: URI): ServerResponse.BodyBuilder = ServerResponse.seeOther(location) /** * Create a builder with a [307 Temporary Redirect][HttpStatus.TEMPORARY_REDIRECT] * status and a location header set to the given URI. * @param location the location URI * @return the created builder * @since 5.1 */ fun temporaryRedirect(location: URI): ServerResponse.BodyBuilder = ServerResponse.temporaryRedirect(location) /** * Create a builder with a [308 Permanent Redirect][HttpStatus.PERMANENT_REDIRECT] * status and a location header set to the given URI. * @param location the location URI * @return the created builder * @since 5.1 */ fun permanentRedirect(location: URI): ServerResponse.BodyBuilder = ServerResponse.permanentRedirect(location) /** * Create a builder with a [400 Bad Request][HttpStatus.BAD_REQUEST] status. * @return the created builder * @since 5.1 */ fun badRequest(): ServerResponse.BodyBuilder = ServerResponse.badRequest() /** * Create a builder with a [404 Not Found][HttpStatus.NOT_FOUND] status. * @return the created builder * @since 5.1 */ fun notFound(): ServerResponse.HeadersBuilder<*> = ServerResponse.notFound() /** * Create a builder with an * [422 Unprocessable Entity][HttpStatus.UNPROCESSABLE_ENTITY] status. * @return the created builder * @since 5.1 */ fun unprocessableEntity(): ServerResponse.BodyBuilder = ServerResponse.unprocessableEntity() }
spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/server/RouterFunctionDsl.kt
1394896895
// 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.serviceContainer import com.intellij.openapi.components.Service import com.intellij.openapi.extensions.DefaultPluginDescriptor import com.intellij.testFramework.PlatformTestUtil import org.junit.Assert import org.junit.Test class ConstructorInjectionTest { private val pluginDescriptor = DefaultPluginDescriptor("test") @Test fun `interface extension`() { val componentManager = TestComponentManager(isGetComponentAdapterOfTypeCheckEnabled = false) val area = componentManager.extensionArea val point = area.registerPoint("bar", Bar::class.java, pluginDescriptor) @Suppress("DEPRECATION") point.registerExtension(BarImpl()) componentManager.instantiateClassWithConstructorInjection(Foo::class.java, Foo::class.java, pluginDescriptor.pluginId) } //@Test //fun `resolve light service`() { // val componentManager = TestComponentManager() // componentManager.instantiateClassWithConstructorInjection(BarServiceClient::class.java, BarServiceClient::class.java.name, pluginDescriptor.pluginId) //} @Test fun `light service getService() performance`() { val componentManager = TestComponentManager() Assert.assertNotNull(componentManager.getService(BarService::class.java)) PlatformTestUtil.startPerformanceTest("getService() must be fast for cached service", 1000) { for (i in 0..30_000_000) { Assert.assertNotNull(componentManager.getService(BarService::class.java)) } }.assertTiming() } @Test fun `constructor with bool`() { val componentManager = TestComponentManager() componentManager.registerService(ConstructorWithBoolean::class.java, ConstructorWithBoolean::class.java, testPluginDescriptor, false) componentManager.getService(ConstructorWithBoolean::class.java) } } private interface Bar private class BarImpl : Bar private class Foo(@Suppress("UNUSED_PARAMETER") bar: BarImpl) @Service private class BarService //private class BarServiceClient(@Suppress("UNUSED_PARAMETER") bar: BarService)
platform/platform-tests/testSrc/com/intellij/serviceContainer/ConstructorInjectionTest.kt
2461390153
package com.intellij.workspace.legacyBridge.intellij import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.rd.attachChild import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Pair import com.intellij.openapi.vfs.AsyncFileListener import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent import com.intellij.openapi.vfs.pointers.VirtualFilePointer import com.intellij.openapi.vfs.pointers.VirtualFilePointerContainer import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.MultiMap import com.intellij.workspace.api.VirtualFileUrl import com.intellij.workspace.virtualFileUrl import org.jdom.Element import java.util.concurrent.ConcurrentMap import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock internal class LegacyBridgeFilePointerProviderImpl : LegacyBridgeFilePointerProvider, Disposable { private var currentDisposable = nextDisposable() private val filePointers: ConcurrentMap<VirtualFileUrl, VirtualFilePointer> = ContainerUtil.newConcurrentMap() private val fileContainers: ConcurrentMap<LegacyBridgeFileContainer, VirtualFilePointerContainer> = ContainerUtil.newConcurrentMap() private val fileContainerUrlsLock = ReentrantLock() private val fileContainerUrls = MultiMap.create<VirtualFileUrl, LegacyBridgeFileContainer>() init { VirtualFileManager.getInstance().addAsyncFileListener(AsyncFileListener { events -> val pointersToProcess = mutableSetOf<VirtualFileUrl>() val containersToProcess = mutableSetOf<LegacyBridgeFileContainer>() fileContainerUrlsLock.withLock { fun handleUrl(url: VirtualFileUrl) { pointersToProcess.add(url) for (descriptor in fileContainerUrls.get(url)) { containersToProcess.add(descriptor) } } for (event in events) { if (event is VFileMoveEvent) { handleUrl(event.file.virtualFileUrl) } else if (event is VFilePropertyChangeEvent && event.isRename) { handleUrl(event.file.virtualFileUrl) } } } object : AsyncFileListener.ChangeApplier { override fun beforeVfsChange() { pointersToProcess.forEach { filePointers.remove(it) } containersToProcess.forEach { fileContainers.remove(it) } } } }, this) } override fun dispose() = Unit override fun getAndCacheFilePointer(url: VirtualFileUrl): VirtualFilePointer = filePointers.getOrPut(url) { VirtualFilePointerManager.getInstance().create(url.url, currentDisposable, object : VirtualFilePointerListener { override fun validityChanged(pointers: Array<out VirtualFilePointer>) { filePointers.remove(url) } }) } override fun getAndCacheFileContainer(description: LegacyBridgeFileContainer): VirtualFilePointerContainer { val existingContainer = fileContainers[description] if (existingContainer != null) return existingContainer val container = VirtualFilePointerManager.getInstance().createContainer( currentDisposable, object : VirtualFilePointerListener { override fun validityChanged(pointers: Array<out VirtualFilePointer>) { fileContainers.remove(description) } } ) for (url in description.urls) { container.add(url.url) } for (jarDirectory in description.jarDirectories) { container.addJarDirectory(jarDirectory.directoryUrl.url, jarDirectory.recursive) } registerContainer(description, container) return ReadonlyFilePointerContainer(container) } fun disposeAndClearCaches() { ApplicationManager.getApplication().assertWriteAccessAllowed() val oldDisposable = currentDisposable currentDisposable = nextDisposable() fileContainerUrlsLock.withLock { fileContainerUrls.clear() } filePointers.clear() fileContainers.clear() Disposer.dispose(oldDisposable) } private fun registerContainer(description: LegacyBridgeFileContainer, container: VirtualFilePointerContainer) { fileContainers[description] = container fileContainerUrlsLock.withLock { description.urls.forEach { fileContainerUrls.putValue(it, description) } description.jarDirectories.forEach { fileContainerUrls.putValue(it.directoryUrl, description) } } } private fun nextDisposable() = Disposer.newDisposable().also { this.attachChild(it) } private class ReadonlyFilePointerContainer(val container: VirtualFilePointerContainer) : VirtualFilePointerContainer { private fun throwReadonly(): Nothing = throw NotImplementedError("Read-Only File Pointer Container") override fun getFiles(): Array<VirtualFile> = container.files override fun getJarDirectories(): MutableList<Pair<String, Boolean>> = container.jarDirectories override fun getUrls(): Array<String> = container.urls override fun getDirectories(): Array<VirtualFile> = container.directories override fun getList(): MutableList<VirtualFilePointer> = container.list override fun clone(parent: Disposable): VirtualFilePointerContainer = container.clone(parent) override fun clone(parent: Disposable, listener: VirtualFilePointerListener?): VirtualFilePointerContainer = container.clone(parent, listener) override fun findByUrl(url: String): VirtualFilePointer? = container.findByUrl(url) override fun writeExternal(element: Element, childElementName: String, externalizeJarDirectories: Boolean) { container.writeExternal(element, childElementName, externalizeJarDirectories) } override fun size(): Int = container.size() override fun clear() = throwReadonly() override fun addAll(that: VirtualFilePointerContainer) = throwReadonly() override fun addJarDirectory(directoryUrl: String, recursively: Boolean) = throwReadonly() override fun remove(pointer: VirtualFilePointer) = throwReadonly() override fun removeJarDirectory(directoryUrl: String): Boolean = throwReadonly() override fun moveUp(url: String) = throwReadonly() override fun add(file: VirtualFile) = throwReadonly() override fun add(url: String) = throwReadonly() override fun readExternal(rootChild: Element, childElementName: String, externalizeJarDirectories: Boolean) = throwReadonly() override fun killAll() = throwReadonly() override fun moveDown(url: String) = throwReadonly() override fun isEmpty(): Boolean = container.isEmpty } }
platform/workspaceModel-ide/src/com/intellij/workspace/legacyBridge/intellij/LegacyBridgeFilePointerProviderImpl.kt
3133021274
package com.dbflow5 import com.dbflow5.sql.Query import org.junit.Assert.assertEquals import org.junit.Assert.fail import kotlin.reflect.KClass fun String.assertEquals(query: Query) = assertEquals(this, query.query.trim()) fun Query.assertEquals(actual: Query) = assertEquals(query.trim(), actual.query.trim()) fun assertThrowsException(expectedException: KClass<out Exception>, function: () -> Unit) { try { function() fail("Expected call to fail. Unexpectedly passed") } catch (e: Exception) { if (e.javaClass != expectedException.java) { e.printStackTrace() fail("Expected $expectedException but got ${e.javaClass}") } } }
tests/src/androidTest/java/com/dbflow5/TestExtensions.kt
3648731313
/* * 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 /** * 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 // TODO: these methods should probably be combined into the only one, but it would require some refactoring. } data class NativeLibrary(val includes: List<String>, val additionalPreambleLines: List<String>, val compilerArgs: List<String>, val headerToIdMapper: HeaderToIdMapper, val language: Language, val excludeSystemLibs: Boolean, // TODO: drop? val excludeDepdendentModules: Boolean, val headerInclusionPolicy: HeaderInclusionPolicy) /** * Retrieves the definitions from given C header file using given compiler arguments (e.g. defines). */ fun buildNativeIndex(library: NativeLibrary): NativeIndex = buildNativeIndexImpl(library) /** * 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 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 } /** * C struct field. */ class Field(val name: String, val type: Type, val offset: Long, val typeAlign: Long) val Field.isAligned: Boolean get() = offset % (typeAlign * 8) == 0L class BitField(val name: String, val type: Type, val offset: Long, val size: Int) /** * 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, val hasNaturalLayout: Boolean) { abstract val fields: List<Field> // TODO: merge two lists to preserve declaration order. abstract val bitFields: List<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 isClass: Boolean, val nsConsumesSelf: Boolean, val nsReturnsRetained: Boolean, val isOptional: Boolean, val isInit: 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 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 ConstantDef(val name: String, val type: Type) 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 GlobalDecl(val name: String, val type: Type, val isConst: Boolean) /** * C type. */ interface Type interface PrimitiveType : Type object CharType : PrimitiveType object BoolType : PrimitiveType 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 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 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
1528867012
/* * Copyright © 2017-2021 WireGuard LLC. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package com.wireguard.android.databinding import androidx.databinding.ObservableArrayList /** * ArrayList that allows looking up elements by some key property. As the key property must always * be retrievable, this list cannot hold `null` elements. Because this class places no * restrictions on the order or duplication of keys, lookup by key, as well as all list modification * operations, require O(n) time. */ open class ObservableKeyedArrayList<K, E : Keyed<out K>> : ObservableArrayList<E>() { fun containsKey(key: K) = indexOfKey(key) >= 0 operator fun get(key: K): E? { val index = indexOfKey(key) return if (index >= 0) get(index) else null } open fun indexOfKey(key: K): Int { val iterator = listIterator() while (iterator.hasNext()) { val index = iterator.nextIndex() if (iterator.next()!!.key == key) return index } return -1 } }
android5/app/wireguard-android/ui/src/main/java/com/wireguard/android/databinding/ObservableKeyedArrayList.kt
2566340464
operator fun <K, V> MutableMap<K, V>.set(k : K, v : V) = put(k, v) fun box() : String { val map = HashMap<String,String>() map["239"] = "932" return if(map["239"] == "932") "OK" else "fail" }
backend.native/tests/external/codegen/box/arrays/kt950.kt
3733481873
package net.ndrei.teslacorelib.test import net.minecraft.item.EnumDyeColor import net.minecraftforge.fluids.FluidRegistry import net.minecraftforge.fluids.IFluidTank import net.ndrei.teslacorelib.inventory.FluidTankType import net.ndrei.teslacorelib.tileentities.ElectricMachine /** * Created by CF on 2017-06-27. */ class TeslaCoreFluidsTestEntity : ElectricMachine(-1) { private lateinit var waterTank: IFluidTank private lateinit var lavaTank: IFluidTank private lateinit var tempTank: IFluidTank private lateinit var outputTank: IFluidTank //#region inventories methods override fun initializeInventories() { super.initializeInventories() this.waterTank = this.addSimpleFluidTank(5000, "Water Tank", EnumDyeColor.BLUE, 43, 25, FluidTankType.INPUT, { it.fluid === FluidRegistry.WATER }) this.lavaTank = this.addSimpleFluidTank(5000, "Lava Tank", EnumDyeColor.RED, 43 + 18, 25, FluidTankType.INPUT, { it.fluid === FluidRegistry.LAVA }) this.tempTank = this.addSimpleFluidTank(5000, "Temp Tank", EnumDyeColor.LIME, 43+18+18, 25, FluidTankType.INPUT) super.ensureFluidItems() this.outputTank = this.addSimpleFluidTank(5000, "Output Tank", EnumDyeColor.WHITE, 43 + 18 + 18 + 18 + 18, 25, FluidTankType.OUTPUT) } //#endregion override fun performWork(): Float { arrayOf(this.waterTank, this.lavaTank, this.tempTank).forEach { val drained = it.drain(100, false) if ((drained != null) && (drained.amount > 0)) { val filled = this.outputTank.fill(drained, false) if (filled > 0) { this.outputTank.fill(it.drain(filled, true), true) return 1.0f } } } return 0.0f } }
src/main/kotlin/net/ndrei/teslacorelib/test/TeslaCoreFluidsTestEntity.kt
3148643099
package au.com.codeka.warworlds.client.game.fleets import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import au.com.codeka.warworlds.client.R import au.com.codeka.warworlds.client.ctrl.ExpandableStarListAdapter import au.com.codeka.warworlds.client.game.world.EmpireManager import au.com.codeka.warworlds.client.game.world.ImageHelper import au.com.codeka.warworlds.client.game.world.StarCollection import au.com.codeka.warworlds.client.util.NumberFormatter.format import au.com.codeka.warworlds.common.proto.Design import au.com.codeka.warworlds.common.proto.Fleet import au.com.codeka.warworlds.common.proto.Star import au.com.codeka.warworlds.common.sim.DesignHelper import com.google.common.base.Preconditions import com.squareup.picasso.Picasso import java.lang.RuntimeException import java.util.* /** * Represents an [ExpandableStarListAdapter] which shows a list of fleets under each star. */ class FleetExpandableStarListAdapter(private val inflater: LayoutInflater, stars: StarCollection?) : ExpandableStarListAdapter<Fleet?>(stars!!) { private val myEmpireId: Long = EmpireManager.getMyEmpire().id private var multiSelect = false var selectedFleetId: Long? = null private set /** * Returns the currently-selected star. This will be non-null if you have one or more fleets * selected under the given star. If you have no fleets selected, or you have fleets selected * under multiple stars, this will return null. * * @return The currently-selected [Star], or null. */ var selectedStar: Star? = null private set /** A list of fleets that are currently selected, contains more than one in multi-select mode. */ private val selectedFleetIds: MutableSet<Long> = HashSet() /** A list of fleets which are currently disabled (you can't select them). */ private val disabledFleetIds: MutableSet<Long> = HashSet() fun getSelectedFleetIds(): Collection<Long> { return selectedFleetIds } /** Disable all fleets that match the given predicate. */ fun disableFleets(predicate: (Fleet) -> Boolean) { disabledFleetIds.clear() for (i in 0 until groupCount) { val star = getStar(i) for (fleet in star.fleets) { if (fleet.empire_id == myEmpireId) { if (predicate(fleet)) { disabledFleetIds.add(fleet.id) } } } } } /** After disabling fleets, this will re-enable all fleets again. */ fun enableAllFleets() { disabledFleetIds.clear() } /** * Sets whether or not we'll allow multi-select. * * * When in multi-select mode, [.getSelectedFleetId] will return the first * selected fleet, and [.getSelectedFleetIds] will return all of them. When not in * multi-select mode, [.getSelectedFleetIds] will return a list of the one selected fleet. */ fun setMultiSelect(multiSelect: Boolean) { this.multiSelect = multiSelect if (!multiSelect) { selectedFleetIds.clear() if (selectedFleetId != null) { selectedFleetIds.add(selectedFleetId!!) } } } fun setSelectedFleetId(star: Star, fleetId: Long) { selectedFleetId = fleetId selectedStar = star if (multiSelect) { selectedFleetIds.add(fleetId) } else { selectedFleetIds.clear() selectedFleetIds.add(fleetId) } notifyDataSetChanged() } fun onItemClick(groupPosition: Int, childPosition: Int) { val star = getGroup(groupPosition) val fleet = getChild(groupPosition, childPosition) selectedStar = if (selectedStar == null || selectedStar!!.id == star.id) { star } else { null } if (multiSelect) { if (!selectedFleetIds.remove(fleet!!.id)) { selectedFleetIds.add(fleet.id) } } else { selectedFleetId = fleet!!.id selectedFleetIds.clear() selectedFleetIds.add(fleet.id) } notifyDataSetChanged() } public override fun getNumChildren(star: Star?): Int { var numFleets = 0 for (i in star!!.fleets.indices) { val empireID = star.fleets[i].empire_id if (empireID == myEmpireId) { numFleets++ } } return numFleets } public override fun getChild(star: Star?, index: Int): Fleet { var fleetIndex = 0 for (i in star!!.fleets.indices) { val empireID = star.fleets[i].empire_id if (empireID == myEmpireId) { if (fleetIndex == index) { return star.fleets[i] } fleetIndex++ } } throw RuntimeException("TODO: shouldn't get here") } override fun getChildId(star: Star?, childPosition: Int): Long { return star!!.fleets[childPosition].id } public override fun getStarView(star: Star?, convertView: View?, parent: ViewGroup?): View { var view = convertView if (view == null) { view = inflater.inflate(R.layout.fleets_star_row, parent, false) } val starIcon = view!!.findViewById<ImageView>(R.id.star_icon) val starName = view.findViewById<TextView>(R.id.star_name) val starType = view.findViewById<TextView>(R.id.star_type) val fightersTotal = view.findViewById<TextView>(R.id.fighters_total) val nonFightersTotal = view.findViewById<TextView>(R.id.nonfighters_total) if (star == null) { starIcon.setImageBitmap(null) starName.text = "" starType.text = "" fightersTotal.text = "..." nonFightersTotal.text = "..." } else { Picasso.get() .load(ImageHelper.getStarImageUrl(view.context, star, 16, 16)) .into(starIcon) starName.text = star.name starType.text = star.classification.toString() val myEmpire = Preconditions.checkNotNull(EmpireManager.getMyEmpire()) var numFighters = 0.0f var numNonFighters = 0.0f for (fleet in star.fleets) { if (fleet.empire_id != myEmpire.id) { continue } if (fleet.design_type == Design.DesignType.FIGHTER) { numFighters += fleet.num_ships } else { numNonFighters += fleet.num_ships } } fightersTotal.text = String.format(Locale.ENGLISH, "%s", format(numFighters)) nonFightersTotal.text = String.format(Locale.ENGLISH, "%s", format(numNonFighters)) } return view } public override fun getChildView(star: Star?, index: Int, convertView: View?, parent: ViewGroup?): View { var view = convertView if (view == null) { view = inflater.inflate(R.layout.fleets_fleet_row, parent, false) } if (star != null) { val fleet = getChild(star, index) FleetListHelper.populateFleetRow( view as ViewGroup?, fleet, DesignHelper.getDesign(fleet.design_type)) when { disabledFleetIds.contains(fleet.id) -> { view!!.setBackgroundResource(R.color.list_item_disabled) } selectedFleetIds.contains(fleet.id) -> { view!!.setBackgroundResource(R.color.list_item_selected) } else -> { view!!.setBackgroundResource(android.R.color.transparent) } } } return view!! } }
client/src/main/kotlin/au/com/codeka/warworlds/client/game/fleets/FleetExpandableStarListAdapter.kt
210921539
package test inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block() class A { class B { class X { } companion object { class Y fun foo(n: Int) {} val bar = 1 fun Int.extFoo(n: Int) {} val Int.extBar: Int get() = 1 } object O { class Y fun foo(n: Int) {} val bar = 1 fun Int.extFoo(n: Int) {} val Int.extBar: Int get() = 1 } class <caret>C { fun test() { X() Y() foo(bar) //1.extFoo(1.extBar) // conflict O.Y() O.foo(O.bar) with (O) { Y() foo(bar) 1.extFoo(1.extBar) } } } } }
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveNestedClass/nonInnerToTopLevelClass/before/test.kt
408882460
// "Make 'First' private" "true" // ACTION: Make 'Data' public private open class Data(val x: Int) class Outer { protected class First : <caret>Data(42) }
plugins/kotlin/idea/tests/testData/quickfix/decreaseVisibility/exposedSuperClassProtectedBase.kt
4066058525
// 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.psi import com.intellij.openapi.util.TextRange import com.intellij.psi.ElementManipulators import com.intellij.testFramework.LoggedErrorProcessor import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinLightProjectDescriptor import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class StringTemplateExpressionManipulatorTest : KotlinLightCodeInsightFixtureTestCase() { fun testSingleQuoted() { doTestContentChange("\"a\"", "b", "\"b\"") doTestContentChange("\"\"", "b", "\"b\"") doTestContentChange("\"a\"", "\t", "\"\\t\"") doTestContentChange("\"a\"", "\n", "\"\\n\"") doTestContentChange("\"a\"", "\\t", "\"\\\\t\"") } fun testUnclosedQuoted() { doTestContentChange("\"a", "b", "\"b") doTestContentChange("\"", "b", "\"b") doTestContentChange("\"a", "\t", "\"\\t") doTestContentChange("\"a", "\n", "\"\\n") doTestContentChange("\"a", "\\t", "\"\\\\t") } fun testTripleQuoted() { doTestContentChange("\"\"\"a\"\"\"", "b", "\"\"\"b\"\"\"") doTestContentChange("\"\"\"\"\"\"", "b", "\"\"\"b\"\"\"") doTestContentChange("\"\"\"a\"\"\"", "\t", "\"\"\"\t\"\"\"") doTestContentChange("\"\"\"a\"\"\"", "\n", "\"\"\"\n\"\"\"") doTestContentChange("\"\"\"a\"\"\"", "\\t", "\"\"\"\\t\"\"\"") } fun testUnclosedTripleQuoted() { doTestContentChange("\"\"\"a", "b", "\"\"\"b") doTestContentChange("\"\"\"", "b", "\"\"\"b") doTestContentChange("\"\"\"a", "\t", "\"\"\"\t") doTestContentChange("\"\"\"a", "\n", "\"\"\"\n") doTestContentChange("\"\"\"a", "\\t", "\"\"\"\\t") } fun testReplaceRange() { doTestContentChange("\"abc\"", "x", range = TextRange(2, 3), expected = "\"axc\"") doTestContentChange("\"\"\"abc\"\"\"", "x", range = TextRange(4, 5), expected = "\"\"\"axc\"\"\"") doTestContentChange( "\"<div style = \\\"default\\\">\${foo(\"\")}</div>\"", "custom", range = TextRange(16, 23), expected = "\"<div style = \\\"custom\\\">\${foo(\"\")}</div>\"" ) } fun testHackyReplaceRange() { suppressFallingOnLogError { doTestContentChange("\"a\\\"bc\"", "'", range = TextRange(0, 4), expected = "'bc\"") } } fun testTemplateWithInterpolation() { doTestContentChange("\"<div>\${foo(\"\")}</div>\"", "<p>\${foo(\"\")}</p>", "\"<p>\${foo(\"\")}</p>\"") doTestContentChange( "\"<div style = \\\"default\\\">\${foo(\"\")}</div>\"", "<p style = \"custom\">\${foo(\"\")}</p>", "\"<p style = \\\"custom\\\">\${foo(\"\")}</p>\"" ) } private fun doTestContentChange(original: String, newContent: String, expected: String, range: TextRange? = null) { val expression = KtPsiFactory(project).createExpression(original) as KtStringTemplateExpression val manipulator = ElementManipulators.getNotNullManipulator(expression) val newExpression = if (range == null) manipulator.handleContentChange(expression, newContent) else manipulator.handleContentChange( expression, range, newContent ) assertEquals(expected, newExpression?.text) } override fun getProjectDescriptor() = KotlinLightProjectDescriptor.INSTANCE } private fun suppressFallingOnLogError(call: () -> Unit) { LoggedErrorProcessor.executeWith<RuntimeException>(object : LoggedErrorProcessor() { override fun processError(category: String, message: String?, t: Throwable?, details: Array<out String>): Boolean = false }) { call() } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/psi/StringTemplateExpressionManipulatorTest.kt
210572955
// 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.credentialStore.keePass import com.intellij.credentialStore.CredentialAttributes import com.intellij.credentialStore.CredentialStore import com.intellij.credentialStore.Credentials import com.intellij.credentialStore.SERVICE_NAME_PREFIX import com.intellij.credentialStore.kdbx.KeePassDatabase import com.intellij.util.text.nullize internal const val ROOT_GROUP_NAME = SERVICE_NAME_PREFIX abstract class BaseKeePassCredentialStore : CredentialStore { protected abstract val db: KeePassDatabase override fun get(attributes: CredentialAttributes): Credentials? { val group = db.rootGroup.getGroup(ROOT_GROUP_NAME) ?: return null val userName = attributes.userName.nullize() // opposite to set, on get if user name is specified, find using specified username, // otherwise, if for some reasons there are several matches by service name, incorrect result can be returned // (on get we cannot punish/judge and better to return the most correct result if possible) val entry = group.getEntry(attributes.serviceName, userName.nullize()) ?: return null return Credentials(userName ?: entry.userName, entry.password?.get()) } override fun set(attributes: CredentialAttributes, credentials: Credentials?) { if (credentials == null) { db.rootGroup.getGroup(ROOT_GROUP_NAME)?.removeEntry(attributes.serviceName, attributes.userName.nullize()) } else { val group = db.rootGroup.getOrCreateGroup(ROOT_GROUP_NAME) val userName = attributes.userName.nullize() ?: credentials.userName // should be the only credentials per service name - find without user name var entry = group.getEntry(attributes.serviceName, if (attributes.serviceName == SERVICE_NAME_PREFIX) userName else null) if (entry == null) { entry = group.createEntry(attributes.serviceName, userName) } else { entry.userName = userName } entry.password = if (attributes.isPasswordMemoryOnly || credentials.password == null) null else db.protectValue(credentials.password!!) } if (db.isDirty) { markDirty() } } protected abstract fun markDirty() }
platform/credential-store/src/keePass/BaseKeePassCredentialStore.kt
1787771721
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.preferences import android.content.SharedPreferences import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import splitties.experimental.ExperimentalSplittiesApi /** * **Requires** your project to depend on kotlinx.coroutines * * ## IMPORTANT: * Make sure that your `Preferences` subclass **constructor is private**! * * This class is meant to be a subclass of the **`companion object`** of your [Preferences] * subclass. * * It allows to always load the underlying [SharedPreferences] and its associated xml file off the * main/UI thread using **constructor-like syntax**. */ @ExperimentalSplittiesApi abstract class SuspendPrefsAccessor<out Prefs : Preferences>(prefsConstructorRef: () -> Prefs) { suspend operator fun invoke(): Prefs = if (prefDelegate.isInitialized()) { prefDelegate.value } else withContext(Dispatchers.IO) { prefDelegate.value } private val prefDelegate = lazy(prefsConstructorRef) }
modules/preferences/src/androidMain/kotlin/splitties/preferences/SuspendPrefsAccessor.kt
1271512349
// AFTER-WARNING: Variable 't' is never used class A(val n: Int) { val <caret>foo: Boolean = n > 1 } fun test() { val t = A(1).foo }
plugins/kotlin/idea/tests/testData/intentions/convertPropertyToFunction/initializer.kt
385836921
// WITH_STDLIB // WITHOUT_CUSTOM_LINE_INDENT_PROVIDER fun foo() { val v = run { <caret>foo() } print(1) }
plugins/kotlin/idea/tests/testData/editor/enterHandler/afterUnmatchedBrace/UnfinishedLambdaInCodeAsVarInitiailzer.after.kt
531824544
// 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.completion.test import com.intellij.codeInsight.completion.CodeCompletionHandlerBase import com.intellij.codeInsight.lookup.LookupManager import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.psi.PsiDocumentManager import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil import org.jetbrains.kotlin.idea.multiplatform.setupMppProjectFromDirStructure import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest import org.jetbrains.kotlin.idea.test.extractMarkerOffset import org.jetbrains.kotlin.idea.test.findFileWithCaret import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.util.slashedPath import java.io.File abstract class AbstractMultiPlatformCompletionTest : AbstractMultiModuleTest() { protected fun doTest(testPath: String) { setupMppProjectFromDirStructure(File(testPath)) val file = project.findFileWithCaret() as KtFile val doc = PsiDocumentManager.getInstance(myProject).getDocument(file)!! val offset = doc.extractMarkerOffset(project) val editor = EditorFactory.getInstance().createEditor(doc, myProject)!! editor.caretModel.moveToOffset(offset) try { testCompletion(file, editor) } finally { EditorFactory.getInstance().releaseEditor(editor) } } private fun testCompletion(file: KtFile, editor: Editor) { testCompletion(file.text, null, { completionType, invocationCount -> CodeCompletionHandlerBase(completionType).invokeCompletion( myProject, InjectedLanguageUtil .getEditorForInjectedLanguageNoCommit(editor, file), invocationCount ) val lookup = LookupManager.getActiveLookup(editor) as LookupImpl lookup.items?.toTypedArray() }) } override fun getTestDataDirectory() = COMPLETION_TEST_DATA_BASE.resolve("smartMultiFile").resolve(getTestName(false)) }
plugins/kotlin/completion/tests/test/org/jetbrains/kotlin/idea/completion/test/AbstractMultiPlatformCompletionTest.kt
2109764151
// WITH_STDLIB abstract class Owner { abstract fun <caret>f() }
plugins/kotlin/idea/tests/testData/intentions/declarations/convertMemberToExtension/abstract.kt
616842568
// 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.facet import com.intellij.facet.impl.ui.libraries.DelegatingLibrariesValidatorContext import com.intellij.facet.ui.FacetEditorContext import com.intellij.facet.ui.FacetEditorValidator import com.intellij.facet.ui.FacetValidatorsManager import org.jetbrains.kotlin.idea.facet.KotlinFacetEditorGeneralTab.EditorComponent class KotlinLibraryValidatorCreator : KotlinFacetValidatorCreator() { override fun create( editor: EditorComponent, validatorsManager: FacetValidatorsManager, editorContext: FacetEditorContext ): FacetEditorValidator = FrameworkLibraryValidatorWithDynamicDescription( DelegatingLibrariesValidatorContext(editorContext), validatorsManager, "kotlin" ) { editor.getChosenPlatform() } }
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/facet/KotlinLibraryValidatorCreator.kt
904113455
open class GFMOutputBuilder( to: StringBuilder ) : MarkdownOutputBuilder(to) { }
plugins/kotlin/idea/tests/testData/formatter/LineBreakBeforeExtendsColon.kt
4100517466
fun foo(bar: Int) { bar > 0 && 10 >= bar<caret> }
plugins/kotlin/idea/tests/testData/inspectionsLocal/convertTwoComparisonsToRangeCheck/gtgteq.kt
1368842227
package com.cn29.aac.ui.shopping.vm import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider.NewInstanceFactory import javax.inject.Inject /** * Created by Charles Ng on 23/10/2017. */ class ShoppingActivityViewModelFactory @Inject constructor() : NewInstanceFactory() { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return ShoppingActivityViewModel() as T } }
app/src/main/java/com/cn29/aac/ui/shopping/vm/ShoppingActivityViewModelFactory.kt
2953390584
package de.fabmax.kool.pipeline expect class ShaderCode { val longHash: ULong }
kool-core/src/commonMain/kotlin/de/fabmax/kool/pipeline/ShaderCode.kt
93025630
package utils import com.google.common.truth.Truth.assertThat import flank.common.isWindows import org.junit.Assert.assertEquals import java.io.File import java.math.BigDecimal const val FLANK_JAR_PATH = "../test_runner/build/libs/flank.jar" const val CONFIGS_PATH = "./src/test/resources/cases" val androidRunCommands = listOf("firebase", "test", "android", "run") val iosRunCommands = listOf("firebase", "test", "ios", "run") val multipleSuccessfulTests = listOf( "test", "testFoo", "test0", "test1", "test2", "clickRightButton[0]", "clickRightButton[1]", "clickRightButton[2]", "shouldHopefullyPass[0]", "shouldHopefullyPass[1]", "shouldHopefullyPass[2]", "clickRightButtonFromMethod(toast, toast) [0]", "clickRightButtonFromMethod(alert, alert) [1]", "clickRightButtonFromMethod(exception, exception) [2]", "clickRightButtonFromAnnotation(toast, toast) [0]", "clickRightButtonFromAnnotation(alert, alert) [1]", "clickRightButtonFromAnnotation(exception, exception) [2]", "clickRightButton[0: toast toast]", "clickRightButton[1: alert alert]", "clickRightButton[2: exception exception]" ) val multipleFailedTests = listOf( "testFoo", "test0", "test1", "test2", "testBar" ) fun assertExitCode(result: ProcessResult, expectedExitCode: Int) = assertEquals( """ Exit code: expected $expectedExitCode actual ${result.exitCode} Output: ${result.output} """.trimIndent(), expectedExitCode, result.exitCode ) @Suppress("SetterBackingFieldAssignment") data class OutcomeSummary(val matcher: MutableMap<TestOutcome, Int> = mutableMapOf<TestOutcome, Int>().withDefault { 0 }) { var success: Int = 0 set(value) { matcher[TestOutcome.SUCCESS] = value } var failure: Int = 0 set(value) { matcher[TestOutcome.FAILURE] = value } var flaky: Int = 0 set(value) { matcher[TestOutcome.FLAKY] = value } } fun assertContainsUploads(input: String, vararg uploads: String) = uploads.forEach { assertThat(input).contains("Uploading [$it]") } fun SuiteOverview.assertTestCountMatches( total: Int = 0, errors: Int = 0, failures: Int = 0, flakes: Int = 0, skipped: Int = 0, ) { assertThat(this.total).isEqualTo(total) assertThat(this.errors).isEqualTo(errors) assertThat(this.failures).isEqualTo(failures) assertThat(this.flakes).isEqualTo(flakes) assertThat(this.skipped).isEqualTo(skipped) } fun OutputReport.assertCostMatches() { assertThat(cost?.physical).isEqualToIgnoringScale(BigDecimal.ZERO) assertThat(cost?.virtual).isGreaterThan(BigDecimal.ZERO) assertThat(cost?.virtual).isEqualToIgnoringScale(cost?.total) } fun assertNoOutcomeSummary(input: String) { if ("┌[\\s\\S]*┘".toRegex().matches(input)) throw AssertionError("There should be no outcome table.") } enum class TestOutcome(val regex: Regex) { SUCCESS(fromCommon("success")), FLAKY(fromCommon("flaky")), FAILURE(fromCommon("failure")), } private val fromCommon = { outcome: String -> if (isWindows) "\\?\\s$outcome\\s\\?\\smatrix-[a-zA-Z0-9]*\\s\\?\\s*[a-zA-Z0-9._-]*\\s*\\?\\s*[a-zA-Z0-9-]*\\s*\\?\\s[a-zA-Z0-9\\s,-]*\\s*\\?".toRegex() else "│\\s$outcome\\s│\\s${"matrix"}-[a-zA-Z0-9]*\\s│\\s*[a-zA-Z0-9._-]*\\s*│\\s*[a-zA-Z0-9-]*\\s*│\\s[a-zA-Z0-9\\s,-]*\\s*│".toRegex() } fun String.removeUnicode() = replace("\u001B\\[\\d{1,2}m".toRegex(), "").trimIndent() fun findInCompare(name: String) = File("./src/test/resources/compare/$name-compare").readText().trimIndent()
integration_tests/src/test/kotlin/utils/IntergrationTestsUtils.kt
1301291413
// WITH_RUNTIME // INTENTION_TEXT: "Replace with 'filterIndexed{}.firstOrNull()'" // INTENTION_TEXT_2: "Replace with 'asSequence().filterIndexed{}.firstOrNull()'" fun foo(list: List<String>): String? { <caret>for ((index, s) in list.withIndex()) { if (s.length > index) { return s } } return null }
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/filter/filterIndexed.kt
302154565
fun test() { val test = when { <caret>1 }
plugins/kotlin/idea/tests/testData/indentationOnNewline/afterUnmatchedBrace/WhenBeforeLocalPropertyInitializer.kt
3417672344
// "Import" "true" // WITH_RUNTIME // ERROR: Unresolved reference: aaa fun test() { AAA().apply { sub { aaa<caret>() } } }
plugins/kotlin/idea/tests/testData/quickfix/autoImports/dslMarkers.before.Main.kt
27853009
fun foo(p1: Int, p2: Int, p3: Int) { val v = <caret>"a" + p1 + '\n' + p2 + '\r' + p3 + '\t' }
plugins/kotlin/idea/tests/testData/intentions/convertToStringTemplate/specialCharsInCharLiteral.kt
628531784
package com.zeke.play.view.controller import android.text.TextUtils import android.view.View import android.widget.CheckBox import android.widget.ImageView import android.widget.SeekBar import android.widget.TextView import com.kingz.utils.ktx.getSystemTime import com.module.tools.ViewUtils import com.zeke.kangaroo.utils.TimeUtils import com.zeke.module_player.R import com.zeke.play.constants.PlayMode /** * author:KingZ * date:2019/7/31 * description:底部工具栏Controller * //TODO 直播时不能拖动 * * 当前底部控制器,是包含了多种UI排列的效果,全部组件参见 * player_view_controller_basic_new.xml */ class BottomBarController(view: View) : BaseController() { private var liveTipsView: TextView? = null private var playPauseChk: CheckBox? = null private var nextImg: ImageView? = null private val seekBar: SeekBar private val currentTimeView: TextView private val durationTimeView: TextView private var qualityTxt: TextView? = null private var fullScreenImg: ImageView? = null private var playMode = PlayMode.VOD fun setPosition(position: Long) { if (isLiveMode) { seekBar.progress = 1 } else { seekBar.progress = position.toInt() currentTimeView.text = TimeUtils.generateTime(position) } } fun setDuration(duration: Long) { if (isLiveMode) { durationTimeView.text = getSystemTime() seekBar.max = 1 } else { durationTimeView.text = TimeUtils.generateTime(duration) seekBar.max = duration.toInt() } } fun onProgressUpdate(position: Long,duration: Long){ setPosition(position) setDuration(duration) //TODO 增加功能:隐藏时,是否在播放器底部显示进度条 } fun setPlayMode(@PlayMode mode: String) { playMode = mode } fun showPlayState() { playPauseChk?.isChecked = true } fun showPauseState() { playPauseChk?.isChecked = false } @Deprecated("废弃") val isInPlayState: Boolean get() = playPauseChk?.isChecked?:false fun setOnSeekBarChangeListener(listener: SeekBar.OnSeekBarChangeListener?) { seekBar.setOnSeekBarChangeListener(listener) } fun setOnClickListener(listener: View.OnClickListener?) { nextImg?.setOnClickListener(listener) qualityTxt?.setOnClickListener(listener) fullScreenImg?.setOnClickListener(listener) liveTipsView?.setOnClickListener(listener) playPauseChk?.setOnClickListener(listener) } override fun show() { // qualityTxt.setVisibility(View.GONE); if (isLiveMode) { liveTipsView?.visibility = View.VISIBLE currentTimeView.visibility = View.GONE } else { liveTipsView?.visibility = View.GONE currentTimeView.visibility = View.VISIBLE } nextImg?.visibility = View.GONE if (ViewUtils.isLandScape(rootView)) { fullScreenImg?.visibility = View.GONE } else { fullScreenImg?.visibility = View.VISIBLE } seekBar.visibility = View.VISIBLE durationTimeView.visibility = View.VISIBLE playPauseChk?.visibility = View.VISIBLE rootView.visibility = View.VISIBLE } private val isLiveMode: Boolean private get() = TextUtils.equals(playMode, PlayMode.LIVE) init { rootView = view.findViewById(R.id.player_bar_bottom) liveTipsView = rootView.findViewById(R.id.live_flag) playPauseChk = rootView.findViewById(R.id.play_pause) nextImg = rootView.findViewById(R.id.play_next) seekBar = rootView.findViewById(R.id.player_seekbar_progress) currentTimeView = rootView.findViewById(R.id.player_txt_current_time) durationTimeView = rootView.findViewById(R.id.player_txt_all_time) qualityTxt = rootView.findViewById(R.id.tv_quality) fullScreenImg = rootView.findViewById(R.id.fullscreen_icon) } }
module-Player/src/main/java/com/zeke/play/view/controller/BottomBarController.kt
2717756952
/** * Copyright 2010 - 2022 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.env import jetbrains.exodus.ExodusException import jetbrains.exodus.core.dataStructures.LongArrayList import jetbrains.exodus.crypto.newCipherProvider import jetbrains.exodus.io.DataReaderWriterProvider import jetbrains.exodus.io.FileDataWriter import jetbrains.exodus.io.LockingManager import jetbrains.exodus.io.SharedOpenFilesCache import jetbrains.exodus.log.Log import jetbrains.exodus.log.LogConfig import jetbrains.exodus.log.LogUtil import jetbrains.exodus.log.StartupMetadata import jetbrains.exodus.tree.ExpiredLoggableCollection import java.io.File import java.nio.file.Files import java.nio.file.Paths object Environments { @JvmStatic fun newInstance(dir: String, subDir: String, ec: EnvironmentConfig): Environment = prepare { EnvironmentImpl(newLogInstance(File(dir, subDir), ec), ec) } @JvmStatic fun newInstance(dir: String): Environment = newInstance(dir, EnvironmentConfig()) @JvmStatic fun newInstance(log: Log, ec: EnvironmentConfig): Environment = prepare { EnvironmentImpl(log, ec) } @JvmStatic fun newInstance(dir: String, ec: EnvironmentConfig): Environment = prepare { EnvironmentImpl(newLogInstance(File(dir), ec), ec) } @JvmStatic fun newInstance(dir: File): Environment = newInstance(dir, EnvironmentConfig()) @JvmStatic fun newInstance(dir: File, ec: EnvironmentConfig): Environment = prepare { EnvironmentImpl(newLogInstance(dir, ec), ec) } @JvmStatic fun newInstance(config: LogConfig): Environment = newInstance(config, EnvironmentConfig()) @JvmStatic fun newInstance(config: LogConfig, ec: EnvironmentConfig): Environment = prepare { EnvironmentImpl(newLogInstance(config, ec), ec) } @JvmStatic fun <T : EnvironmentImpl> newInstance(envCreator: () -> T): T = prepare(envCreator) @JvmStatic fun newContextualInstance(dir: String, subDir: String, ec: EnvironmentConfig): ContextualEnvironment = prepare { ContextualEnvironmentImpl(newLogInstance(File(dir, subDir), ec), ec) } @JvmStatic fun newContextualInstance(dir: String): ContextualEnvironment = newContextualInstance(dir, EnvironmentConfig()) @JvmStatic fun newContextualInstance(dir: String, ec: EnvironmentConfig): ContextualEnvironment = prepare { ContextualEnvironmentImpl(newLogInstance(File(dir), ec), ec) } @JvmStatic fun newContextualInstance(dir: File): ContextualEnvironment = newContextualInstance(dir, EnvironmentConfig()) @JvmStatic fun newContextualInstance(dir: File, ec: EnvironmentConfig): ContextualEnvironment = prepare { ContextualEnvironmentImpl(newLogInstance(dir, ec), ec) } @JvmStatic fun newContextualInstance(config: LogConfig, ec: EnvironmentConfig): ContextualEnvironment = prepare { ContextualEnvironmentImpl(newLogInstance(config, ec), ec) } @JvmStatic fun newLogInstance(dir: File, ec: EnvironmentConfig): Log = newLogInstance(LogConfig().setLocation(dir.path), ec) @JvmStatic fun newLogInstance(config: LogConfig, ec: EnvironmentConfig): Log { return newLogInstance(config.apply { val maxMemory = ec.memoryUsage if (maxMemory != null) { memoryUsage = maxMemory } else { memoryUsagePercentage = ec.memoryUsagePercentage } setReaderWriterProvider(ec.logDataReaderWriterProvider) if (isReadonlyReaderWriterProvider) { ec.envIsReadonly = true ec.envFailFastInReadonly = true ec.isGcEnabled = false isLockIgnored = true } fileSize = ec.logFileSize lockTimeout = ec.logLockTimeout cachePageSize = ec.logCachePageSize cacheOpenFilesCount = ec.logCacheOpenFilesCount isDurableWrite = ec.logDurableWrite isSharedCache = ec.isLogCacheShared isNonBlockingCache = ec.isLogCacheNonBlocking cacheUseSoftReferences = ec.logCacheUseSoftReferences cacheGenerationCount = ec.logCacheGenerationCount isCleanDirectoryExpected = ec.isLogCleanDirectoryExpected isClearInvalidLog = ec.isLogClearInvalid isWarmup = ec.logCacheWarmup syncPeriod = ec.logSyncPeriod isFullFileReadonly = ec.isLogFullFileReadonly cipherProvider = ec.cipherId?.let { cipherId -> newCipherProvider(cipherId) } cipherKey = ec.cipherKey cipherBasicIV = ec.cipherBasicIV setUseV1Format(ec.useVersion1Format) }) } @JvmStatic fun newLogInstance(config: LogConfig): Log = Log(config.also { SharedOpenFilesCache.setSize(config.cacheOpenFilesCount) }, EnvironmentImpl.CURRENT_FORMAT_VERSION ) private fun <T : EnvironmentImpl> prepare(envCreator: () -> T): T { var env = envCreator() val ec = env.environmentConfig val needsToBeMigrated = !env.log.formatWithHashCodeIsUsed if (ec.logDataReaderWriterProvider == DataReaderWriterProvider.DEFAULT_READER_WRITER_PROVIDER && ec.envCompactOnOpen && env.log.numberOfFiles > 1 || needsToBeMigrated ) { if (needsToBeMigrated) { EnvironmentImpl.loggerInfo( "Outdated binary format is used in environment ${env.log.location} " + "migration of binary format will be performed." ) } val location = env.location File(location, "compactTemp${System.currentTimeMillis()}").let { tempDir -> if (!tempDir.mkdir()) { EnvironmentImpl.loggerError("Failed to create temporary directory: $tempDir") return@let } if (tempDir.freeSpace < env.diskUsage) { EnvironmentImpl.loggerError("Not enough free disk space to compact the database: $location") tempDir.delete() return@let } env.copyTo(tempDir, false, null) { msg -> EnvironmentImpl.loggerInfo(msg.toString()) } val files = env.log.allFileAddresses env.close() files.forEach { fileAddress -> val file = File(location, LogUtil.getLogFilename(fileAddress)) if (!FileDataWriter.renameFile(file)) { EnvironmentImpl.loggerError("Failed to rename file: $file") return@let } } val locationPath = Paths.get(location) val firstMetadataPath = locationPath.resolve(StartupMetadata.FIRST_FILE_NAME) if (Files.exists(firstMetadataPath)) { val delFirstMetadataPath = locationPath.resolve( StartupMetadata.FIRST_FILE_NAME + FileDataWriter.DELETED_FILE_EXTENSION ) Files.move(firstMetadataPath, delFirstMetadataPath) } val secondMetadataPath = locationPath.resolve(StartupMetadata.SECOND_FILE_NAME) if (Files.exists(secondMetadataPath)) { val delSecondMetadataPath = locationPath.resolve( StartupMetadata.SECOND_FILE_NAME + FileDataWriter.DELETED_FILE_EXTENSION ) Files.move(firstMetadataPath, delSecondMetadataPath) } LogUtil.listFiles(tempDir).forEach { file -> if (!file.renameTo(File(location, file.name))) { throw ExodusException("Failed to rename file: $file") } } LogUtil.listMetadataFiles(tempDir).forEach { file -> if (!file.renameTo(File(location, file.name))) { throw ExodusException("Failed to rename file: $file") } } Files.deleteIfExists(Paths.get(tempDir.toURI()).resolve(LockingManager.LOCK_FILE_NAME)) env = envCreator() if (needsToBeMigrated) { EnvironmentImpl.loggerInfo( "Migration of binary format in environment ${env.log.location}" + " has been completed. Please delete all files with extension " + "*.del once you ensure database consistency." ) } tempDir.delete() } } if (env.log.isClossedCorrectly) { if (env.log.formatWithHashCodeIsUsed) { env.gc.utilizationProfile.load() val rootAddress = env.metaTree.rootAddress() val rootLoggable = env.log.read(rootAddress) //once we close the log, the rest of the page is padded with null loggables //this free space should be taken into account during next open val paddedSpace = env.log.dataSpaceLeftInPage(rootAddress) val expiredLoggableCollection = ExpiredLoggableCollection() expiredLoggableCollection.add(rootLoggable.end(), paddedSpace) env.gc.utilizationProfile.fetchExpiredLoggables(expiredLoggableCollection) } } else { EnvironmentImpl.loggerInfo( "Because environment ${env.log.location} was closed incorrectly space utilization " + "will be computed from scratch" ) env.gc.utilizationProfile.computeUtilizationFromScratch() EnvironmentImpl.loggerInfo("Computation of space utilization for environment ${env.log.location} is completed") } val metaServer = ec.metaServer metaServer?.start(env) return env } }
environment/src/main/kotlin/jetbrains/exodus/env/Environments.kt
978114008
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package nanovg.templates import org.lwjgl.generator.* import nanovg.* import java.io.* val nanovg_bgfx = "NanoVGBGFX".dependsOn(Module.BGFX)?.nativeClass(Module.NANOVG, prefix = "NVG", binding = object : SimpleBinding(Module.NANOVG, "BGFX.getLibrary()") { override fun PrintWriter.generateFunctionSetup(nativeClass: NativeClass) { generateFunctionsClass(nativeClass, "\n$t/** Contains the function pointers loaded from bgfx. */") } }) { documentation = "Implementation of the NanoVG API using bgfx." javaImport("static org.lwjgl.nanovg.NanoVG.*") NVGcontext.p( "Create", "", int32_tb("_edgeaa", ""), MapToInt..ViewId("_viewId", ""), nullable..AllocatorI("_allocator", "") ) void( "Delete", "", NVGcontext.p("_ctx", "") ) void( "SetViewId", "", NVGcontext.p("_ctx", ""), MapToInt..ViewId("_viewId", "") ) uint16_t( "GetViewId", "", NVGcontext.p("_ctx", "") ) NVGLUframebufferBGFX.p( "luCreateFramebuffer", "", NVGcontext.p("_ctx", ""), int32_t("_width", ""), int32_t("_height", ""), int32_t("imageFlags", "") ) void( "luBindFramebuffer", "", Input..nullable..NVGLUframebufferBGFX.p("_framebuffer", "") ) void( "luDeleteFramebuffer", "", Input..NVGLUframebufferBGFX.p("_framebuffer", "") ) void( "luSetViewFramebuffer", "", MapToInt..ViewId("_view_id", ""), Input..NVGLUframebufferBGFX.p("_framebuffer", "") ) void( "CreateBgfxTexture", "", NVGcontext.p("_ctx", ""), TextureHandle("_id", ""), int("_width", ""), int("_height", ""), int("flags", "") ) // BGFX/NanoVG integration // 1. Make the bgfx back-end use LWJGL's allocation functions, which are also internally used by NanoVG. // 2. Pass NanoVG's internal functions to the bgfx back-end. private..void( "org_lwjgl_nanovg_setup", "", opaque_p("realloc", ""), opaque_p("free", ""), opaque_p("nvgCreateInternal", ""), opaque_p("nvgInternalParams", ""), opaque_p("nvgDeleteInternal", ""), noPrefix = true ) customMethod(""" static { MemoryAllocator allocator = getAllocator(Configuration.DEBUG_MEMORY_ALLOCATOR_INTERNAL.get(true)); org_lwjgl_nanovg_setup( allocator.getRealloc(), allocator.getFree(), nvgCreateInternal, nvgInternalParams, nvgDeleteInternal ); }""") customMethod(""" private static class BGFX { private static final SharedLibrary library; static { try { library = (SharedLibrary)Class.forName("org.lwjgl.bgfx.BGFX").getMethod("getLibrary").invoke(null); } catch (Exception e) { throw new RuntimeException(e); } } static SharedLibrary getLibrary() { return library; } } """) }
modules/lwjgl/nanovg/src/templates/kotlin/nanovg/templates/nanovg_bgfx.kt
332895905
package com.github.kerubistan.kerub.planner.steps.vm.migrate.kvm import com.fasterxml.jackson.annotation.JsonTypeName import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.VirtualMachine import com.github.kerubistan.kerub.model.expectations.NoMigrationExpectation import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.costs.ComputationCost import com.github.kerubistan.kerub.planner.costs.Cost import com.github.kerubistan.kerub.planner.costs.NetworkCost import com.github.kerubistan.kerub.planner.costs.Risk import com.github.kerubistan.kerub.planner.reservations.Reservation import com.github.kerubistan.kerub.planner.reservations.UseHostReservation import com.github.kerubistan.kerub.planner.reservations.VmReservation import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStep import com.github.kerubistan.kerub.planner.steps.InvertibleStep import com.github.kerubistan.kerub.planner.steps.vm.migrate.MigrateVirtualMachine import com.github.kerubistan.kerub.utils.any import io.github.kerubistan.kroki.collections.update import java.math.BigInteger @JsonTypeName("kvm-migrate-vm") data class KvmMigrateVirtualMachine( override val vm: VirtualMachine, override val source: Host, override val target: Host ) : AbstractOperationalStep, MigrateVirtualMachine, InvertibleStep { override fun isInverseOf(other: AbstractOperationalStep) = other is KvmMigrateVirtualMachine && other.vm == vm && other.source == target && other.target == source override fun reservations(): List<Reservation<*>> = listOf( VmReservation(vm), UseHostReservation(target), UseHostReservation(source) ) override fun take(state: OperationalState): OperationalState { val vmDyn = requireNotNull(state.vms[vm.id]?.dynamic) val targetHostDyn = requireNotNull(state.hosts[target.id]?.dynamic) val sourceHostDyn = requireNotNull(state.hosts[source.id]?.dynamic) return state.copy( vms = state.vms.update(vm.id) { it.copy( dynamic = vmDyn.copy( hostId = target.id ) ) }, hosts = state.hosts .update(target.id) { it.copy( dynamic = targetHostDyn.copy( memFree = sourceHostDyn.memFree!! + vmDyn.memoryUsed, memUsed = (sourceHostDyn.memUsed ?: BigInteger.ZERO - vmDyn.memoryUsed) .coerceAtLeast(BigInteger.ZERO) ) ) } .update(source.id) { it.copy( dynamic = sourceHostDyn.copy( memFree = sourceHostDyn.memFree!! + vmDyn.memoryUsed, memUsed = (sourceHostDyn.memUsed ?: BigInteger.ZERO - vmDyn.memoryUsed) .coerceAtLeast(BigInteger.ZERO) ) ) } ) } override fun getCost(): List<Cost> = listOf( /* * TODO * This calculates cost based on the max, which is pessimistic * rather than realistic. */ NetworkCost( hosts = listOf(source, target), bytes = vm.memory.max.toLong() ), ComputationCost( host = target, cycles = vm.memory.max.toLong() ), ComputationCost( host = source, cycles = vm.memory.max.toLong() ) ) + if (vm.expectations.any<NoMigrationExpectation>()) { // TODO: hmm, do I want to have this logic here? NoMigrationExpectationViolationDetector detects the problem listOf(Risk(1000, comment = "broken no-migration rule")) } else { listOf<Cost>() } }
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/vm/migrate/kvm/KvmMigrateVirtualMachine.kt
698911079
// 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.testGenerator.generator import com.intellij.testFramework.TestDataPath import org.jetbrains.kotlin.idea.artifacts.AdditionalKotlinArtifacts import org.jetbrains.kotlin.test.* import org.jetbrains.kotlin.testGenerator.model.* import org.junit.runner.RunWith import org.jetbrains.kotlin.idea.test.JUnit3RunnerWithInners import org.jetbrains.kotlin.idea.test.KotlinTestUtils import org.jetbrains.kotlin.idea.test.TestRoot import java.io.File import java.util.* object TestGenerator { private val commonImports = importsListOf( TestDataPath::class, JUnit3RunnerWithInners::class, KotlinTestUtils::class, TestMetadata::class, TestRoot::class, RunWith::class ) fun write(workspace: TWorkspace) { for (group in workspace.groups) { for (suite in group.suites) { write(suite, group) } } } private fun write(suite: TSuite, group: TGroup) { val packageName = suite.generatedClassName.substringBeforeLast('.') val rootModelName = suite.generatedClassName.substringAfterLast('.') val content = buildCode { appendCopyrightComment() newLine() appendLine("package $packageName;") newLine() appendImports(getImports(suite, group)) appendGeneratedComment() appendAnnotation(TAnnotation<SuppressWarnings>("all")) appendAnnotation(TAnnotation<TestRoot>(group.modulePath)) appendAnnotation(TAnnotation<TestDataPath>("\$CONTENT_ROOT")) val singleModel = suite.models.singleOrNull() if (singleModel != null) { append(SuiteElement.create(group, suite, singleModel, rootModelName, isNested = false)) } else { appendAnnotation(TAnnotation<RunWith>(JUnit3RunnerWithInners::class.java)) appendBlock("public abstract class $rootModelName extends ${suite.abstractTestClass.simpleName}") { val children = suite.models .map { SuiteElement.create(group, suite, it, it.testClassName, isNested = true) } appendList(children, separator = "\n\n") } } newLine() } val filePath = suite.generatedClassName.replace('.', '/') + ".java" val file = File(group.testSourcesRoot, filePath) write(file, postProcessContent(content)) } private fun write(file: File, content: String) { val oldContent = file.takeIf { it.isFile }?.readText() ?: "" if (normalizeContent(content) != normalizeContent(oldContent)) { file.writeText(content) val path = file.toRelativeStringSystemIndependent(KotlinRoot.DIR) println("Updated $path") } } private fun normalizeContent(content: String): String = content.replace(Regex("\\R"), "\n") private fun getImports(suite: TSuite, group: TGroup): List<String> { val imports = (commonImports + suite.imports).toMutableList() if (suite.models.any { it.targetBackend != TargetBackend.ANY }) { imports += importsListOf(TargetBackend::class) } val superPackageName = suite.abstractTestClass.`package`.name val selfPackageName = suite.generatedClassName.substringBeforeLast('.') if (superPackageName != selfPackageName) { imports += importsListOf(suite.abstractTestClass.kotlin) } if (group.isCompilerTestData) { imports += "static ${AdditionalKotlinArtifacts::class.java.canonicalName}.${AdditionalKotlinArtifacts::compilerTestData.name}" } return imports } private fun postProcessContent(text: String): String { return text.lineSequence() .map { it.trimEnd() } .joinToString(System.getProperty("line.separator")) } private fun Code.appendImports(imports: List<String>) { if (imports.isNotEmpty()) { imports.forEach { appendLine("import $it;") } newLine() } } private fun Code.appendCopyrightComment() { val year = GregorianCalendar()[Calendar.YEAR] appendLine("// Copyright 2000-$year JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.") } private fun Code.appendGeneratedComment() { appendDocComment(""" This class is generated by {@link org.jetbrains.kotlin.testGenerator.generator.TestGenerator}. DO NOT MODIFY MANUALLY. """.trimIndent()) } }
plugins/kotlin/generators/test/org/jetbrains/kotlin/testGenerator/generator/TestGenerator.kt
3694488267
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.backend.konan.lower import org.jetbrains.kotlin.backend.common.lower.* import org.jetbrains.kotlin.backend.common.* import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.builders.* import org.jetbrains.kotlin.ir.declarations.impl.IrVariableImpl import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.impl.* import org.jetbrains.kotlin.ir.symbols.IrReturnTargetSymbol import org.jetbrains.kotlin.ir.symbols.IrReturnableBlockSymbol import org.jetbrains.kotlin.ir.symbols.impl.IrReturnableBlockSymbolImpl import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.builders.irGet import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl import org.jetbrains.kotlin.ir.symbols.impl.IrVariableSymbolImpl import org.jetbrains.kotlin.ir.types.IrSimpleType import org.jetbrains.kotlin.ir.util.SYNTHETIC_OFFSET import org.jetbrains.kotlin.ir.util.defaultType import org.jetbrains.kotlin.ir.util.setDeclarationsParent import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid import org.jetbrains.kotlin.name.Name internal class FinallyBlocksLowering(val context: Context): FileLoweringPass, IrElementTransformerVoidWithContext() { private val symbols = context.ir.symbols private interface HighLevelJump { fun toIr(context: Context, startOffset: Int, endOffset: Int, value: IrExpression): IrExpression } private data class Return(val target: IrReturnTargetSymbol): HighLevelJump { override fun toIr(context: Context, startOffset: Int, endOffset: Int, value: IrExpression) = IrReturnImpl(startOffset, endOffset, context.irBuiltIns.nothingType, target, value) } private data class Break(val loop: IrLoop): HighLevelJump { override fun toIr(context: Context, startOffset: Int, endOffset: Int, value: IrExpression) = IrBlockImpl(startOffset, endOffset, context.irBuiltIns.nothingType, null, statements = listOf( value, IrBreakImpl(startOffset, endOffset, context.irBuiltIns.nothingType, loop) )) } private data class Continue(val loop: IrLoop): HighLevelJump { override fun toIr(context: Context, startOffset: Int, endOffset: Int, value: IrExpression) = IrBlockImpl(startOffset, endOffset, context.irBuiltIns.nothingType, null, statements = listOf( value, IrContinueImpl(startOffset, endOffset, context.irBuiltIns.nothingType, loop) )) } private abstract class Scope private class ReturnableScope(val symbol: IrReturnTargetSymbol): Scope() private class LoopScope(val loop: IrLoop): Scope() private class TryScope(var expression: IrExpression, val finallyExpression: IrExpression, val irBuilder: IrBuilderWithScope): Scope() { val jumps = mutableMapOf<HighLevelJump, IrReturnTargetSymbol>() } private val scopeStack = mutableListOf<Scope>() private inline fun <S: Scope, R> using(scope: S, block: (S) -> R): R { scopeStack.push(scope) try { return block(scope) } finally { scopeStack.pop() } } override fun lower(irFile: IrFile) { irFile.transformChildrenVoid(this) } override fun visitFunctionNew(declaration: IrFunction): IrStatement { using(ReturnableScope(declaration.symbol)) { return super.visitFunctionNew(declaration) } } override fun visitContainerExpression(expression: IrContainerExpression): IrExpression { if (expression !is IrReturnableBlock) return super.visitContainerExpression(expression) using(ReturnableScope(expression.symbol)) { return super.visitContainerExpression(expression) } } override fun visitLoop(loop: IrLoop): IrExpression { using(LoopScope(loop)) { return super.visitLoop(loop) } } override fun visitBreak(jump: IrBreak): IrExpression { val startOffset = jump.startOffset val endOffset = jump.endOffset val irBuilder = context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, startOffset, endOffset) return performHighLevelJump( targetScopePredicate = { it is LoopScope && it.loop == jump.loop }, jump = Break(jump.loop), startOffset = startOffset, endOffset = endOffset, value = irBuilder.irGetObject(context.ir.symbols.unit) ) ?: jump } override fun visitContinue(jump: IrContinue): IrExpression { val startOffset = jump.startOffset val endOffset = jump.endOffset val irBuilder = context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, startOffset, endOffset) return performHighLevelJump( targetScopePredicate = { it is LoopScope && it.loop == jump.loop }, jump = Continue(jump.loop), startOffset = startOffset, endOffset = endOffset, value = irBuilder.irGetObject(context.ir.symbols.unit) ) ?: jump } override fun visitReturn(expression: IrReturn): IrExpression { expression.transformChildrenVoid(this) return performHighLevelJump( targetScopePredicate = { it is ReturnableScope && it.symbol == expression.returnTargetSymbol }, jump = Return(expression.returnTargetSymbol), startOffset = expression.startOffset, endOffset = expression.endOffset, value = expression.value ) ?: expression } private fun performHighLevelJump(targetScopePredicate: (Scope) -> Boolean, jump: HighLevelJump, startOffset: Int, endOffset: Int, value: IrExpression): IrExpression? { val tryScopes = scopeStack.reversed() .takeWhile { !targetScopePredicate(it) } .filterIsInstance<TryScope>() .toList() if (tryScopes.isEmpty()) return null return performHighLevelJump(tryScopes, 0, jump, startOffset, endOffset, value) } private val IrReturnTarget.returnType: IrType get() = when (this) { is IrConstructor -> context.irBuiltIns.unitType is IrFunction -> returnType is IrReturnableBlock -> type else -> error("Unknown ReturnTarget: $this") } private fun performHighLevelJump(tryScopes: List<TryScope>, index: Int, jump: HighLevelJump, startOffset: Int, endOffset: Int, value: IrExpression): IrExpression { if (index == tryScopes.size) return jump.toIr(context, startOffset, endOffset, value) val currentTryScope = tryScopes[index] currentTryScope.jumps.getOrPut(jump) { val type = (jump as? Return)?.target?.owner?.returnType ?: value.type val symbol = IrReturnableBlockSymbolImpl() with(currentTryScope) { irBuilder.run { val inlinedFinally = irInlineFinally(symbol, type, expression, finallyExpression) expression = performHighLevelJump( tryScopes = tryScopes, index = index + 1, jump = jump, startOffset = startOffset, endOffset = endOffset, value = inlinedFinally) } } symbol }.let { return IrReturnImpl( startOffset = startOffset, endOffset = endOffset, type = context.irBuiltIns.nothingType, returnTargetSymbol = it, value = value) } } override fun visitTry(aTry: IrTry): IrExpression { val finallyExpression = aTry.finallyExpression ?: return super.visitTry(aTry) val startOffset = aTry.startOffset val endOffset = aTry.endOffset val irBuilder = context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, startOffset, endOffset) val transformer = this irBuilder.run { val transformedTry = IrTryImpl( startOffset = startOffset, endOffset = endOffset, type = context.irBuiltIns.nothingType ) val transformedFinallyExpression = finallyExpression.transform(transformer, null) val catchParameter = IrVariableImpl( startOffset, endOffset, IrDeclarationOrigin.CATCH_PARAMETER, IrVariableSymbolImpl(), Name.identifier("t"), symbols.throwable.owner.defaultType, isVar = false, isConst = false, isLateinit = false ).apply { parent = [email protected] } val syntheticTry = IrTryImpl( startOffset = startOffset, endOffset = endOffset, type = context.irBuiltIns.nothingType, tryResult = transformedTry, catches = listOf( irCatch(catchParameter, irBlock { +copy(finallyExpression) +irThrow(irGet(catchParameter)) }) ), finallyExpression = null ) using(TryScope(syntheticTry, transformedFinallyExpression, this)) { val fallThroughType = aTry.type val fallThroughSymbol = IrReturnableBlockSymbolImpl() val transformedResult = aTry.tryResult.transform(transformer, null) transformedTry.tryResult = irReturn(fallThroughSymbol, transformedResult) for (aCatch in aTry.catches) { val transformedCatch = aCatch.transform(transformer, null) transformedCatch.result = irReturn(fallThroughSymbol, transformedCatch.result) transformedTry.catches.add(transformedCatch) } return irInlineFinally(fallThroughSymbol, fallThroughType, it.expression, it.finallyExpression) } } } private fun IrBuilderWithScope.irInlineFinally(symbol: IrReturnableBlockSymbol, type: IrType, value: IrExpression, finallyExpression: IrExpression): IrExpression { val returnTypeClassifier = (type as? IrSimpleType)?.classifier return when (returnTypeClassifier) { symbols.unit, symbols.nothing -> irBlock(value, null, type) { +irReturnableBlock(finallyExpression.startOffset, finallyExpression.endOffset, symbol, type) { +value } +copy(finallyExpression) } else -> irBlock(value, null, type) { val tmp = irTemporary(irReturnableBlock(finallyExpression.startOffset, finallyExpression.endOffset, symbol, type) { +irReturn(symbol, value) }) +copy(finallyExpression) +irGet(tmp) } } } private inline fun <reified T : IrElement> IrBuilderWithScope.copy(element: T) = element.deepCopyWithVariables().setDeclarationsParent(parent) fun IrBuilderWithScope.irReturn(target: IrReturnTargetSymbol, value: IrExpression) = IrReturnImpl(startOffset, endOffset, context.irBuiltIns.nothingType, target, value) private inline fun IrBuilderWithScope.irReturnableBlock(startOffset: Int, endOffset: Int, symbol: IrReturnableBlockSymbol, type: IrType, body: IrBlockBuilder.() -> Unit) = IrReturnableBlockImpl(startOffset, endOffset, type, symbol, null, IrBlockBuilder(context, scope, startOffset, endOffset, null, type) .block(body).statements) }
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/FinallyBlocksLowering.kt
1557227841
interface <info textAttributesKey="KOTLIN_TRAIT">TheInterface</info> { } class <info textAttributesKey="KOTLIN_CLASS">TheClass</info> : <info textAttributesKey="KOTLIN_TRAIT">TheInterface</info> { } <info textAttributesKey="KOTLIN_BUILTIN_ANNOTATION">annotation</info> class <info textAttributesKey="KOTLIN_ANNOTATION">magnificent</info> <info textAttributesKey="KOTLIN_BUILTIN_ANNOTATION">annotation</info> class <info textAttributesKey="KOTLIN_ANNOTATION">Deprecated</info> <info textAttributesKey="KOTLIN_ANNOTATION">@Deprecated</info> <info textAttributesKey="KOTLIN_ANNOTATION">@magnificent</info> <info textAttributesKey="KOTLIN_BUILTIN_ANNOTATION">abstract</info> class <info textAttributesKey="KOTLIN_ABSTRACT_CLASS">AbstractClass</info><<info textAttributesKey="KOTLIN_TYPE_PARAMETER">T</info>> { }
plugins/kotlin/idea/tests/testData/highlighter/TypesAndAnnotations.kt
4150359988
/* * 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.camera.testing import androidx.test.espresso.Espresso import androidx.test.espresso.IdlingRegistry import androidx.test.espresso.IdlingResource fun IdlingResource?.waitForIdle() { if (this != null) { IdlingRegistry.getInstance().register(this) Espresso.onIdle() IdlingRegistry.getInstance().unregister(this) } }
camera/camera-testing/src/main/java/androidx/camera/testing/IdlingResourceUtil.kt
731659172
/* * 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.metrics.performance.janktest import android.content.Context import android.graphics.Canvas import android.util.AttributeSet import android.view.View /** * This custom view is used to inject an artificial, random delay during drawing, to simulate * jank on the UI thread. */ class MyCustomView : View { constructor(context: Context?) : super(context) {} constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {} constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) override fun onDraw(canvas: Canvas) { /** * Inject random delay to cause jank in the app. * For any given item, there should be a 30% chance of jank (>32ms), and a 2% chance of * extreme jank (>500ms). * Regular jank will be between 32 and 82ms, extreme from 500-700ms. */ val probability = Math.random() if (probability > .7) { val delay: Long delay = if (probability > .98) { 500 + (Math.random() * 200).toLong() } else { 32 + (Math.random() * 50).toLong() } try { Thread.sleep(delay) } catch (e: Exception) { } } super.onDraw(canvas) } }
metrics/integration-tests/janktest/src/main/java/androidx/metrics/performance/janktest/MyCustomView.kt
3479156103
package domain.recommendation data class DomainRecommendationPhoto( val id: String, val url: String, val processedFiles: Iterable<DomainRecommendationProcessedFile>) { companion object { val NONE = DomainRecommendationPhoto("", "", emptySet()) } }
domain/src/main/kotlin/domain/recommendation/DomainRecommendationPhoto.kt
947555824
package com.sedsoftware.yaptalker.presentation.base.enums.lifecycle import androidx.annotation.LongDef class FragmentLifecycle { companion object { const val ATTACH = 0L const val CREATE = 1L const val START = 2L const val RESUME = 3L const val PAUSE = 4L const val STOP = 5L const val DESTROY = 6L const val DETACH = 7L } @Retention(AnnotationRetention.SOURCE) @LongDef(ATTACH, CREATE, START, RESUME, PAUSE, STOP, DESTROY, DETACH) annotation class Event }
app/src/main/java/com/sedsoftware/yaptalker/presentation/base/enums/lifecycle/FragmentLifecycle.kt
2023524819
/* * 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.collection import kotlin.DeprecationLevel.HIDDEN /** Returns the number of key/value pairs in the collection. */ public inline val <T> SparseArrayCompat<T>.size: Int get() = size() /** Returns true if the collection contains [key]. */ @Suppress("NOTHING_TO_INLINE") public inline operator fun <T> SparseArrayCompat<T>.contains(key: Int): Boolean = containsKey(key) /** Allows the use of the index operator for storing values in the collection. */ @Suppress("NOTHING_TO_INLINE") public inline operator fun <T> SparseArrayCompat<T>.set(key: Int, value: T): Unit = put(key, value) /** Creates a new collection by adding or replacing entries from [other]. */ public operator fun <T> SparseArrayCompat<T>.plus( other: SparseArrayCompat<T> ): SparseArrayCompat<T> { val new = SparseArrayCompat<T>(size() + other.size()) new.putAll(this) new.putAll(other) return new } /** Return the value corresponding to [key], or [defaultValue] when not present. */ @Suppress("NOTHING_TO_INLINE") public inline fun <T> SparseArrayCompat<T>.getOrDefault(key: Int, defaultValue: T): T = get(key, defaultValue) /** Return the value corresponding to [key], or from [defaultValue] when not present. */ public inline fun <T> SparseArrayCompat<T>.getOrElse(key: Int, defaultValue: () -> T): T = get(key) ?: defaultValue() /** Return true when the collection contains elements. */ @Suppress("NOTHING_TO_INLINE") public inline fun <T> SparseArrayCompat<T>.isNotEmpty(): Boolean = !isEmpty() /** Removes the entry for [key] only if it is mapped to [value]. */ @Suppress("EXTENSION_SHADOWED_BY_MEMBER") // Binary API compatibility. @Deprecated("Replaced with member function. Remove extension import!", level = HIDDEN) public fun <T> SparseArrayCompat<T>.remove(key: Int, value: T): Boolean = remove(key, value) /** Performs the given [action] for each key/value entry. */ public inline fun <T> SparseArrayCompat<T>.forEach(action: (key: Int, value: T) -> Unit) { for (index in 0 until size()) { action(keyAt(index), valueAt(index)) } } /** Return an iterator over the collection's keys. */ public fun <T> SparseArrayCompat<T>.keyIterator(): IntIterator = object : IntIterator() { var index = 0 override fun hasNext() = index < size() override fun nextInt() = keyAt(index++) } /** Return an iterator over the collection's values. */ public fun <T> SparseArrayCompat<T>.valueIterator(): Iterator<T> = object : Iterator<T> { var index = 0 override fun hasNext() = index < size() override fun next() = valueAt(index++) }
collection/collection/src/commonMain/kotlin/androidx/collection/SparseArray.kt
522321987
package com.sedsoftware.yaptalker.presentation.feature.blacklist import com.arellomobile.mvp.InjectViewState import com.sedsoftware.yaptalker.data.system.SchedulersProvider import com.sedsoftware.yaptalker.domain.interactor.BlacklistInteractor import com.sedsoftware.yaptalker.presentation.base.BasePresenter import com.sedsoftware.yaptalker.presentation.base.enums.lifecycle.PresenterLifecycle import com.sedsoftware.yaptalker.presentation.feature.blacklist.adapter.BlacklistElementsClickListener import com.sedsoftware.yaptalker.presentation.mapper.BlacklistTopicModelMapper import com.uber.autodispose.kotlin.autoDisposable import timber.log.Timber import javax.inject.Inject @InjectViewState class BlacklistPresenter @Inject constructor( private val blacklistInteractor: BlacklistInteractor, private val topicsMapper: BlacklistTopicModelMapper, private val schedulers: SchedulersProvider ) : BasePresenter<BlacklistView>(), BlacklistElementsClickListener { override fun onFirstViewAttach() { super.onFirstViewAttach() loadBlacklist() } override fun attachView(view: BlacklistView?) { super.attachView(view) viewState.updateCurrentUiState() } override fun onDeleteIconClick(topicId: Int) { viewState.showDeleteConfirmationDialog(topicId) } fun deleteTopicFromBlacklist(topicId: Int) { blacklistInteractor .removeTopicFromBlacklistById(topicId) .observeOn(schedulers.ui()) .autoDisposable(event(PresenterLifecycle.DESTROY)) .subscribe({ Timber.i("Topic deleted from blacklist") loadBlacklist() }, { e: Throwable -> e.message?.let { viewState.showErrorMessage(it) } }) } fun clearBlacklist() { blacklistInteractor .clearTopicsBlacklist() .observeOn(schedulers.ui()) .autoDisposable(event(PresenterLifecycle.DESTROY)) .subscribe({ Timber.i("Blacklist cleared") loadBlacklist() }, { e: Throwable -> e.message?.let { viewState.showErrorMessage(it) } }) } fun clearBlacklistMonthOld() { blacklistInteractor .clearMonthOldTopicsBlacklist() .observeOn(schedulers.ui()) .autoDisposable(event(PresenterLifecycle.DESTROY)) .subscribe({ Timber.i("Month old topics cleared") loadBlacklist() }, { e: Throwable -> e.message?.let { viewState.showErrorMessage(it) } }) } private fun loadBlacklist() { blacklistInteractor .getBlacklistedTopics() .map(topicsMapper) .observeOn(schedulers.ui()) .autoDisposable(event(PresenterLifecycle.DESTROY)) .subscribe({ topics -> viewState.showBlacklistedTopics(topics) }, { e: Throwable -> e.message?.let { viewState.showErrorMessage(it) } }) } }
app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/blacklist/BlacklistPresenter.kt
4279575947
/* * 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.camera.camera2.pipe.integration.interop import android.annotation.SuppressLint import android.hardware.camera2.CameraCaptureSession import android.hardware.camera2.CameraCaptureSession.CaptureCallback import android.hardware.camera2.CameraDevice import android.hardware.camera2.CaptureRequest import androidx.annotation.RequiresApi import androidx.annotation.RestrictTo import androidx.camera.camera2.pipe.integration.impl.DEVICE_STATE_CALLBACK_OPTION import androidx.camera.camera2.pipe.integration.impl.SESSION_CAPTURE_CALLBACK_OPTION import androidx.camera.camera2.pipe.integration.impl.SESSION_PHYSICAL_CAMERA_ID_OPTION import androidx.camera.camera2.pipe.integration.impl.SESSION_STATE_CALLBACK_OPTION import androidx.camera.camera2.pipe.integration.impl.TEMPLATE_TYPE_OPTION import androidx.camera.camera2.pipe.integration.impl.createCaptureRequestOption import androidx.camera.core.ExtendableBuilder import androidx.camera.core.impl.Config /** * Utilities related to interoperability with the [android.hardware.camera2] APIs. * * @constructor Private constructor to ensure this class isn't instantiated. */ @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java @ExperimentalCamera2Interop class Camera2Interop private constructor() { /** * Extends a [ExtendableBuilder] to add Camera2 options. * * @param T the type being built by the extendable builder. * @property baseBuilder The builder being extended. * @constructor Creates an Extender that can be used to add Camera2 options to another Builder. */ @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java class Extender<T> (private var baseBuilder: ExtendableBuilder<T>) { /** * Sets a [CaptureRequest.Key] and Value on the configuration. * * The value will override any value set by CameraX internally with the risk of * interfering with some CameraX CameraControl APIs as well as 3A behavior. * * @param key The [CaptureRequest.Key] which will be set. * @param value The value for the key. * @param ValueT The type of the value. * @return The current Extender. */ fun <ValueT> setCaptureRequestOption( key: CaptureRequest.Key<ValueT>, value: ValueT ): Extender<T> { // Reify the type so we can obtain the class val opt = key.createCaptureRequestOption() baseBuilder.mutableConfig.insertOption( opt, Config.OptionPriority.ALWAYS_OVERRIDE, value ) return this } /** * Sets a CameraDevice template on the given configuration. * * See [CameraDevice] for valid template types. For example, * [CameraDevice.TEMPLATE_PREVIEW]. * * Only used by [androidx.camera.core.ImageCapture] to set the template type * used. For all other [androidx.camera.core.UseCase] this value is ignored. * * @param templateType The template type to set. * @return The current Extender. * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY) fun setCaptureRequestTemplate(templateType: Int): Extender<T> { baseBuilder.mutableConfig.insertOption( TEMPLATE_TYPE_OPTION, templateType ) return this } /** * Sets a [CameraDevice.StateCallback]. * * The caller is expected to use the [CameraDevice] instance accessed through the * callback methods responsibly. Generally safe usages include: (1) querying the device for * its id, (2) using the callbacks to determine what state the device is currently in. * Generally unsafe usages include: (1) creating a new [CameraCaptureSession], (2) * creating a new [CaptureRequest], (3) closing the device. When the caller uses the * device beyond the safe usage limits, the usage may still work in conjunction with * CameraX, but any strong guarantees provided by CameraX about the validity of the camera * state become void. * * @param stateCallback The [CameraDevice.StateCallback]. * @return The current Extender. */ @SuppressLint("ExecutorRegistration") fun setDeviceStateCallback( stateCallback: CameraDevice.StateCallback ): Extender<T> { baseBuilder.mutableConfig.insertOption( DEVICE_STATE_CALLBACK_OPTION, stateCallback ) return this } /** * Sets a [CameraCaptureSession.StateCallback]. * * The caller is expected to use the [CameraCaptureSession] instance accessed * through the callback methods responsibly. Generally safe usages include: (1) querying the * session for its properties, (2) using the callbacks to determine what state the session * is currently in. Generally unsafe usages include: (1) submitting a new * [CameraCaptureSession], (2) stopping an existing [CaptureRequest], (3) closing the * session, (4) attaching a new [android.view.Surface] to the session. When the * caller uses the session beyond the safe usage limits, the usage may still work in * conjunction with CameraX, but any strong guarantees provided by CameraX about the * validity of the camera state become void. * * @param stateCallback The [CameraCaptureSession.StateCallback]. * @return The current Extender. */ @SuppressLint("ExecutorRegistration") fun setSessionStateCallback( stateCallback: CameraCaptureSession.StateCallback ): Extender<T> { baseBuilder.mutableConfig.insertOption( SESSION_STATE_CALLBACK_OPTION, stateCallback ) return this } /** * Sets a [CameraCaptureSession.CaptureCallback]. * * The caller is expected to use the [CameraCaptureSession] instance accessed * through the callback methods responsibly. Generally safe usages include: (1) querying the * session for its properties. Generally unsafe usages include: (1) submitting a new * [CaptureRequest], (2) stopping an existing [CaptureRequest], (3) closing the * session, (4) attaching a new [android.view.Surface] to the session. When the * caller uses the session beyond the safe usage limits, the usage may still work in * conjunction with CameraX, but any strong guarantees provided by CameraX about the * validity of the camera state become void. * * The caller is generally free to use the [CaptureRequest] and [CaptureRequest] * instances accessed through the callback methods. * * @param captureCallback The [CameraCaptureSession.CaptureCallback]. * @return The current Extender. */ @SuppressLint("ExecutorRegistration") fun setSessionCaptureCallback(captureCallback: CaptureCallback): Extender<T> { baseBuilder.mutableConfig.insertOption( SESSION_CAPTURE_CALLBACK_OPTION, captureCallback ) return this } /** * Set the ID of the physical camera to get output from. * * In the case one logical camera is made up of multiple physical cameras, this call * forces the physical camera with the specified camera ID to produce image. * * The valid physical camera IDs can be queried by `CameraCharacteristics * .getPhysicalCameraIds` on API &gt;= 28. Passing in an invalid physical camera ID will * be ignored. * * On API &lt;= 27, the physical camera ID will be ignored since logical camera is not * supported on these API levels. * * Currently it doesn't support binding use cases with different physical camera IDs. If * use cases with different physical camera IDs are bound at the same time, an * [IllegalArgumentException] will be thrown. * * @param cameraId The desired camera ID. * @return The current Extender. */ @RequiresApi(28) fun setPhysicalCameraId(@Suppress("UNUSED_PARAMETER") cameraId: String): Extender<T> { baseBuilder.mutableConfig.insertOption(SESSION_PHYSICAL_CAMERA_ID_OPTION, cameraId) return this } } }
camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/interop/Camera2Interop.kt
1347368798
// 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 training.actions import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.ui.showYesNoDialog import training.learn.LearnBundle import training.util.clearTrainingProgress private class ResetLearningProgressAction : AnAction(AllIcons.Actions.Restart) { override fun actionPerformed(e: AnActionEvent) { if (showYesNoDialog(LearnBundle.message("learn.option.reset.progress.dialog"), LearnBundle.message("learn.option.reset.progress.confirm"), null)) { clearTrainingProgress() } } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = e.project != null } }
plugins/ide-features-trainer/src/training/actions/ResetLearningProgressAction.kt
398997644
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplacePutWithAssignment") package org.jetbrains.intellij.build.impl sealed class BaseLayoutSpec(private val layout: BaseLayout) { /** * Register an additional module to be included into the plugin distribution. Module-level libraries from * {@code moduleName} with scopes 'Compile' and 'Runtime' will be also copied to the 'lib' directory of the plugin. */ fun withModule(moduleName: String) { layout.withModule(moduleName) } fun withModules(names: Iterable<String>) { names.forEach(layout::withModule) } /** * Register an additional module to be included into the plugin distribution. If {@code relativeJarPath} doesn't contain '/' (i.e. the * JAR will be added to the plugin's classpath) this will also cause modules library from {@code moduleName} with scopes 'Compile' and * 'Runtime' to be copied to the 'lib' directory of the plugin. * * @param relativeJarPath target JAR path relative to 'lib' directory of the plugin; different modules may be packed into the same JAR, * but <strong>don't use this for new plugins</strong>; this parameter is temporary added to keep layout of old plugins. */ fun withModule(moduleName: String, relativeJarPath: String) { layout.withModule(moduleName, relativeJarPath) } /** * Include the project library to 'lib' directory or its subdirectory of the plugin distribution * @param libraryName path relative to 'lib' plugin directory */ fun withProjectLibrary(libraryName: String) { layout.withProjectLibrary(libraryName) } fun withProjectLibrary(libraryName: String, outPath: String) { layout.includedProjectLibraries.add(ProjectLibraryData(libraryName = libraryName, packMode = LibraryPackMode.MERGED, outPath = outPath)) } fun withProjectLibrary(libraryName: String, packMode: LibraryPackMode) { layout.includedProjectLibraries.add(ProjectLibraryData(libraryName = libraryName, packMode = packMode)) } fun withProjectLibrary(libraryName: String, outPath: String, packMode: LibraryPackMode) { layout.includedProjectLibraries.add(ProjectLibraryData(libraryName = libraryName, packMode = packMode, outPath = outPath)) } /** * Include the module library to the plugin distribution. Please note that it makes sense to call this method only * for additional modules which aren't copied directly to the 'lib' directory of the plugin distribution, because for ordinary modules * their module libraries are included into the layout automatically. * @param relativeOutputPath target path relative to 'lib' directory */ fun withModuleLibrary(libraryName: String, moduleName: String, relativeOutputPath: String) { layout.withModuleLibrary(libraryName = libraryName, moduleName = moduleName, relativeOutputPath = relativeOutputPath) } /** * Exclude the specified files when {@code moduleName} is packed into JAR file. * <strong>This is a temporary method added to keep layout of some old plugins. If some files from a module shouldn't be included into the * module JAR it's strongly recommended to move these files outside the module source roots.</strong> * @param excludedPattern Ant-like pattern describing files to be excluded (relatively to the module output root); e.g. foo&#47;** * to exclude `foo` directory */ fun excludeFromModule(moduleName: String, excludedPattern: String) { layout.excludeFromModule(moduleName, excludedPattern) } fun excludeFromModule(moduleName: String, excludedPatterns: List<String>) { layout.excludeFromModule(moduleName, excludedPatterns) } /** * Include an artifact output to the plugin distribution. * @param artifactName name of the project configuration * @param relativeOutputPath target path relative to 'lib' directory */ fun withArtifact(artifactName: String, relativeOutputPath: String) { layout.includedArtifacts = layout.includedArtifacts.put(artifactName, relativeOutputPath) } /** * Include contents of JARs of the project library {@code libraryName} into JAR {@code jarName} */ fun withProjectLibraryUnpackedIntoJar(libraryName: String, jarName: String) { layout.withProjectLibraryUnpackedIntoJar(libraryName, jarName) } }
platform/build-scripts/src/org/jetbrains/intellij/build/impl/BaseLayoutSpec.kt
1956889673
package com.haishinkit.media internal data class Timestamp( val scale: Long = 1L, private var start: Long = DEFAULT_TIMESTAMP ) { val duration: Long get() = (nanoTime - start) / scale var nanoTime: Long = DEFAULT_TIMESTAMP set(value) { if (0 < value && start == DEFAULT_TIMESTAMP) { start = value } field = value } fun clear() { nanoTime = DEFAULT_TIMESTAMP start = DEFAULT_TIMESTAMP } companion object { private const val DEFAULT_TIMESTAMP = -1L } }
haishinkit/src/main/java/com/haishinkit/media/Timestamp.kt
2571672997
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models import com.intellij.openapi.util.NlsSafe import com.jetbrains.packagesearch.intellij.plugin.extensibility.RepositoryDeclaration import org.jetbrains.packagesearch.api.v2.ApiRepository internal data class RepositoryModel( val id: String?, val name: String?, val url: String?, val usageInfo: List<RepositoryUsageInfo>, val remoteInfo: ApiRepository ) { @NlsSafe val displayName = remoteInfo.friendlyName fun isEquivalentTo(other: RepositoryDeclaration): Boolean { if (id != null && id == other.id) return true if (url != null && url == other.url) return true return false } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/RepositoryModel.kt
3357297703
import kotlin.tex<caret>t.toString // REF: text
plugins/kotlin/idea/tests/testData/resolve/references/inImport/kotlinPackageSecondQualifier.kt
3660194001
object A { private<caret> } // WITHOUT_CUSTOM_LINE_INDENT_PROVIDER
plugins/kotlin/idea/tests/testData/indentationOnNewline/ModifierListInUnfinishedDeclaration.kt
621480966
package org.penella.node import io.vertx.core.AbstractVerticle import io.vertx.core.Future import org.penella.MailBoxes import org.penella.codecs.CreateDBCodec import org.penella.codecs.ListDBCodec import org.penella.codecs.ListDBResponseCodec import org.penella.index.IIndexFactory import org.penella.index.bstree.BSTreeIndexFactory import org.penella.messages.CreateDB import org.penella.messages.ListDB import org.penella.messages.ListDBResponse import org.penella.store.VerticalStoreWrapper /** * 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. * * Created by alisle on 1/24/17. */ class InvalidIndexFactory : Exception("Invalid Index Factory") class NodeVertical : AbstractVerticle() { companion object { val INDEX_FACTORY_TYPE = "index_factory" } val indexFactoryType : String by lazy { config().getString(INDEX_FACTORY_TYPE) } val indexFactory : IIndexFactory by lazy { when(indexFactoryType) { "BSTreeTreeIndexFactory" -> BSTreeIndexFactory() else -> throw InvalidIndexFactory() } } val node : INode by lazy { Node(VerticalStoreWrapper(vertx), indexFactory) } private fun registerCodecs() { vertx.eventBus().registerDefaultCodec(CreateDB::class.java, CreateDBCodec()) vertx.eventBus().registerDefaultCodec(ListDB::class.java, ListDBCodec()) vertx.eventBus().registerDefaultCodec(ListDBResponse::class.java, ListDBResponseCodec()) } override fun start(startFuture: Future<Void>?) { registerCodecs() vertx.eventBus().consumer<CreateDB>(MailBoxes.NODE_CREATE_DB.mailbox).handler{ msg -> msg.reply(node.createDB(msg.body())) } vertx.eventBus().consumer<ListDB>(MailBoxes.NODE_LIST_DBS.mailbox).handler{ msg -> msg.reply(node.listDB(msg.body())) } startFuture?.complete() } }
src/main/java/org/penella/node/NodeVertical.kt
2488505959
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtParameter // OPTIONS: usages data class A(val <caret>x: Int, val y: Int) { companion object { fun b(): B = B(1, 2) } } data class B(val x: Int, val y: Int) fun foo() { val (x, y) = A.b() } // FIR_COMPARISON // FIR_COMPARISON_WITH_DISABLED_COMPONENTS
plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/components/companionObjectAccess.0.kt
3600944682
KtClass: Y KtClass: Z
plugins/kotlin/fir/testData/search/implementations/classes/classWithTypeParameters.result.kt
1900940399
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.application.constraints import com.intellij.openapi.application.constraints.ConstrainedExecution.ContextConstraint import com.intellij.openapi.diagnostic.Logger import com.intellij.util.containers.map2Array import kotlinx.coroutines.Runnable import org.jetbrains.annotations.ApiStatus import java.util.function.BooleanSupplier /** * This class is responsible for running a task in a proper context defined using various builder methods of this class and it's * implementations, like [com.intellij.openapi.application.AppUIExecutor.later], or generic [withConstraint]. * * ## Implementation notes: ## * * The [scheduleWithinConstraints] starts checking the list of constraints, one by one, rescheduling and restarting itself * for each unsatisfied constraint until at some point *all* of the constraints are satisfied *at once*. * * This ultimately ends up with [ContextConstraint.schedule] being called one by one for every constraint that needs to be scheduled. * Finally, the runnable is called, executing the task in the properly arranged context. * * @author eldar */ abstract class BaseConstrainedExecution<E : ConstrainedExecution<E>>(protected val constraints: Array<ContextConstraint>) : ConstrainedExecution<E>, ConstrainedExecutionScheduler { protected abstract fun cloneWith(constraints: Array<ContextConstraint>): E override fun withConstraint(constraint: ContextConstraint): E = cloneWith(constraints + constraint) override fun asExecutor() = ConstrainedTaskExecutor(this, composeCancellationCondition(), composeExpiration()) override fun asCoroutineDispatcher() = createConstrainedCoroutineDispatcher(this, composeCancellationCondition(), composeExpiration()) protected open fun composeExpiration(): Expiration? = null protected open fun composeCancellationCondition(): BooleanSupplier? = null override fun scheduleWithinConstraints(runnable: Runnable, condition: BooleanSupplier?) = scheduleWithinConstraints(runnable, condition, constraints) companion object { private val LOG = Logger.getInstance("#com.intellij.openapi.application.constraints.ConstrainedExecution") @JvmStatic @ApiStatus.Internal fun scheduleWithinConstraints(runnable: Runnable, condition: BooleanSupplier?, constraints: Array<ContextConstraint>) { val attemptChain = mutableListOf<ContextConstraint>() fun inner() { if (attemptChain.size > 3000) { val lastCauses = attemptChain.takeLast(15) LOG.error("Too many reschedule requests, probably constraints can't be satisfied all together", *lastCauses.map2Array { it.toString() }) } if (condition?.asBoolean == false) return for (constraint in constraints) { if (!constraint.isCorrectContext()) { return constraint.schedule(Runnable { if (!constraint.isCorrectContext()) { LOG.error("ContextConstraint scheduled into incorrect context: $constraint", *constraints.map2Array { it.toString() }) } attemptChain.add(constraint) inner() }) } } runnable.run() } inner() } } }
platform/platform-impl/src/com/intellij/openapi/application/constraints/BaseConstrainedExecution.kt
4026820292
package test import kotlinx.parcelize.* import android.os.* class Box(val value: String) @Parcelize class Foo(val box: Box): Parcelable { companion object : Parceler<Foo> { override fun create(parcel: Parcel) = Foo(Box(parcel.readString())) override fun Foo.write(parcel: Parcel, flags: Int) { parcel.writeString(box.value) } } } @Parcelize class Foo2(val box: <error descr="[PARCELABLE_TYPE_NOT_SUPPORTED] Type is not directly supported by 'Parcelize'. Annotate the parameter type with '@RawValue' if you want it to be serialized using 'writeValue()'">Box</error>): Parcelable
plugins/kotlin/compiler-plugins/parcelize/tests/testData/checker/kt20062.kt
1047747023
// "Change type to 'Int'" "true" // ERROR: Null can not be a value of a non-null type Int interface Test<T> { val prop : T } class Other { fun doTest() { val some = object: Test<Int> { override val <caret>prop = null } } }
plugins/kotlin/idea/tests/testData/quickfix/override/typeMismatchOnOverride/objectInsideBody.kt
2149070986
// 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.nj2k import com.intellij.openapi.project.Project import com.intellij.openapi.roots.LanguageLevelProjectExtension import com.intellij.pom.java.LanguageLevel import com.intellij.psi.codeStyle.JavaCodeStyleSettings import com.intellij.util.ThrowableRunnable import org.jetbrains.kotlin.idea.j2k.IdeaJavaToKotlinServices import org.jetbrains.kotlin.idea.test.runAll import org.jetbrains.kotlin.idea.test.withCustomCompilerOptions import org.jetbrains.kotlin.j2k.AbstractJavaToKotlinConverterSingleFileTest import org.jetbrains.kotlin.j2k.ConverterSettings import org.jetbrains.kotlin.nj2k.postProcessing.NewJ2kPostProcessor import org.jetbrains.kotlin.test.KotlinTestUtils import java.io.File abstract class AbstractNewJavaToKotlinConverterSingleFileTest : AbstractJavaToKotlinConverterSingleFileTest() { override fun doTest(javaPath: String) { val javaFile = File(javaPath) withCustomCompilerOptions(javaFile.readText(), project, module) { val directory = javaFile.parentFile val expectedFileName = "${javaFile.nameWithoutExtension}.external" val expectedFiles = directory.listFiles { _, name -> name == "$expectedFileName.kt" || name == "$expectedFileName.java" }!!.filterNotNull() for (expectedFile in expectedFiles) { addFile(expectedFile, dirName = null) } super.doTest(javaPath) } } override fun compareResults(expectedFile: File, actual: String) { KotlinTestUtils.assertEqualsToFile(expectedFile, actual) } override fun setUp() { super.setUp() JavaCodeStyleSettings.getInstance(project).USE_EXTERNAL_ANNOTATIONS = true } override fun tearDown() { runAll( ThrowableRunnable { JavaCodeStyleSettings.getInstance(project).USE_EXTERNAL_ANNOTATIONS = false }, ThrowableRunnable { super.tearDown() } ) } override fun fileToKotlin(text: String, settings: ConverterSettings, project: Project): String { val file = createJavaFile(text) return NewJavaToKotlinConverter(project, module, settings, IdeaJavaToKotlinServices) .filesToKotlin(listOf(file), NewJ2kPostProcessor()).results.single() } override fun provideExpectedFile(javaPath: String): File = File(javaPath.replace(".java", ".new.kt")).takeIf { it.exists() } ?: super.provideExpectedFile(javaPath) private fun getLanguageLevel() = if (testDataDirectory.toString().contains("newJavaFeatures")) LanguageLevel.HIGHEST else LanguageLevel.JDK_1_8 override fun getProjectDescriptor() = descriptorByFileDirective(File(testDataPath, fileName()), languageLevel = getLanguageLevel()) }
plugins/kotlin/j2k/new/tests/test/org/jetbrains/kotlin/nj2k/AbstractNewJavaToKotlinConverterSingleFileTest.kt
2556466032
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.impl import com.intellij.CommonBundle import com.intellij.build.BuildContentManager import com.intellij.execution.* import com.intellij.execution.configuration.CompatibilityAwareRunProfile import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.configurations.RunConfiguration.RestartSingletonResult import com.intellij.execution.configurations.RunProfile import com.intellij.execution.configurations.RunProfileState import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.filters.TextConsoleBuilderFactory import com.intellij.execution.impl.ExecutionManagerImpl.Companion.DELEGATED_RUN_PROFILE_KEY import com.intellij.execution.impl.statistics.RunConfigurationUsageTriggerCollector import com.intellij.execution.impl.statistics.RunConfigurationUsageTriggerCollector.RunConfigurationFinishType import com.intellij.execution.impl.statistics.RunConfigurationUsageTriggerCollector.UI_SHOWN_STAGE import com.intellij.execution.process.* import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionEnvironmentBuilder import com.intellij.execution.runners.ExecutionUtil import com.intellij.execution.runners.ProgramRunner import com.intellij.execution.target.TargetEnvironmentAwareRunProfile import com.intellij.execution.target.TargetProgressIndicator import com.intellij.execution.target.getEffectiveTargetName import com.intellij.execution.ui.ConsoleView import com.intellij.execution.ui.RunContentDescriptor import com.intellij.execution.ui.RunContentManager import com.intellij.ide.SaveAndSyncHandler import com.intellij.internal.statistic.StructuredIdeActivity import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ReadAction import com.intellij.openapi.components.service import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.* import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.ToolWindow import com.intellij.ui.AppUIUtil import com.intellij.ui.UIBundle import com.intellij.ui.content.ContentManager import com.intellij.ui.content.impl.ContentImpl import com.intellij.util.Alarm import com.intellij.util.SmartList import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.containers.ContainerUtil import org.jetbrains.annotations.* import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.resolvedPromise import java.awt.BorderLayout import java.io.OutputStream import java.util.* import java.util.concurrent.Callable import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Consumer import javax.swing.JPanel import javax.swing.SwingUtilities class ExecutionManagerImpl(private val project: Project) : ExecutionManager(), Disposable { companion object { val LOG = logger<ExecutionManagerImpl>() private val EMPTY_PROCESS_HANDLERS = emptyArray<ProcessHandler>() internal val DELEGATED_RUN_PROFILE_KEY = Key.create<RunProfile>("DELEGATED_RUN_PROFILE_KEY") @JvmField val EXECUTION_SESSION_ID_KEY = ExecutionManager.EXECUTION_SESSION_ID_KEY @JvmField val EXECUTION_SKIP_RUN = ExecutionManager.EXECUTION_SKIP_RUN @JvmStatic fun getInstance(project: Project) = project.service<ExecutionManager>() as ExecutionManagerImpl @JvmStatic fun isProcessRunning(descriptor: RunContentDescriptor?): Boolean { val processHandler = descriptor?.processHandler return processHandler != null && !processHandler.isProcessTerminated } @JvmStatic fun stopProcess(descriptor: RunContentDescriptor?) { stopProcess(descriptor?.processHandler) } @JvmStatic fun stopProcess(processHandler: ProcessHandler?) { if (processHandler == null) { return } processHandler.putUserData(ProcessHandler.TERMINATION_REQUESTED, true) if (processHandler is KillableProcess && processHandler.isProcessTerminating) { // process termination was requested, but it's still alive // in this case 'force quit' will be performed processHandler.killProcess() return } if (!processHandler.isProcessTerminated) { if (processHandler.detachIsDefault()) { processHandler.detachProcess() } else { processHandler.destroyProcess() } } } @JvmStatic fun getAllDescriptors(project: Project): List<RunContentDescriptor> { return project.serviceIfCreated<RunContentManager>()?.allDescriptors ?: emptyList() } @ApiStatus.Internal @JvmStatic fun setDelegatedRunProfile(runProfile: RunProfile, runProfileToDelegate: RunProfile) { if (runProfile !== runProfileToDelegate && runProfile is UserDataHolder) { DELEGATED_RUN_PROFILE_KEY[runProfile] = runProfileToDelegate } } } init { val connection = ApplicationManager.getApplication().messageBus.connect(this) connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectClosed(project: Project) { if (project === [email protected]) { inProgress.clear() } } }) } @set:TestOnly @Volatile var forceCompilationInTests = false private val awaitingTerminationAlarm = Alarm() private val awaitingRunProfiles = HashMap<RunProfile, ExecutionEnvironment>() private val runningConfigurations: MutableList<RunningConfigurationEntry> = ContainerUtil.createLockFreeCopyOnWriteList() private val inProgress = Collections.synchronizedSet(HashSet<InProgressEntry>()) private fun processNotStarted(environment: ExecutionEnvironment, activity: StructuredIdeActivity?, e : Throwable? = null) { RunConfigurationUsageTriggerCollector.logProcessFinished(activity, RunConfigurationFinishType.FAILED_TO_START) val executorId = environment.executor.id inProgress.remove(InProgressEntry(executorId, environment.runner.runnerId)) project.messageBus.syncPublisher(EXECUTION_TOPIC).processNotStarted(executorId, environment, e) } /** * Internal usage only. Maybe removed or changed in any moment. No backward compatibility. */ @ApiStatus.Internal override fun startRunProfile(environment: ExecutionEnvironment, starter: () -> Promise<RunContentDescriptor?>) { doStartRunProfile(environment) { // errors are handled by startRunProfile starter() .then { descriptor -> if (descriptor != null) { descriptor.executionId = environment.executionId val toolWindowId = RunContentManager.getInstance(environment.project).getContentDescriptorToolWindowId(environment) if (toolWindowId != null) { descriptor.contentToolWindowId = toolWindowId } environment.runnerAndConfigurationSettings?.let { descriptor.isActivateToolWindowWhenAdded = it.isActivateToolWindowBeforeRun } } environment.callback?.let { it.processStarted(descriptor) environment.callback = null } descriptor } } } override fun startRunProfile(starter: RunProfileStarter, environment: ExecutionEnvironment) { doStartRunProfile(environment) { starter.executeAsync(environment) } } private fun doStartRunProfile(environment: ExecutionEnvironment, task: () -> Promise<RunContentDescriptor>) { val activity = triggerUsage(environment) RunManager.getInstance(environment.project).refreshUsagesList(environment.runProfile) val project = environment.project val reuseContent = RunContentManager.getInstance(project).getReuseContent(environment) if (reuseContent != null) { reuseContent.executionId = environment.executionId environment.contentToReuse = reuseContent } val executor = environment.executor inProgress.add(InProgressEntry(executor.id, environment.runner.runnerId)) project.messageBus.syncPublisher(EXECUTION_TOPIC).processStartScheduled(executor.id, environment) val startRunnable = Runnable { if (project.isDisposed) { return@Runnable } project.messageBus.syncPublisher(EXECUTION_TOPIC).processStarting(executor.id, environment) fun handleError(e: Throwable) { processNotStarted(environment, activity, e) if (e !is ProcessCanceledException) { ProgramRunnerUtil.handleExecutionError(project, environment, e, environment.runProfile) LOG.debug(e) } } try { task() .onSuccess { descriptor -> AppUIUtil.invokeLaterIfProjectAlive(project) { if (descriptor == null) { processNotStarted(environment, activity) return@invokeLaterIfProjectAlive } val entry = RunningConfigurationEntry(descriptor, environment.runnerAndConfigurationSettings, executor) runningConfigurations.add(entry) Disposer.register(descriptor, Disposable { runningConfigurations.remove(entry) }) if (!descriptor.isHiddenContent && !environment.isHeadless) { RunContentManager.getInstance(project).showRunContent(executor, descriptor, environment.contentToReuse) } activity?.stageStarted(UI_SHOWN_STAGE) environment.contentToReuse = descriptor val processHandler = descriptor.processHandler if (processHandler != null) { if (!processHandler.isStartNotified) { project.messageBus.syncPublisher(EXECUTION_TOPIC).processStarting(executor.id, environment, processHandler) processHandler.startNotify() } inProgress.remove(InProgressEntry(executor.id, environment.runner.runnerId)) project.messageBus.syncPublisher(EXECUTION_TOPIC).processStarted(executor.id, environment, processHandler) val listener = ProcessExecutionListener(project, executor.id, environment, processHandler, descriptor, activity) processHandler.addProcessListener(listener) // Since we cannot guarantee that the listener is added before process handled is start notified, // we have to make sure the process termination events are delivered to the clients. // Here we check the current process state and manually deliver events, while // the ProcessExecutionListener guarantees each such event is only delivered once // either by this code, or by the ProcessHandler. val terminating = processHandler.isProcessTerminating val terminated = processHandler.isProcessTerminated if (terminating || terminated) { listener.processWillTerminate(ProcessEvent(processHandler), false /* doesn't matter */) if (terminated) { val exitCode = if (processHandler.isStartNotified) processHandler.exitCode ?: -1 else -1 listener.processTerminated(ProcessEvent(processHandler, exitCode)) } } } } } .onError(::handleError) } catch (e: Throwable) { handleError(e) } } if (!forceCompilationInTests && ApplicationManager.getApplication().isUnitTestMode) { startRunnable.run() } else { compileAndRun(Runnable { ApplicationManager.getApplication().invokeLater(startRunnable, project.disposed) }, environment, Runnable { if (!project.isDisposed) { processNotStarted(environment, activity) } }) } } override fun dispose() { for (entry in runningConfigurations) { Disposer.dispose(entry.descriptor) } runningConfigurations.clear() } @Suppress("OverridingDeprecatedMember") override fun getContentManager() = RunContentManager.getInstance(project) override fun getRunningProcesses(): Array<ProcessHandler> { var handlers: MutableList<ProcessHandler>? = null for (descriptor in getAllDescriptors(project)) { val processHandler = descriptor.processHandler ?: continue if (handlers == null) { handlers = SmartList() } handlers.add(processHandler) } return handlers?.toTypedArray() ?: EMPTY_PROCESS_HANDLERS } override fun compileAndRun(startRunnable: Runnable, environment: ExecutionEnvironment, onCancelRunnable: Runnable?) { var id = environment.executionId if (id == 0L) { id = environment.assignNewExecutionId() } val profile = environment.runProfile if (profile !is RunConfiguration) { startRunnable.run() return } val beforeRunTasks = doGetBeforeRunTasks(profile) if (beforeRunTasks.isEmpty()) { startRunnable.run() return } val context = environment.dataContext val projectContext = context ?: SimpleDataContext.getProjectContext(project) val runBeforeRunExecutorMap = Collections.synchronizedMap(linkedMapOf<BeforeRunTask<*>, Executor>()) ApplicationManager.getApplication().executeOnPooledThread { for (task in beforeRunTasks) { val provider = BeforeRunTaskProvider.getProvider(project, task.providerId) if (provider == null || task !is RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask) { continue } val settings = task.settings if (settings != null) { // as side-effect here we setup runners list ( required for com.intellij.execution.impl.RunManagerImpl.canRunConfiguration() ) var executor = if (Registry.`is`("lock.run.executor.for.before.run.tasks", false)) { DefaultRunExecutor.getRunExecutorInstance() } else { environment.executor } val builder = ExecutionEnvironmentBuilder.createOrNull(executor, settings) if (builder == null || !RunManagerImpl.canRunConfiguration(settings, executor)) { executor = DefaultRunExecutor.getRunExecutorInstance() if (!RunManagerImpl.canRunConfiguration(settings, executor)) { // we should stop here as before run task cannot be executed at all (possibly it's invalid) onCancelRunnable?.run() ExecutionUtil.handleExecutionError(environment, ExecutionException( ExecutionBundle.message("dialog.message.cannot.start.before.run.task", settings))) return@executeOnPooledThread } } runBeforeRunExecutorMap[task] = executor } } for (task in beforeRunTasks) { if (project.isDisposed) { return@executeOnPooledThread } @Suppress("UNCHECKED_CAST") val provider = BeforeRunTaskProvider.getProvider(project, task.providerId) as BeforeRunTaskProvider<BeforeRunTask<*>>? if (provider == null) { LOG.warn("Cannot find BeforeRunTaskProvider for id='${task.providerId}'") continue } val builder = ExecutionEnvironmentBuilder(environment).contentToReuse(null) val executor = runBeforeRunExecutorMap[task] if (executor != null) { builder.executor(executor) } val taskEnvironment = builder.build() taskEnvironment.executionId = id EXECUTION_SESSION_ID_KEY.set(taskEnvironment, id) try { if (!provider.executeTask(projectContext, profile, taskEnvironment, task)) { if (onCancelRunnable != null) { SwingUtilities.invokeLater(onCancelRunnable) } return@executeOnPooledThread } } catch (e: ProcessCanceledException) { if (onCancelRunnable != null) { SwingUtilities.invokeLater(onCancelRunnable) } return@executeOnPooledThread } } doRun(environment, startRunnable) } } private fun doRun(environment: ExecutionEnvironment, startRunnable: Runnable) { val allowSkipRun = environment.getUserData(EXECUTION_SKIP_RUN) if (allowSkipRun != null && allowSkipRun) { processNotStarted(environment, null) return } // important! Do not use DumbService.smartInvokeLater here because it depends on modality state // and execution of startRunnable could be skipped if modality state check fails SwingUtilities.invokeLater { if (project.isDisposed) { return@invokeLater } val settings = environment.runnerAndConfigurationSettings if (settings != null && !settings.type.isDumbAware && DumbService.isDumb(project)) { DumbService.getInstance(project).runWhenSmart(startRunnable) } else { try { startRunnable.run() } catch (ignored: IndexNotReadyException) { ExecutionUtil.handleExecutionError(environment, ExecutionException( ExecutionBundle.message("dialog.message.cannot.start.while.indexing.in.progress"))) } } } } override fun restartRunProfile(project: Project, executor: Executor, target: ExecutionTarget, configuration: RunnerAndConfigurationSettings?, processHandler: ProcessHandler?, environmentCustomization: Consumer<ExecutionEnvironment>?) { val builder = createEnvironmentBuilder(project, executor, configuration) if (processHandler != null) { for (descriptor in getAllDescriptors(project)) { if (descriptor.processHandler === processHandler) { builder.contentToReuse(descriptor) break } } } val environment = builder.target(target).build() environmentCustomization?.accept(environment) restartRunProfile(environment) } override fun restartRunProfile(environment: ExecutionEnvironment) { val configuration = environment.runnerAndConfigurationSettings val runningIncompatible: List<RunContentDescriptor> if (configuration == null) { runningIncompatible = emptyList() } else { runningIncompatible = getIncompatibleRunningDescriptors(configuration) } val contentToReuse = environment.contentToReuse val runningOfTheSameType = if (configuration != null && !configuration.configuration.isAllowRunningInParallel) { getRunningDescriptors(Condition { it.isOfSameType(configuration) }) } else if (isProcessRunning(contentToReuse)) { listOf(contentToReuse!!) } else { emptyList() } val runningToStop = ContainerUtil.concat(runningOfTheSameType, runningIncompatible) if (runningToStop.isNotEmpty()) { if (configuration != null) { if (runningOfTheSameType.isNotEmpty() && (runningOfTheSameType.size > 1 || contentToReuse == null || runningOfTheSameType.first() !== contentToReuse)) { val result = configuration.configuration.restartSingleton(environment) if (result == RestartSingletonResult.NO_FURTHER_ACTION) { return } if (result == RestartSingletonResult.ASK_AND_RESTART && !userApprovesStopForSameTypeConfigurations(environment.project, configuration.name, runningOfTheSameType.size)) { return } } if (runningIncompatible.isNotEmpty() && !userApprovesStopForIncompatibleConfigurations(project, configuration.name, runningIncompatible)) { return } } for (descriptor in runningToStop) { stopProcess(descriptor) } } if (awaitingRunProfiles[environment.runProfile] === environment) { // defense from rerunning exactly the same ExecutionEnvironment return } awaitingRunProfiles[environment.runProfile] = environment awaitTermination(object : Runnable { override fun run() { if (awaitingRunProfiles[environment.runProfile] !== environment) { // a new rerun has been requested before starting this one, ignore this rerun return } if ((configuration != null && !configuration.type.isDumbAware && DumbService.getInstance(project).isDumb) || inProgress.contains(InProgressEntry(environment.executor.id, environment.runner.runnerId))) { awaitTermination(this, 100) return } for (descriptor in runningOfTheSameType) { val processHandler = descriptor.processHandler if (processHandler != null && !processHandler.isProcessTerminated) { awaitTermination(this, 100) return } } awaitingRunProfiles.remove(environment.runProfile) // start() can be called during restartRunProfile() after pretty long 'awaitTermination()' so we have to check if the project is still here if (environment.project.isDisposed) { return } val settings = environment.runnerAndConfigurationSettings executeConfiguration(environment, settings != null && settings.isEditBeforeRun) } }, 50) } private class MyProcessHandler : ProcessHandler() { override fun destroyProcessImpl() {} override fun detachProcessImpl() {} override fun detachIsDefault(): Boolean { return false } override fun getProcessInput(): OutputStream? = null public override fun notifyProcessTerminated(exitCode: Int) { super.notifyProcessTerminated(exitCode) } } override fun executePreparationTasks(environment: ExecutionEnvironment, currentState: RunProfileState): Promise<Any?> { if (!(environment.runProfile is TargetEnvironmentAwareRunProfile)) { return resolvedPromise() } val targetEnvironmentAwareRunProfile = environment.runProfile as TargetEnvironmentAwareRunProfile if (!targetEnvironmentAwareRunProfile.needPrepareTarget()) { return resolvedPromise() } val processHandler = MyProcessHandler() val consoleView = TextConsoleBuilderFactory.getInstance().createBuilder(environment.project).console ProcessTerminatedListener.attach(processHandler) consoleView.attachToProcess(processHandler) val component = TargetPrepareComponent(consoleView) val buildContentManager = BuildContentManager.getInstance(environment.project) val contentName = targetEnvironmentAwareRunProfile.getEffectiveTargetName(environment.project)?.let { ExecutionBundle.message("tab.title.prepare.environment", it, environment.runProfile.name) } ?: ExecutionBundle.message("tab.title.prepare.target.environment", environment.runProfile.name) val toolWindow = buildContentManager.orCreateToolWindow val contentManager: ContentManager = toolWindow.contentManager val contentImpl = ContentImpl(component, contentName, true) contentImpl.putUserData(ToolWindow.SHOW_CONTENT_ICON, java.lang.Boolean.TRUE) contentImpl.icon = environment.runProfile.icon for (content in contentManager.contents) { if (contentName != content.displayName) continue if (content.isPinned) continue val contentComponent = content.component if (contentComponent !is TargetPrepareComponent) continue if (contentComponent.isPreparationFinished()) { contentManager.removeContent(content, true) } } contentManager.addContent(contentImpl) contentManager.setSelectedContent(contentImpl) toolWindow.activate(null) val promise = AsyncPromise<Any?>() ApplicationManager.getApplication().executeOnPooledThread { try { processHandler.startNotify() val targetProgressIndicator = object : TargetProgressIndicator { @Volatile var stopped = false override fun addText(text: @Nls String, key: Key<*>) { processHandler.notifyTextAvailable(text, key) } override fun isCanceled(): Boolean { return false } override fun stop() { stopped = true } override fun isStopped(): Boolean = stopped } promise.setResult(environment.prepareTargetEnvironment(currentState, targetProgressIndicator)) } catch (t: Throwable) { LOG.warn(t) promise.setError(ExecutionBundle.message("message.error.happened.0", t.localizedMessage)) processHandler.notifyTextAvailable(StringUtil.notNullize(t.localizedMessage), ProcessOutputType.STDERR) processHandler.notifyTextAvailable("\n", ProcessOutputType.STDERR) } finally { val exitCode = if (promise.isSucceeded) 0 else -1 processHandler.notifyProcessTerminated(exitCode) component.setPreparationFinished() } } return promise } @ApiStatus.Internal fun executeConfiguration(environment: ExecutionEnvironment, showSettings: Boolean, assignNewId: Boolean = true) { val runnerAndConfigurationSettings = environment.runnerAndConfigurationSettings val project = environment.project var runner = environment.runner if (runnerAndConfigurationSettings != null) { val targetManager = ExecutionTargetManager.getInstance(project) if (!targetManager.doCanRun(runnerAndConfigurationSettings.configuration, environment.executionTarget)) { ExecutionUtil.handleExecutionError(environment, ExecutionException(ProgramRunnerUtil.getCannotRunOnErrorMessage( environment.runProfile, environment.executionTarget))) processNotStarted(environment, null) return } if (!DumbService.isDumb(project)) { if (showSettings && runnerAndConfigurationSettings.isEditBeforeRun) { if (!RunDialog.editConfiguration(environment, ExecutionBundle.message("dialog.title.edit.configuration", 0))) { processNotStarted(environment, null) return } editConfigurationUntilSuccess(environment, assignNewId) } else { inProgress.add(InProgressEntry(environment.executor.id, environment.runner.runnerId)) ReadAction.nonBlocking(Callable { RunManagerImpl.canRunConfiguration(environment) }) .finishOnUiThread(ModalityState.NON_MODAL) { canRun -> inProgress.remove(InProgressEntry(environment.executor.id, environment.runner.runnerId)) if (canRun) { executeConfiguration(environment, environment.runner, assignNewId, this.project, environment.runnerAndConfigurationSettings) return@finishOnUiThread } if (!RunDialog.editConfiguration(environment, ExecutionBundle.message("dialog.title.edit.configuration", 0))) { processNotStarted(environment, null) return@finishOnUiThread } editConfigurationUntilSuccess(environment, assignNewId) } .expireWith(this) .submit(AppExecutorUtil.getAppExecutorService()) } return } } executeConfiguration(environment, runner, assignNewId, project, runnerAndConfigurationSettings) } private fun editConfigurationUntilSuccess(environment: ExecutionEnvironment, assignNewId: Boolean) { ReadAction.nonBlocking(Callable { RunManagerImpl.canRunConfiguration(environment) }) .finishOnUiThread(ModalityState.NON_MODAL) { canRun -> val runAnyway = if (!canRun) { val message = ExecutionBundle.message("dialog.message.configuration.still.incorrect.do.you.want.to.edit.it.again") val title = ExecutionBundle.message("dialog.title.change.configuration.settings") Messages.showYesNoDialog(project, message, title, CommonBundle.message("button.edit"), ExecutionBundle.message("run.continue.anyway"), Messages.getErrorIcon()) != Messages.YES } else true if (canRun || runAnyway) { val runner = ProgramRunner.getRunner(environment.executor.id, environment.runnerAndConfigurationSettings!!.configuration) if (runner == null) { ExecutionUtil.handleExecutionError(environment, ExecutionException(ExecutionBundle.message("dialog.message.cannot.find.runner", environment.runProfile.name))) } else { executeConfiguration(environment, runner, assignNewId, project, environment.runnerAndConfigurationSettings) } return@finishOnUiThread } if (!RunDialog.editConfiguration(environment, ExecutionBundle.message("dialog.title.edit.configuration", 0))) { processNotStarted(environment, null) return@finishOnUiThread } editConfigurationUntilSuccess(environment, assignNewId) } .expireWith(this) .submit(AppExecutorUtil.getAppExecutorService()) } private fun executeConfiguration(environment: ExecutionEnvironment, runner: @NotNull ProgramRunner<*>, assignNewId: Boolean, project: @NotNull Project, runnerAndConfigurationSettings: @Nullable RunnerAndConfigurationSettings?) { try { var effectiveEnvironment = environment if (runner != effectiveEnvironment.runner) { effectiveEnvironment = ExecutionEnvironmentBuilder(effectiveEnvironment).runner(runner).build() } if (assignNewId) { effectiveEnvironment.assignNewExecutionId() } runner.execute(effectiveEnvironment) } catch (e: ExecutionException) { ProgramRunnerUtil.handleExecutionError(project, environment, e, runnerAndConfigurationSettings?.configuration) } } override fun isStarting(executorId: String, runnerId: String): Boolean { return inProgress.contains(InProgressEntry(executorId, runnerId)) } private fun awaitTermination(request: Runnable, delayMillis: Long) { val app = ApplicationManager.getApplication() if (app.isUnitTestMode) { app.invokeLater(request, ModalityState.any()) } else { awaitingTerminationAlarm.addRequest(request, delayMillis) } } private fun getIncompatibleRunningDescriptors(configurationAndSettings: RunnerAndConfigurationSettings): List<RunContentDescriptor> { val configurationToCheckCompatibility = configurationAndSettings.configuration return getRunningDescriptors(Condition { runningConfigurationAndSettings -> val runningConfiguration = runningConfigurationAndSettings.configuration if (runningConfiguration is CompatibilityAwareRunProfile) { runningConfiguration.mustBeStoppedToRun(configurationToCheckCompatibility) } else { false } }) } fun getRunningDescriptors(condition: Condition<in RunnerAndConfigurationSettings>): List<RunContentDescriptor> { val result = SmartList<RunContentDescriptor>() for (entry in runningConfigurations) { if (entry.settings != null && condition.value(entry.settings)) { val processHandler = entry.descriptor.processHandler if (processHandler != null /*&& !processHandler.isProcessTerminating()*/ && !processHandler.isProcessTerminated) { result.add(entry.descriptor) } } } return result } fun getDescriptors(condition: Condition<in RunnerAndConfigurationSettings>): List<RunContentDescriptor> { val result = SmartList<RunContentDescriptor>() for (entry in runningConfigurations) { if (entry.settings != null && condition.value(entry.settings)) { result.add(entry.descriptor) } } return result } fun getExecutors(descriptor: RunContentDescriptor): Set<Executor> { val result = HashSet<Executor>() for (entry in runningConfigurations) { if (descriptor === entry.descriptor) { result.add(entry.executor) } } return result } fun getConfigurations(descriptor: RunContentDescriptor): Set<RunnerAndConfigurationSettings> { val result = HashSet<RunnerAndConfigurationSettings>() for (entry in runningConfigurations) { if (descriptor === entry.descriptor && entry.settings != null) { result.add(entry.settings) } } return result } } @ApiStatus.Internal fun RunnerAndConfigurationSettings.isOfSameType(runnerAndConfigurationSettings: RunnerAndConfigurationSettings): Boolean { if (this === runnerAndConfigurationSettings) return true val thisConfiguration = configuration val thatConfiguration = runnerAndConfigurationSettings.configuration if (thisConfiguration === thatConfiguration) return true if (thisConfiguration is UserDataHolder) { val originalRunProfile = DELEGATED_RUN_PROFILE_KEY[thisConfiguration] ?: return false if (originalRunProfile === thatConfiguration) return true if (thatConfiguration is UserDataHolder) return originalRunProfile === DELEGATED_RUN_PROFILE_KEY[thatConfiguration] } return false } private fun triggerUsage(environment: ExecutionEnvironment): StructuredIdeActivity? { val runConfiguration = environment.runnerAndConfigurationSettings?.configuration val configurationFactory = runConfiguration?.factory ?: return null return RunConfigurationUsageTriggerCollector.trigger(environment.project, configurationFactory, environment.executor, runConfiguration) } private fun createEnvironmentBuilder(project: Project, executor: Executor, configuration: RunnerAndConfigurationSettings?): ExecutionEnvironmentBuilder { val builder = ExecutionEnvironmentBuilder(project, executor) val runner = configuration?.let { ProgramRunner.getRunner(executor.id, it.configuration) } if (runner == null && configuration != null) { ExecutionManagerImpl.LOG.error("Cannot find runner for ${configuration.name}") } else if (runner != null) { builder.runnerAndSettings(runner, configuration) } return builder } private fun userApprovesStopForSameTypeConfigurations(project: Project, configName: String, instancesCount: Int): Boolean { val config = RunManagerImpl.getInstanceImpl(project).config if (!config.isRestartRequiresConfirmation) { return true } @Suppress("DuplicatedCode") val option = object : DialogWrapper.DoNotAskOption { override fun isToBeShown() = config.isRestartRequiresConfirmation override fun setToBeShown(value: Boolean, exitCode: Int) { config.isRestartRequiresConfirmation = value } override fun canBeHidden() = true override fun shouldSaveOptionsOnCancel() = false override fun getDoNotShowMessage(): String { return UIBundle.message("dialog.options.do.not.show") } } return Messages.showOkCancelDialog( project, ExecutionBundle.message("rerun.singleton.confirmation.message", configName, instancesCount), ExecutionBundle.message("process.is.running.dialog.title", configName), ExecutionBundle.message("rerun.confirmation.button.text"), CommonBundle.getCancelButtonText(), Messages.getQuestionIcon(), option) == Messages.OK } private fun userApprovesStopForIncompatibleConfigurations(project: Project, configName: String, runningIncompatibleDescriptors: List<RunContentDescriptor>): Boolean { @Suppress("DuplicatedCode") val config = RunManagerImpl.getInstanceImpl(project).config @Suppress("DuplicatedCode") if (!config.isStopIncompatibleRequiresConfirmation) { return true } @Suppress("DuplicatedCode") val option = object : DialogWrapper.DoNotAskOption { override fun isToBeShown() = config.isStopIncompatibleRequiresConfirmation override fun setToBeShown(value: Boolean, exitCode: Int) { config.isStopIncompatibleRequiresConfirmation = value } override fun canBeHidden() = true override fun shouldSaveOptionsOnCancel() = false override fun getDoNotShowMessage(): String { return UIBundle.message("dialog.options.do.not.show") } } val names = StringBuilder() for (descriptor in runningIncompatibleDescriptors) { val name = descriptor.displayName if (names.isNotEmpty()) { names.append(", ") } names.append(if (name.isNullOrEmpty()) ExecutionBundle.message("run.configuration.no.name") else String.format("'%s'", name)) } return Messages.showOkCancelDialog( project, ExecutionBundle.message("stop.incompatible.confirmation.message", configName, names.toString(), runningIncompatibleDescriptors.size), ExecutionBundle.message("incompatible.configuration.is.running.dialog.title", runningIncompatibleDescriptors.size), ExecutionBundle.message("stop.incompatible.confirmation.button.text"), CommonBundle.getCancelButtonText(), Messages.getQuestionIcon(), option) == Messages.OK } private class ProcessExecutionListener(private val project: Project, private val executorId: String, private val environment: ExecutionEnvironment, private val processHandler: ProcessHandler, private val descriptor: RunContentDescriptor, private val activity: StructuredIdeActivity?) : ProcessAdapter() { private val willTerminateNotified = AtomicBoolean() private val terminateNotified = AtomicBoolean() override fun processTerminated(event: ProcessEvent) { if (project.isDisposed || !terminateNotified.compareAndSet(false, true)) { return } ApplicationManager.getApplication().invokeLater(Runnable { val ui = descriptor.runnerLayoutUi if (ui != null && !ui.isDisposed) { ui.updateActionsNow() } }, ModalityState.any(), project.disposed) project.messageBus.syncPublisher(ExecutionManager.EXECUTION_TOPIC).processTerminated(executorId, environment, processHandler, event.exitCode) val runConfigurationFinishType = if (event.processHandler.getUserData(ProcessHandler.TERMINATION_REQUESTED) == true) RunConfigurationFinishType.TERMINATED else RunConfigurationFinishType.UNKNOWN RunConfigurationUsageTriggerCollector.logProcessFinished(activity, runConfigurationFinishType) processHandler.removeProcessListener(this) SaveAndSyncHandler.getInstance().scheduleRefresh() } override fun processWillTerminate(event: ProcessEvent, shouldNotBeUsed: Boolean) { if (project.isDisposed || !willTerminateNotified.compareAndSet(false, true)) { return } project.messageBus.syncPublisher(ExecutionManager.EXECUTION_TOPIC).processTerminating(executorId, environment, processHandler) } } private data class InProgressEntry(val executorId: String, val runnerId: String) private data class RunningConfigurationEntry(val descriptor: RunContentDescriptor, val settings: RunnerAndConfigurationSettings?, val executor: Executor) private class TargetPrepareComponent(val console: ConsoleView) : JPanel(BorderLayout()), Disposable { init { add(console.component, BorderLayout.CENTER) } @Volatile private var finished = false fun isPreparationFinished() = finished fun setPreparationFinished() { finished = true } override fun dispose() { Disposer.dispose(console) } }
platform/execution-impl/src/com/intellij/execution/impl/ExecutionManagerImpl.kt
1887886198
// PROBLEM: none abstract class Parent { abstract val foo: Int? } class Child : Parent() { override val <caret>foo = null }
plugins/kotlin/idea/tests/testData/inspectionsLocal/implicitNullableNothingType/overrideVal.kt
1119653611
// 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.jetbrains.python.testing import com.jetbrains.python.PyBundle import com.jetbrains.python.run.targetBasedConfiguration.PyRunTargetVariant import org.jetbrains.annotations.Nls import java.util.* import kotlin.reflect.KCallable internal class PyTestCustomOption(property: KCallable<*>, vararg supportedTypes: PyRunTargetVariant) { val name: String = property.name val isBooleanType: Boolean = property.returnType.classifier == Boolean::class @field:Nls val localizedName: String init { localizedName = property.annotations.filterIsInstance<ConfigField>().firstOrNull()?.localizedName?.let { PyBundle.message(it) } ?: name } /** * Types to display this option for */ val mySupportedTypes: EnumSet<PyRunTargetVariant> = EnumSet.copyOf(supportedTypes.asList()) }
python/src/com/jetbrains/python/testing/PyTestCustomOption.kt
3261326975
fun foo(list: List<String>): Int { <caret>val first = list.firstOrNull() if (first == null) return -1 return first.length }
plugins/kotlin/idea/tests/testData/joinLines/initializerAndIfToElvis/simple.kt
3716623953
package org.ccci.gto.android.common.androidx.fragment.app import android.os.Bundle import android.view.LayoutInflater import androidx.fragment.app.DialogFragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry abstract class BaseDialogFragment : DialogFragment() { // region Lifecycle override fun onGetLayoutInflater(savedInstanceState: Bundle?): LayoutInflater { _dialogLifecycleOwner = FragmentDialogLifecycleOwner() val inflater = super.onGetLayoutInflater(savedInstanceState) initializeDialogLifecycleOwner() return inflater } override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) _dialogLifecycleOwner?.handleLifecycleEvent(Lifecycle.Event.ON_CREATE) } override fun onStart() { super.onStart() _dialogLifecycleOwner?.handleLifecycleEvent(Lifecycle.Event.ON_START) } override fun onResume() { super.onResume() _dialogLifecycleOwner?.handleLifecycleEvent(Lifecycle.Event.ON_RESUME) } override fun onPause() { _dialogLifecycleOwner?.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) super.onPause() } override fun onStop() { _dialogLifecycleOwner?.handleLifecycleEvent(Lifecycle.Event.ON_STOP) super.onStop() } override fun onDestroyView() { _dialogLifecycleOwner?.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY) super.onDestroyView() _dialogLifecycleOwner = null } // endregion Lifecycle // region DialogLifecycleOwner private var _dialogLifecycleOwner: FragmentDialogLifecycleOwner? = null val dialogLifecycleOwner: LifecycleOwner get() = _dialogLifecycleOwner ?: throw IllegalStateException( "Can't access the Fragment Dialog's LifecycleOwner when getDialog() is null " + "i.e., before onCreateDialog() or after onDestroyView()" ) private fun initializeDialogLifecycleOwner() { when { dialog != null -> _dialogLifecycleOwner!!.initialize() _dialogLifecycleOwner!!.isInitialized -> throw IllegalStateException("Called getDialogLifecycleOwner() but onCreateDialog() returned null") else -> _dialogLifecycleOwner = null } } // endregion DialogLifecycleOwner } internal class FragmentDialogLifecycleOwner : LifecycleOwner { private var lifecycleRegistry: LifecycleRegistry? = null internal fun initialize() { if (lifecycleRegistry == null) { lifecycleRegistry = LifecycleRegistry(this) } } internal val isInitialized = lifecycleRegistry != null override fun getLifecycle(): Lifecycle { initialize() return lifecycleRegistry!! } fun handleLifecycleEvent(event: Lifecycle.Event) = lifecycleRegistry!!.handleLifecycleEvent(event) }
gto-support-androidx-fragment/src/main/kotlin/org/ccci/gto/android/common/androidx/fragment/app/BaseDialogFragment.kt
960266572
fun <T> f(a: Int) { <lineMarker>f</lineMarker><String>(55) }
plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/recursiveCall/generic.kt
213477532
fun foo() { A<caret>() } class A (x: Int) fun A(): A = A(1)
plugins/kotlin/idea/tests/testData/hierarchy/class/type/CaretAtFabricMethod/main.kt
2449863363
package ch.rmy.android.framework.extensions import android.app.Activity import android.content.Context import android.content.Intent import android.os.Build import androidx.activity.result.ActivityResultLauncher import androidx.core.app.ActivityOptionsCompat import androidx.fragment.app.Fragment import ch.rmy.android.framework.ui.IntentBuilder import java.io.Serializable inline fun createIntent(block: Intent.() -> Unit): Intent = Intent().apply(block) fun Intent.startActivity(activity: Activity) { activity.startActivity(this) } fun Intent.startActivity(fragment: Fragment) { fragment.startActivity(this) } fun Intent.startActivity(context: Context) { when (context) { is Activity -> startActivity(context) else -> context.startActivity(this) } } fun IntentBuilder.startActivity(activity: Activity) { build(activity).startActivity(activity) } fun IntentBuilder.startActivity(fragment: Fragment) { build(fragment.requireContext()).startActivity(fragment) } fun IntentBuilder.startActivity(context: Context) { build(context).startActivity(context) } fun <T : Any?> ActivityResultLauncher<T>.launch(options: ActivityOptionsCompat? = null) { launch(null, options) } @Suppress("DEPRECATION") inline fun <reified T : Any?> Intent.getParcelable(key: String): T? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) getParcelableExtra(key, T::class.java) else getParcelableExtra(key) @Suppress("DEPRECATION") inline fun <reified T : Any?> Intent.getParcelableList(key: String): List<T>? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) getParcelableArrayListExtra(key, T::class.java) else getParcelableArrayListExtra(key) @Suppress("DEPRECATION") inline fun <reified T : Serializable?> Intent.getSerializable(key: String): T? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) getSerializableExtra(key, T::class.java) else getSerializableExtra(key) as? T
HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/extensions/IntentExtensions.kt
2559015435
package de.treichels.hott.voice import org.apache.commons.io.IOUtils import java.io.* import java.nio.file.Files import java.util.* import javax.sound.sampled.* import javax.sound.sampled.AudioFormat.Encoding /** * Representation of a single announcement in a voice data file (.vdf). * * @author [email protected] */ class VoiceData(name: String, val rawData: ByteArray) : Serializable, ObservableBase() { companion object { /** Default audio format 11 kHz 16-bit signed PCM mono */ private val audioFormat = AudioFormat(Encoding.PCM_SIGNED, 11025f, 16, 1, 2, 11025f, false) fun forStream(sourceAudioStream: AudioInputStream, name: String, volume: Double = 1.0): VoiceData { // read from stream val sourceFormat = sourceAudioStream.format val rate = sourceFormat.sampleRate val channels = sourceFormat.channels // convert to from MP3 or OGG to PCM val pcmFormat = AudioFormat(Encoding.PCM_SIGNED, rate, 16, channels, channels * 2, rate, false) val pcmAudioStream = if (sourceFormat.encoding === Encoding.PCM_SIGNED) sourceAudioStream else AudioSystem.getAudioInputStream(pcmFormat, sourceAudioStream) // convert sample rate and channels val targetAudioStream = if (pcmFormat.matches(audioFormat)) pcmAudioStream else AudioSystem.getAudioInputStream(audioFormat, pcmAudioStream) // encode to ADPCM val encodedStream = ADPCMCodec.encode(targetAudioStream, volume) return VoiceData(name, IOUtils.toByteArray(encodedStream)) } fun forFile(soundFile: File, volume: Double = 1.0): VoiceData { // read from file val sourceAudioStream = AudioSystem.getAudioInputStream(soundFile) val fileName = soundFile.name val dot = fileName.lastIndexOf(".") val name = fileName.substring(0, dot) return forStream(sourceAudioStream, name, volume) } } var name = name set(name) { field = if (name.length > 17) name.substring(0, 18) else name invalidate() } val audioInputStream: AudioInputStream get() = AudioInputStream(pcmInputStream, audioFormat, 2L * rawData.size.toLong()) val pcmData: ByteArray get() = ADPCMCodec.decode(rawData) val pcmInputStream: InputStream get() = ADPCMCodec.decode(rawInputStream) val rawInputStream: InputStream get() = ByteArrayInputStream(rawData) fun play() { try { Player.play(audioFormat, pcmInputStream) } catch (e: LineUnavailableException) { throw RuntimeException(e) } catch (e: IOException) { throw RuntimeException(e) } } override fun toString(): String { return String.format("VoiceData [name=%s]", this.name) } fun writeVox(voxFile: File) { Files.write(voxFile.toPath(), rawData) } fun writeWav(wavFile: File) { AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, wavFile) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as VoiceData if (!Arrays.equals(rawData, other.rawData)) return false if (name != other.name) return false return true } override fun hashCode(): Int { var result = Arrays.hashCode(rawData) result = 31 * result + (name.hashCode()) return result } fun clone(): VoiceData = VoiceData(this.name, this.rawData) }
HoTT-Voice/src/main/kotlin/de/treichels/hott/voice/VoiceData.kt
1077065246
package io.datawire.discovery.auth import io.datawire.discovery.DiscoveryTest import io.vertx.core.AbstractVerticle import io.vertx.core.DeploymentOptions import io.vertx.core.Vertx import io.vertx.core.json.JsonObject import io.vertx.ext.auth.jwt.JWTAuth import io.vertx.ext.auth.jwt.JWTOptions import io.vertx.ext.unit.TestContext import io.vertx.ext.unit.junit.VertxUnitRunner import io.vertx.ext.web.Router import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import java.net.ServerSocket import java.util.* /** * Unit tests for [DiscoveryAuthHandler]. The DiscoveryAuthHandler only checks to see whether the provided * Json Web Token (JWT) can be verified (signature match). It is not concerned with verifying any claims provided by * the token. * * TODO: Enhance these test cases once more stringent claim validation is implemented. */ @RunWith(VertxUnitRunner::class) class DiscoveryAuthHandlerTest : DiscoveryTest() { lateinit private var validJsonWebToken: String lateinit private var invalidJsonWebToken: String lateinit private var authProvider: JWTAuth lateinit private var vertx: Vertx lateinit private var socket: ServerSocket private var port: Int = 0 @Before fun setup(context: TestContext) { vertx = Vertx.vertx() socket = ServerSocket(0) port = socket.localPort socket.close() val jsonWebTokenKeyStoreConfig = buildJsonWebTokenKeyStoreConfig( path = resourcePath("ks-hmac256-notasecret.jceks"), password = "notasecret") vertx.deployVerticle( TestVerticle(), DeploymentOptions().setConfig(JsonObject(mapOf( "http.port" to port, "auth.jwt" to jsonWebTokenKeyStoreConfig) )), context.asyncAssertSuccess()) authProvider = JWTAuth.create(vertx, jsonWebTokenKeyStoreConfig) validJsonWebToken = authProvider.generateToken(JsonObject().put("aud", "VALID_AUDIENCE"), JWTOptions()) invalidJsonWebToken = makeInvalidToken("INVALID_AUDIENCE") } @After fun teardown(context: TestContext) { socket.close() vertx.close(context.asyncAssertSuccess()) } @Test fun useTokenQueryParameterIfPresent(context: TestContext) { val async = context.async() val http = vertx.createHttpClient() val request = http.post(port, "localhost", "/authenticated?token=$validJsonWebToken") { resp -> resp.bodyHandler { context.assertEquals(204, resp.statusCode()) http.close() async.complete() } } request.end() } @Test fun useAuthorizationHeaderWithBearerTokenIfPresent(context: TestContext) { val async = context.async() val http = vertx.createHttpClient() val request = http.post(port, "localhost", "/authenticated") { resp -> resp.bodyHandler { context.assertEquals(204, resp.statusCode()) http.close() async.complete() } } request.putHeader("Authorization", "Bearer $validJsonWebToken") request.end() } @Test fun useTokenQueryParameterBeforeAttemptingToUseAuthorizationHeaderWithBearerToken(context: TestContext) { val async = context.async() val http = vertx.createHttpClient() val request = http.post(port, "localhost", "/authenticated?token=$validJsonWebToken") { resp -> resp.bodyHandler { context.assertEquals(204, resp.statusCode()) http.close() async.complete() } } // If the logic in the handler is not correct then the invalid token will be used. request.putHeader("Authorization", "Bearer $invalidJsonWebToken") request.end() } @Test fun failIfTokenIsIncorrectlySigned(context: TestContext) { val async = context.async() val http = vertx.createHttpClient() val request = http.post(port, "localhost", "/authenticated?token=$invalidJsonWebToken") { resp -> resp.bodyHandler { context.assertEquals(401, resp.statusCode()) http.close() async.complete() } } request.end() } private fun makeInvalidToken(aud: String): String { val (header, claims, signature) = validJsonWebToken.split(".") val decodedClaims = Base64.getUrlDecoder().decode(claims) val typeFactory = objectMapper.typeFactory val mapType = typeFactory.constructMapType(HashMap::class.java, String::class.java, String::class.java) val claimsMap = objectMapper.readValue<HashMap<String, String>>(decodedClaims, mapType) claimsMap["aud"] = aud val falseClaims = objectMapper.writeValueAsBytes(claimsMap) return listOf(header, Base64.getUrlEncoder().encodeToString(falseClaims), signature).joinToString(".") } class TestVerticle : AbstractVerticle() { override fun start() { val router = Router.router(this.vertx) val authProvider = JWTAuth.create(this.vertx, config().getJsonObject("auth.jwt")) router.post("/authenticated").handler(DiscoveryAuthHandler(authProvider, null)) router.post("/authenticated").handler { rc -> rc.response().setStatusCode(204).end() } val server = this.vertx.createHttpServer() server.requestHandler { router.accept(it) }.listen(config().getInteger("http.port")) } } }
discovery-server/src/test/kotlin/io/datawire/discovery/auth/DiscoveryAuthHandlerTest.kt
568504196
/** * HoTT Transmitter Config Copyright (C) 2013 Oliver Treichel * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package de.treichels.hott.model.enums import de.treichels.hott.util.get import java.util.* /** * @author Oliver Treichel &lt;[email protected]&gt; */ enum class TrimMode { Global, Phase, ThrottleLimit, ThrottelAR, Pitch; override fun toString(): String = ResourceBundle.getBundle(javaClass.name)[name] }
HoTT-Model/src/main/kotlin/de/treichels/hott/model/enums/TrimMode.kt
3902138825
package com.bixlabs.bkotlin import android.content.Context import androidx.annotation.StringRes import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast /** * Display the simple Toast message with the [Toast.LENGTH_SHORT] duration. * @param message the message text. */ fun Context.shortToast(message: String) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show() /** * Display the simple Toast message with the [Toast.LENGTH_SHORT] duration. * @param message the message text resource. */ fun Context.shortToast(@StringRes message: Int) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show() /** * Display the simple Toast message with the [Toast.LENGTH_LONG] duration. * @param message the message text. */ fun Context.longToast(message: CharSequence) = Toast.makeText(this, message, Toast.LENGTH_LONG).show() /** * Display the simple Toast message with the [Toast.LENGTH_LONG] duration. * @param message the message text resource. */ fun Context.longToast(@StringRes message: Int) = Toast.makeText(this, message, Toast.LENGTH_LONG).show() /** * Shortcut for LayoutInflater.from(this) */ fun Context.inflate(layoutResource: Int, parent: ViewGroup? = null, attachToRoot: Boolean = false) { LayoutInflater.from(this).inflate(layoutResource, parent, attachToRoot) } /** * get Height of status bar * @return height of status bar */ fun Context.getStatusBarHeight(): Int { val resourceId = this.resources.getIdentifier("status_bar_height", "dimen", "android") return this.resources.getDimensionPixelSize(resourceId) }
bkotlin/src/main/java/com/bixlabs/bkotlin/Context.kt
601361559
package com.breadwallet.platform.entities import com.breadwallet.crypto.WalletManagerMode import com.breadwallet.logger.logError import com.platform.util.getIntOrDefault import com.platform.util.getLongOrDefault import com.platform.util.getStringOrNull import org.json.JSONException import org.json.JSONObject /** * BreadWallet * * Created by Mihail Gutan <[email protected]> on 6/22/17. * Copyright (c) 2017 breadwallet LLC * * 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. */ data class WalletInfoData( val classVersion: Int = DEFAULT_CLASS_VERSION, val creationDate: Long = DEFAULT_CREATION_DATE, val name: String? = null, val connectionModes: Map<String, WalletManagerMode> = emptyMap() ) { companion object { private const val NAME = "name" private const val CLASS_VERSION = "classVersion" private const val CREATION_DATE = "creationDate" private const val CONNECTION_MODES = "connectionModes" private const val DEFAULT_CLASS_VERSION = 3 private const val DEFAULT_CREATION_DATE = 0L fun fromJsonObject(json: JSONObject): WalletInfoData = json.run { WalletInfoData( classVersion = getIntOrDefault(CLASS_VERSION, DEFAULT_CLASS_VERSION), creationDate = getLongOrDefault(CREATION_DATE, DEFAULT_CREATION_DATE), name = getStringOrNull(NAME), connectionModes = getConnectionModes(this) ) } private fun getConnectionModes(json: JSONObject): Map<String, WalletManagerMode> { val mutableModes = mutableMapOf<String, WalletManagerMode>() val modes = json.optJSONArray(CONNECTION_MODES) ?: return mutableModes.toMap() try { var currencyId = "" for (i in 0 until modes.length()) { if (i % 2 == 0) currencyId = modes.getString(i) else mutableModes[currencyId] = WalletManagerMode.fromSerialization(modes.getInt(i)) } } catch (ex: JSONException) { logError("Malformed $CONNECTION_MODES array: $modes") } return mutableModes.toMap() } } fun toJSON(): JSONObject { val connectionModesList = mutableListOf<Any>() connectionModes.entries.forEach { connectionModesList.add(it.key) connectionModesList.add(it.value.toSerialization()) } return JSONObject( mapOf( CLASS_VERSION to classVersion, CREATION_DATE to creationDate, NAME to name, CONNECTION_MODES to connectionModesList ) ) } }
app-core/src/main/java/com/breadwallet/platform/entities/WalletInfoData.kt
4131699075
package com.quran.labs.androidquran.common.audio.cache import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.filter import javax.inject.Inject import javax.inject.Singleton @Singleton class AudioCacheInvalidator @Inject constructor() { private val cache = MutableSharedFlow<Int>(extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) fun qarisToInvalidate(): Flow<Int> = cache.filter { it > -1 } fun invalidateCacheForQari(qariId: Int) { cache.tryEmit(qariId) } }
common/audio/src/main/java/com/quran/labs/androidquran/common/audio/cache/AudioCacheInvalidator.kt
280283166
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.adblock.ui.original import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.* import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.view.ActionMode import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.github.clans.fab.FloatingActionButton import com.github.clans.fab.FloatingActionMenu import jp.hazuki.yuzubrowser.adblock.R import jp.hazuki.yuzubrowser.adblock.repository.original.AdBlock import jp.hazuki.yuzubrowser.adblock.repository.original.AdBlockManager import jp.hazuki.yuzubrowser.ui.extensions.applyIconColor import jp.hazuki.yuzubrowser.ui.widget.recycler.DividerItemDecoration import jp.hazuki.yuzubrowser.ui.widget.recycler.OnRecyclerListener import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import java.io.IOException import java.io.PrintWriter import java.util.* class AdBlockFragment : Fragment(), OnRecyclerListener, AdBlockEditDialog.AdBlockEditDialogListener, AdBlockMenuDialog.OnAdBlockMenuListener, AdBlockItemDeleteDialog.OnBlockItemDeleteListener, ActionMode.Callback, DeleteSelectedDialog.OnDeleteSelectedListener, AdBlockDeleteAllDialog.OnDeleteAllListener { private lateinit var provider: AdBlockManager.AdBlockItemProvider private lateinit var adapter: AdBlockArrayRecyclerAdapter private lateinit var layoutManager: LinearLayoutManager private var listener: AdBlockFragmentListener? = null private var actionMode: ActionMode? = null private var type: Int = 0 private var isModified = false override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { setHasOptionsMenu(true) return inflater.inflate(R.layout.fragment_ad_block_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val activity = activity ?: return val arguments = arguments ?: return type = arguments.getInt(ARG_TYPE) listener!!.setFragmentTitle(type) provider = AdBlockManager.getProvider(activity.applicationContext, type) adapter = AdBlockArrayRecyclerAdapter(activity, provider.allItems, this) layoutManager = LinearLayoutManager(activity) val recyclerView: RecyclerView = view.findViewById(R.id.recyclerView) val fabMenu: FloatingActionMenu = view.findViewById(R.id.fabMenu) val addByEditFab: FloatingActionButton = view.findViewById(R.id.addByEditFab) val addFromFileFab: FloatingActionButton = view.findViewById(R.id.addFromFileFab) recyclerView.let { it.layoutManager = layoutManager it.addItemDecoration(DividerItemDecoration(activity)) it.adapter = adapter } addByEditFab.setOnClickListener { AdBlockEditDialog(getString(R.string.add)) .show(childFragmentManager, "add") fabMenu.close(true) } addFromFileFab.setOnClickListener { val intent = Intent(Intent.ACTION_GET_CONTENT) intent.type = "*/*" startActivityForResult(Intent.createChooser(intent, null), REQUEST_SELECT_FILE) fabMenu.close(false) } } override fun onRecyclerItemClicked(v: View, position: Int) { isModified = true val adBlock = adapter[position] adBlock.isEnable = !adBlock.isEnable provider.update(adBlock) adapter.notifyItemChanged(position) } override fun onRecyclerItemLongClicked(v: View, position: Int): Boolean { if (!adapter.isMultiSelectMode) { AdBlockMenuDialog(position, adapter[position].id) .show(childFragmentManager, "menu") } return true } override fun onEdited(index: Int, id: Int, text: String) { isModified = true if (index >= 0 && index < adapter.itemCount) { val adBlock = adapter[index] adBlock.match = text if (provider.update(adBlock)) { adapter.notifyItemChanged(index) } else { adapter.remove(index) provider.delete(adBlock.id) } } else { if (id > -1) { var i = 0 while (adapter.size() > i) { val adBlock = adapter[i] if (adBlock.id == id) { adBlock.match = text if (provider.update(adBlock)) { adapter.notifyItemChanged(i) } else { adapter.remove(i) provider.delete(adBlock.id) } break } i++ } } else { val adBlock = AdBlock(text) if (provider.update(adBlock)) { adapter.add(adBlock) adapter.notifyDataSetChanged() } } } } fun addAll(adBlocks: List<AdBlock>) { isModified = true provider.addAll(adBlocks) adapter.clear() adapter.addAll(provider.allItems) adapter.notifyDataSetChanged() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { REQUEST_SELECT_FILE -> if (resultCode == Activity.RESULT_OK && data != null && data.data != null) { listener!!.requestImport(data.data!!) } REQUEST_SELECT_EXPORT -> if (resultCode == Activity.RESULT_OK && data != null && data.data != null) { GlobalScope.launch(Dispatchers.IO) { try { context?.run { contentResolver.openOutputStream(data.data!!)!!.use { os -> PrintWriter(os).use { pw -> val adBlockList = provider.enableItems for ((_, match) in adBlockList) pw.println(match) launch(Dispatchers.Main) { Toast.makeText(context, R.string.pref_exported, Toast.LENGTH_SHORT).show() } } } } } catch (e: IOException) { e.printStackTrace() } } } } } override fun onAskDelete(index: Int, id: Int) { AdBlockItemDeleteDialog(index, id, adapter[index].match) .show(childFragmentManager, "delete") } override fun onDelete(index: Int, id: Int) { val adBlock = getItem(index, id) if (adBlock != null) { isModified = true adapter.remove(adBlock) provider.delete(adBlock.id) adapter.notifyDataSetChanged() } } override fun onEdit(index: Int, id: Int) { val adBlock = getItem(index, id) if (adBlock != null) { AdBlockEditDialog(getString(R.string.pref_edit), index, adBlock) .show(childFragmentManager, "edit") } } override fun startMultiSelect(index: Int) { actionMode = (activity as AppCompatActivity).startSupportActionMode(this) adapter.isMultiSelectMode = true adapter.setSelect(index, true) } override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.ad_block_action_mode, menu) return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu) = false override fun onDeleteSelected() { val items = adapter.selectedItems Collections.sort(items, Collections.reverseOrder()) for (index in items) { isModified = true val (id) = adapter.remove(index) provider.delete(id) } actionMode!!.finish() } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { when (item.itemId) { R.id.delete -> { actionMode = mode DeleteSelectedDialog().show(childFragmentManager, "delete_selected") return true } } return false } override fun onDestroyActionMode(mode: ActionMode) { adapter.isMultiSelectMode = false } private fun getItem(index: Int, id: Int): AdBlock? { if (index < adapter.itemCount) { val adBlock = adapter[index] if (adBlock.id == id) return adBlock } return getItemFromId(id) } private fun getItemFromId(id: Int) = adapter.items.firstOrNull { it.id == id } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.ad_block_menu, menu) applyIconColor(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val activity = activity ?: return false when (item.itemId) { android.R.id.home -> { activity.onBackPressed() return true } R.id.export -> { val intent = Intent(Intent.ACTION_CREATE_DOCUMENT) intent.type = "*/*" intent.putExtra(Intent.EXTRA_TITLE, listener!!.getExportFileName(type)) startActivityForResult(intent, REQUEST_SELECT_EXPORT) return true } R.id.deleteAll -> { AdBlockDeleteAllDialog().show(childFragmentManager, "delete_all") return true } R.id.sort_registration -> { adapter.items.sortWith { m1, m2 -> m1.id.compareTo(m2.id) } adapter.notifyDataSetChanged() layoutManager.scrollToPosition(0) return true } R.id.sort_registration_reverse -> { adapter.items.sortWith { m1, m2 -> m2.id.compareTo(m1.id) } adapter.notifyDataSetChanged() layoutManager.scrollToPosition(0) return true } R.id.sort_name -> { adapter.items.sortWith { m1, m2 -> m1.match.compareTo(m2.match) } adapter.notifyDataSetChanged() layoutManager.scrollToPosition(0) return true } R.id.sort_name_reverse -> { adapter.items.sortWith { m1, m2 -> m2.match.compareTo(m1.match) } adapter.notifyDataSetChanged() layoutManager.scrollToPosition(0) return true } } return super.onOptionsItemSelected(item) } override fun onDeleteAll() { isModified = true provider.deleteAll() adapter.clear() adapter.notifyDataSetChanged() } override fun onAttach(context: Context) { super.onAttach(context) listener = activity as AdBlockFragmentListener } override fun onDestroy() { super.onDestroy() GlobalScope.launch(Dispatchers.IO) { provider.updateCache() } } override fun onDetach() { super.onDetach() listener = null } interface AdBlockFragmentListener { fun setFragmentTitle(type: Int) fun requestImport(uri: Uri) fun getExportFileName(type: Int): String } companion object { private const val ARG_TYPE = "type" private const val REQUEST_SELECT_FILE = 1 private const val REQUEST_SELECT_EXPORT = 2 operator fun invoke(type: Int): AdBlockFragment { return AdBlockFragment().apply { arguments = Bundle().apply { putInt(ARG_TYPE, type) } } } } }
module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/ui/original/AdBlockFragment.kt
2770956428
package i_introduction._2_Named_Arguments // default values for arguments: fun bar(i: Int, s: String = "", b: Boolean = true) {} fun usage() { // named arguments: bar(1, b = false) } fun todoTask2(collection: Collection<Int>): String = collection.joinToString(prefix="{", postfix="}") fun task2(collection: Collection<Int>): String { return todoTask2(collection) }
src/i_introduction/_2_Named_Arguments/NamedArguments.kt
1595038255
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.shops.bukkit.database.table import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.shops.bukkit.RPKShopsBukkit import com.rpkit.shops.bukkit.database.jooq.rpkit.Tables.RPKIT_SHOP_COUNT import com.rpkit.shops.bukkit.shopcount.RPKShopCount import org.ehcache.config.builders.CacheConfigurationBuilder import org.ehcache.config.builders.ResourcePoolsBuilder import org.jooq.impl.DSL.constraint import org.jooq.impl.SQLDataType /** * Represents the shop count table. */ class RPKShopCountTable(database: Database, private val plugin: RPKShopsBukkit): Table<RPKShopCount>(database, RPKShopCount::class) { private val cache = if (plugin.config.getBoolean("caching.rpkit_shop_count.id.enabled")) { database.cacheManager.createCache("rpk-shops-bukkit.rpkit_shop_count.id", CacheConfigurationBuilder .newCacheConfigurationBuilder(Int::class.javaObjectType, RPKShopCount::class.java, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_shop_count.id.size"))).build()) } else { null } private val characterCache = if (plugin.config.getBoolean("caching.rpkit_shop_count.character_id.enabled")) { database.cacheManager.createCache("rpk-shops-bukkit.rpkit_shop_count.character_id", CacheConfigurationBuilder .newCacheConfigurationBuilder(Int::class.javaObjectType, Int::class.javaObjectType, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_shop_count.character_id.size"))).build()) } else { null } override fun create() { database.create .createTableIfNotExists(RPKIT_SHOP_COUNT) .column(RPKIT_SHOP_COUNT.ID, SQLDataType.INTEGER.identity(true)) .column(RPKIT_SHOP_COUNT.CHARACTER_ID, SQLDataType.INTEGER) .column(RPKIT_SHOP_COUNT.COUNT, SQLDataType.INTEGER) .constraints( constraint("pk_rpkit_shop_count").primaryKey(RPKIT_SHOP_COUNT.ID) ) .execute() } override fun applyMigrations() { if (database.getTableVersion(this) == null) { database.setTableVersion(this, "0.4.0") } } override fun insert(entity: RPKShopCount): Int { database.create .insertInto( RPKIT_SHOP_COUNT, RPKIT_SHOP_COUNT.CHARACTER_ID, RPKIT_SHOP_COUNT.COUNT ) .values( entity.character.id, entity.count ) .execute() val id = database.create.lastID().toInt() entity.id = id cache?.put(id, entity) characterCache?.put(entity.character.id, id) return id } override fun update(entity: RPKShopCount) { database.create .update(RPKIT_SHOP_COUNT) .set(RPKIT_SHOP_COUNT.CHARACTER_ID, entity.character.id) .set(RPKIT_SHOP_COUNT.COUNT, entity.count) .where(RPKIT_SHOP_COUNT.ID.eq(entity.id)) .execute() cache?.put(entity.id, entity) characterCache?.put(entity.character.id, entity.id) } override fun get(id: Int): RPKShopCount? { if (cache?.containsKey(id) == true) { return cache.get(id) } else { val result = database.create .select( RPKIT_SHOP_COUNT.CHARACTER_ID, RPKIT_SHOP_COUNT.COUNT ) .from(RPKIT_SHOP_COUNT) .where(RPKIT_SHOP_COUNT.ID.eq(id)) .fetchOne() ?: return null val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val characterId = result.get(RPKIT_SHOP_COUNT.CHARACTER_ID) val character = characterProvider.getCharacter(characterId) if (character != null) { val shopCount = RPKShopCount( id, character, result.get(RPKIT_SHOP_COUNT.COUNT) ) cache?.put(id, shopCount) characterCache?.put(shopCount.character.id, id) return shopCount } else { database.create .deleteFrom(RPKIT_SHOP_COUNT) .where(RPKIT_SHOP_COUNT.ID.eq(id)) .execute() characterCache?.remove(characterId) return null } } } /** * Gets the shop count for a character. * If there is no shop count for the given character * * @param character The character * @return The shop count for the character, or null if there is no shop count for the given character */ fun get(character: RPKCharacter): RPKShopCount? { if (characterCache?.containsKey(character.id) == true) { return get(characterCache.get(character.id)) } else { val result = database.create .select(RPKIT_SHOP_COUNT.ID) .from(RPKIT_SHOP_COUNT) .where(RPKIT_SHOP_COUNT.CHARACTER_ID.eq(character.id)) .fetchOne() ?: return null return get(result.get(RPKIT_SHOP_COUNT.ID)) } } override fun delete(entity: RPKShopCount) { database.create .deleteFrom(RPKIT_SHOP_COUNT) .where(RPKIT_SHOP_COUNT.ID.eq(entity.id)) .execute() cache?.remove(entity.id) characterCache?.remove(entity.character.id) } }
bukkit/rpk-shops-bukkit/src/main/kotlin/com/rpkit/shops/bukkit/database/table/RPKShopCountTable.kt
1126827024
package com.almasb.zeph.item import com.almasb.fxgl.dsl.getUIFactoryService import com.almasb.zeph.character.CharacterEntity import com.almasb.zeph.combat.Stat import javafx.beans.binding.Bindings import javafx.beans.property.SimpleIntegerProperty import javafx.beans.property.SimpleObjectProperty import javafx.beans.property.SimpleStringProperty import javafx.beans.value.ChangeListener import javafx.scene.paint.Color import java.util.concurrent.Callable enum class WeaponType(val range: Int, val aspdFactor: Float) { ONE_H_SWORD(2, 0.85f), ONE_H_AXE(2, 0.95f), DAGGER(1, 1.25f), SPEAR(3, 0.85f), MACE(2, 1.0f), ROD(5, 0.9f), SHIELD(0, 0.9f), // 1H, shield only left-hand TWO_H_SWORD(2, 0.7f), TWO_H_AXE(2, 0.65f), KATAR(1, 0.85f), BOW(5, 0.75f); fun isTwoHanded() = this.ordinal >= TWO_H_SWORD.ordinal } /** * Weapon item. * * @author Almas Baimagambetov ([email protected]) */ class Weapon(private val data: WeaponData) : EquipItem(data.description, data.itemLevel, data.runes, data.essences) { val element = SimpleObjectProperty(data.element) val pureDamage = SimpleIntegerProperty() val range get() = data.type.range val type get() = data.type private var damageListener: ChangeListener<Number>? = null init { pureDamage.bind(refineLevel.multiply(Bindings .`when`(refineLevel.greaterThan(2)) .then(data.itemLevel.bonus + 1) .otherwise(data.itemLevel.bonus)) .add(data.pureDamage)) dynamicDescription.bind( SimpleStringProperty("") .concat(description.name + "\n") .concat(description.description + "\n") .concat(element.asString("Element: %s").concat("\n")) .concat(pureDamage.asString("Damage: %d").concat("\n")) .concat(runes) .concat(essences) ) dynamicTextFlow.children.addAll( getUIFactoryService().newText("", Color.WHITE, 14.0).also { it.textProperty().bind(refineLevel.asString("Refinement Level: %d\n")) }, getUIFactoryService().newText("Element: ", Color.WHITE, 14.0), getUIFactoryService().newText("", 16.0).also { it.fillProperty().bind(Bindings.createObjectBinding(Callable { element.value.color }, element)) it.textProperty().bind(element.asString("%s\n")) }, getUIFactoryService().newText("Damage: ", Color.WHITE, 14.0), getUIFactoryService().newText("", Color.WHITE, 16.0).also { it.textProperty().bind(pureDamage.asString("%d\n")) } ) } fun onAttack(attacker: CharacterEntity, target: CharacterEntity) { data.onAttackScript.invoke(attacker, target) } override fun onEquip(char: CharacterEntity) { super.onEquip(char) char.addBonus(Stat.ATK, pureDamage.value) // TODO: the same thing for Armor equipment damageListener = ChangeListener<Number> { _, oldDamage, newDamage -> char.addBonus(Stat.ATK, -oldDamage.toInt()) char.addBonus(Stat.ATK, newDamage.toInt()) } pureDamage.addListener(damageListener) } override fun onUnEquip(char: CharacterEntity) { super.onUnEquip(char) char.addBonus(Stat.ATK, -pureDamage.value) damageListener?.let { pureDamage.removeListener(it) } } }
src/main/kotlin/com/almasb/zeph/item/Weapon.kt
1732987874
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.kork.sql import com.netflix.spinnaker.kork.PlatformComponents import com.netflix.spinnaker.kork.sql.config.DefaultSqlConfiguration import com.netflix.spinnaker.kork.sql.health.SqlHealthIndicator import org.jooq.DSLContext import org.jooq.impl.DSL.field import org.jooq.impl.DSL.table import org.junit.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.getBeansOfType import org.springframework.boot.actuate.health.HealthIndicator import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.test.context.SpringBootTest import org.springframework.context.ApplicationContext import org.springframework.context.annotation.Import import org.springframework.test.context.junit4.SpringRunner import strikt.api.expectThat import strikt.assertions.isA import strikt.assertions.isEqualTo import strikt.assertions.isNotNull @RunWith(SpringRunner::class) @SpringBootTest( classes = [StartupTestApp::class], properties = [ "sql.enabled=true", "sql.migration.jdbcUrl=jdbc:h2:mem:test", "sql.migration.dialect=H2", "sql.connectionPool.jdbcUrl=jdbc:h2:mem:test", "sql.connectionPool.dialect=H2" ] ) internal class SpringStartupTests { @Autowired lateinit var dbHealthIndicator: HealthIndicator @Autowired lateinit var jooq: DSLContext @Autowired lateinit var applicationContext: ApplicationContext @Test fun `uses SqlHealthIndicator`() { expectThat(dbHealthIndicator).isA<SqlHealthIndicator>() expectThat( jooq .insertInto(table("healthcheck"), listOf(field("id"))) .values(true).execute() ).isEqualTo(1) expectThat(applicationContext.getBeansOfType(DSLContext::class.java).size).isEqualTo(1) expectThat(applicationContext.getBean("jooq")).isNotNull() expectThat(applicationContext.getBean("liquibase")).isNotNull() } } @SpringBootApplication @Import(PlatformComponents::class, DefaultSqlConfiguration::class) internal class StartupTestApp
kork-sql/src/test/kotlin/com/netflix/spinnaker/kork/sql/SpringStartupTests.kt
2110086593
package it.achdjian.paolo.temperaturemonitor.graphic import android.content.Context import android.util.Log import android.view.MotionEvent import android.view.ScaleGestureDetector import android.view.View import it.achdjian.paolo.temperaturemonitor.domusEngine.DomusEngine import org.joda.time.LocalDateTime /** * Created by Paolo Achdjian on 11/14/17. */ class GraphViewScale(val networkAddress:Int, context: Context, val domusEngine: DomusEngine) : View.OnTouchListener, ScaleGestureDetector.OnScaleGestureListener { val scaleGestureDetector = ScaleGestureDetector(context, this) var startSpanX = 0.0f; var end = LocalDateTime() var start = end.minusDays(1) override fun onScaleBegin(detector: ScaleGestureDetector?): Boolean { if (detector != null) startSpanX = detector.currentSpanX; return true; } override fun onScaleEnd(detector: ScaleGestureDetector?) { if (detector != null) { val factor = detector.getCurrentSpanX() / startSpanX val period = (end.toDate().time - start.toDate().time)*factor val toNow = LocalDateTime().toDate().time - end.toDate().time if (toNow < period/2){ end= LocalDateTime() start = end.minusMillis(period.toInt()) } else { end = end.plusMillis((period/2).toInt()) start = start.minusMillis((period/2).toInt()) } domusEngine.getTemperatureData(networkAddress, start, end) Log.i("UI", "span: " + factor) Log.i("UI", "start: " + start + ", end: " + end) } } override fun onScale(detector: ScaleGestureDetector?): Boolean{ if (detector != null) { Log.i("UI", "span: " + detector.getCurrentSpanX() / startSpanX) } return true; } override fun onTouch(v: View?, event: MotionEvent?): Boolean { return scaleGestureDetector.onTouchEvent(event); } }
temperature_monitor/app/src/main/java/it/achdjian/paolo/temperaturemonitor/graphic/GraphViewScale.kt
3931504507
/* Copyright 2015 Andreas Würl 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.blitzortung.android.map.overlay import android.graphics.Canvas import android.graphics.Paint import android.graphics.RectF import android.graphics.drawable.shapes.Shape class ParticipantShape : Shape() { private val rect: RectF = RectF() private var color: Int = 0 init { color = 0 } override fun draw(canvas: Canvas, paint: Paint) { paint.color = color paint.alpha = 255 paint.style = Paint.Style.FILL canvas.drawRect(rect, paint) } fun update(size: Float, color: Int) { val halfSize = size / 2f rect.set(-halfSize, -halfSize, halfSize, halfSize) resize(rect.width(), rect.width()) this.color = color } }
app/src/main/java/org/blitzortung/android/map/overlay/ParticipantShape.kt
3940847310
package com.foo.graphql.mutation import com.foo.graphql.mutation.type.Flower import org.springframework.stereotype.Component import java.util.concurrent.atomic.AtomicInteger @Component open class DataRepository { private val flowers = mutableMapOf<Int?, Flower>() private val counter = AtomicInteger(0) init { listOf(Flower(0, "Darcey", "Roses", "Red", 50), Flower(1, "Candy Prince", "Tulips", "Pink", 18), Flower(2, "Lily", "Lilies", "White", 30), Flower(3, "Lavender", "Limonium", "Purple", 25) ).forEach { flowers[it.id] = it } } fun allFlowers(): Collection<Flower> = flowers.values fun saveFlower(name: String?, type: String? , color: String?, price: Int?): Flower { val id = counter.getAndIncrement() return Flower(id, name, type, color, price) } }
e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/mutation/DataRepository.kt
3097703782
/* * Copyright 2000-2021 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"). * See LICENSE in the project root for license information. */ package jetbrains.buildServer.rust.commands.cargo import jetbrains.buildServer.rust.CargoConstants import jetbrains.buildServer.rust.commands.CommandType /** * Provides parameters for cargo clean command. */ class ClippyCommandType : CommandType { override val name: String get() = CargoConstants.COMMAND_CLIPPY override val editPage: String get() = "editClippyParameters.jsp" override val viewPage: String get() = "viewClippyParameters.jsp" }
plugin-rust-server/src/main/kotlin/jetbrains/buildServer/rust/commands/cargo/ClippyCommandType.kt
296008485
package trypp.support.pattern import trypp.support.memory.Pool import trypp.support.memory.Poolable import trypp.support.pattern.observer.Event3 import trypp.support.pattern.observer.Event4 import java.util.* /** * Encapsulation of a finite state machine. * * You instantiate a state machine by registering a list of states and a list of events that it can * accept in each state. * * You must [freeze] a state machine before you can start using it. Once frozen, you can't * register any more states. * * @param S An enumeration type that represents the known states this machine can get into. * @param E An enumeration type that represents the known events this machine can accept. * @param initialState The first state this machine will start out in */ class StateMachine<S : Enum<S>, E : Enum<E>>(private val initialState: S) { internal data class StateEventKey(var state: Any?, var event: Any?) : Poolable { constructor() : this(null, null) override fun reset() { state = null event = null } } /** * Method for handling a state transition. Given a state and an event, run some logic and then * return the new state that the state machine should be in. */ interface EventHandler<S : Enum<S>, E : Enum<E>> { fun run(state: S, event: E, eventData: Any?): S } var currentState = initialState private set /** * Event that is triggered anytime a successful state transition occurs. * * S - oldState * E - event * S - newState * Any? - eventData * * The event will be run on the same thread [handle] is called on. */ val onTransition = Event4<S, E, S, Any?>() /** * Method that is called anytime an event is unhandled. Often useful for logging. * * S - state * E - event * Any? - eventData * * The event will be run on the same thread [handle] is called on. */ val onUnhandled = Event3<S, E, Any?>() private val eventHandlers = HashMap<StateEventKey, EventHandler<S, E>>() private val keyPool = Pool.of(StateEventKey::class, capacity = 1) var frozen = false private set /** * Reset this state machine back to its initial state. */ fun reset() { currentState = initialState frozen = false keyPool.freeAll() eventHandlers.clear() onTransition.clearListeners() onUnhandled.clearListeners() } /** * Register a state and a handler for whenever we receive an event in that state. * * The handler will be called on the same thread that [handle] is called on. * * @throws IllegalArgumentException if duplicate state/event pairs are registered */ fun registerTransition(state: S, event: E, handler: EventHandler<S, E>) { if (frozen) { throw IllegalStateException("Can't register transition on frozen state machine") } val key = StateEventKey(state, event) if (eventHandlers.containsKey(key)) { throw IllegalArgumentException( "Duplicate registration of state+event pair: ${key.state}, ${key.event}.") } eventHandlers.put(key, handler) } /** * Convenience method for [registerTransition] that takes a lambda for conciseness. */ fun registerTransition(state: S, event: E, handle: (S, E, Any?) -> S) { registerTransition(state, event, object : EventHandler<S, E> { override fun run(state: S, event: E, eventData: Any?): S { return handle(state, event, eventData) } }) } fun freeze() { if (frozen) { throw IllegalStateException("Can't freeze already frozen state machine") } frozen = true } /** * Tell the state machine to handle the passed in event given the current state. */ fun handle(event: E): Boolean { return handle(event, null) } /** * Like [handle] but with some additional data that is related to the event. */ fun handle(event: E, eventData: Any?): Boolean { if (!frozen) { throw IllegalStateException("You must freeze this state machine before firing events") } val key = keyPool.grabNew() key.state = currentState key.event = event val eventHandler = eventHandlers[key] keyPool.free(key) val prevState = currentState if (eventHandler != null) { currentState = eventHandler.run(prevState, event, eventData) onTransition(prevState, event, currentState, eventData) return true } else { onUnhandled(currentState, event, eventData) return false } } }
src/main/code/trypp/support/pattern/StateMachine.kt
2832014294
package cx.ring.views import androidx.recyclerview.widget.RecyclerView import cx.ring.databinding.ItemConferenceParticipantBinding import io.reactivex.rxjava3.disposables.Disposable /* class ParticipantView(val participantBinding: ItemConferenceParticipantBinding? = null, val addBinding: ItemConferenceAddBinding? = null) : RecyclerView.ViewHolder(participantBinding?.root ?: addBinding!!.root) { var disposable: Disposable? = null }*/ class ParticipantView(val participantBinding: ItemConferenceParticipantBinding): RecyclerView.ViewHolder(participantBinding.root) { var disposable: Disposable? = null }
ring-android/app/src/main/java/cx/ring/views/ParticipantView.kt
3383074972
package com.elkriefy.games.belote.model /** * */ enum class Value(val sofix: String) { SEVEN("7"), EIGHT("8"), NINE("9"), TEN("10"), JACK("jack"), QUEEN("queen"), KING("king"), ACE("ace") }
Belote/app/src/main/java/com/elkriefy/games/belote/model/Value.kt
1069746720
package cheetatech.com.colorhub.defines /** * Created by coderkan on 29.06.2017. */ data class ColorData(var name: String, var code: String)
app/src/main/java/cheetatech/com/colorhub/defines/ColorData.kt
3173378018
/* * Copyright 2020 Esri * * 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.esri.arcgisruntime.sample.routearoundbarriers import android.graphics.Color import android.graphics.drawable.BitmapDrawable import android.os.Bundle import android.util.Log import android.view.MotionEvent import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.widget.* import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.content.ContextCompat import com.esri.arcgisruntime.ArcGISRuntimeEnvironment import com.esri.arcgisruntime.geometry.GeometryEngine import com.esri.arcgisruntime.geometry.Point import com.esri.arcgisruntime.loadable.LoadStatus import com.esri.arcgisruntime.mapping.ArcGISMap import com.esri.arcgisruntime.mapping.BasemapStyle import com.esri.arcgisruntime.mapping.Viewpoint import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener import com.esri.arcgisruntime.mapping.view.Graphic import com.esri.arcgisruntime.mapping.view.GraphicsOverlay import com.esri.arcgisruntime.mapping.view.MapView import com.esri.arcgisruntime.sample.routearoundbarriers.databinding.ActivityMainBinding import com.esri.arcgisruntime.symbology.CompositeSymbol import com.esri.arcgisruntime.symbology.PictureMarkerSymbol import com.esri.arcgisruntime.symbology.SimpleFillSymbol import com.esri.arcgisruntime.symbology.SimpleLineSymbol import com.esri.arcgisruntime.symbology.SimpleRenderer import com.esri.arcgisruntime.symbology.TextSymbol import com.esri.arcgisruntime.tasks.networkanalysis.DirectionManeuver import com.esri.arcgisruntime.tasks.networkanalysis.PolygonBarrier import com.esri.arcgisruntime.tasks.networkanalysis.Route import com.esri.arcgisruntime.tasks.networkanalysis.RouteParameters import com.esri.arcgisruntime.tasks.networkanalysis.RouteResult import com.esri.arcgisruntime.tasks.networkanalysis.RouteTask import com.esri.arcgisruntime.tasks.networkanalysis.Stop import com.google.android.material.bottomsheet.BottomSheetBehavior import kotlin.math.roundToInt class MainActivity : AppCompatActivity() { private val TAG: String = MainActivity::class.java.simpleName private var bottomSheetBehavior: BottomSheetBehavior<View>? = null private var routeTask: RouteTask? = null private var routeParameters: RouteParameters? = null private var pinSymbol: PictureMarkerSymbol? = null private val routeGraphicsOverlay by lazy { GraphicsOverlay() } private val stopsGraphicsOverlay by lazy { GraphicsOverlay() } private val barriersGraphicsOverlay by lazy { GraphicsOverlay() } private val stopList by lazy { mutableListOf<Stop>() } private val barrierList by lazy { mutableListOf<PolygonBarrier>() } private val directionsList by lazy { mutableListOf<DirectionManeuver>() } private val routeLineSymbol by lazy { SimpleLineSymbol( SimpleLineSymbol.Style.SOLID, Color.BLUE, 5.0f ) } private val barrierSymbol by lazy { SimpleFillSymbol( SimpleFillSymbol.Style.DIAGONAL_CROSS, Color.RED, null ) } private val activityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } private val mapView: MapView by lazy { activityMainBinding.mapView } private val mapViewContainer: ConstraintLayout by lazy { activityMainBinding.mapViewContainer } private val resetButton: Button by lazy { activityMainBinding.resetButton } private val bottomSheet: LinearLayout by lazy { activityMainBinding.bottomSheet.bottomSheetLayout } private val header: ConstraintLayout by lazy { activityMainBinding.bottomSheet.header } private val imageView: ImageView by lazy { activityMainBinding.bottomSheet.imageView } private val addStopButton: ToggleButton by lazy { activityMainBinding.bottomSheet.addStopButton } private val addBarrierButton: ToggleButton by lazy { activityMainBinding.bottomSheet.addBarrierButton } private val reorderCheckBox: CheckBox by lazy { activityMainBinding.bottomSheet.reorderCheckBox } private val preserveFirstStopCheckBox: CheckBox by lazy { activityMainBinding.bottomSheet.preserveFirstStopCheckBox } private val preserveLastStopCheckBox: CheckBox by lazy { activityMainBinding.bottomSheet.preserveLastStopCheckBox } private val directionsTextView: TextView by lazy { activityMainBinding.bottomSheet.directionsTextView } private val directionsListView: ListView by lazy { activityMainBinding.bottomSheet.directionsListView } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(activityMainBinding.root) // authentication with an API key or named user is required to access basemaps and other // location services ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY) // create simple renderer for routes, and set it to use the line symbol routeGraphicsOverlay.renderer = SimpleRenderer().apply { symbol = routeLineSymbol } mapView.apply { // add a map with the streets basemap to the map view, centered on San Diego map = ArcGISMap(BasemapStyle.ARCGIS_STREETS) // center on San Diego setViewpoint(Viewpoint(32.7270, -117.1750, 40000.0)) // add the graphics overlays to the map view graphicsOverlays.addAll( listOf(stopsGraphicsOverlay, barriersGraphicsOverlay, routeGraphicsOverlay) ) onTouchListener = object : DefaultMapViewOnTouchListener(this@MainActivity, mapView) { override fun onSingleTapConfirmed(motionEvent: MotionEvent): Boolean { val screenPoint = android.graphics.Point( motionEvent.x.roundToInt(), motionEvent.y.roundToInt() ) addStopOrBarrier(screenPoint) return true } } } // create a new picture marker from a pin drawable pinSymbol = PictureMarkerSymbol.createAsync( ContextCompat.getDrawable( this, R.drawable.pin_symbol ) as BitmapDrawable ).get().apply { width = 30f height = 30f offsetY = 20f } // create route task from San Diego service routeTask = RouteTask( this, "https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route" ).apply { addDoneLoadingListener { if (loadStatus == LoadStatus.LOADED) { // get default route parameters val routeParametersFuture = createDefaultParametersAsync() routeParametersFuture.addDoneListener { try { routeParameters = routeParametersFuture.get().apply { // set flags to return stops and directions isReturnStops = true isReturnDirections = true } } catch (e: Exception) { Log.e(TAG, "Cannot create RouteTask parameters " + e.message) } } } else { Log.e(TAG, "Unable to load RouteTask $loadStatus") } } } routeTask?.loadAsync() // shrink the map view so it is not hidden under the bottom sheet header bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet) (mapViewContainer.layoutParams as CoordinatorLayout.LayoutParams).bottomMargin = (bottomSheetBehavior as BottomSheetBehavior<View>).peekHeight bottomSheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED bottomSheet.apply { // expand or collapse the bottom sheet when the header is clicked header.setOnClickListener { bottomSheetBehavior?.state = when (bottomSheetBehavior?.state) { BottomSheetBehavior.STATE_COLLAPSED -> BottomSheetBehavior.STATE_HALF_EXPANDED else -> BottomSheetBehavior.STATE_COLLAPSED } } // rotate the arrow so it starts off in the correct rotation imageView.rotation = 180f } // change button toggle state on click addStopButton.setOnClickListener { addBarrierButton.isChecked = false } addBarrierButton.setOnClickListener { addStopButton.isChecked = false } // solve route on checkbox change state reorderCheckBox.setOnCheckedChangeListener { _, _ -> createAndDisplayRoute() } preserveFirstStopCheckBox.setOnCheckedChangeListener { _, _ -> createAndDisplayRoute() } preserveLastStopCheckBox.setOnCheckedChangeListener { _, _ -> createAndDisplayRoute() } // start sample with add stop button true addStopButton.isChecked = true } /** * Add a stop or a point to the correct graphics overlay depending on which button is currently * checked. * * @param screenPoint at which to create a stop or point */ private fun addStopOrBarrier(screenPoint: android.graphics.Point) { // convert screen point to map point val mapPoint = mapView.screenToLocation(screenPoint) // normalize geometry - important for geometries that will be sent to a server for processing val normalizedPoint = GeometryEngine.normalizeCentralMeridian(mapPoint) as Point // clear the displayed route, if it exists, since it might not be up to date any more routeGraphicsOverlay.graphics.clear() if (addStopButton.isChecked) { // use the clicked map point to construct a stop val stopPoint = Stop(Point(normalizedPoint.x, normalizedPoint.y, mapPoint.spatialReference)) // add the new stop to the list of stops stopList.add(stopPoint) // create a marker symbol and graphics, and add the graphics to the graphics overlay stopsGraphicsOverlay.graphics.add( Graphic( mapPoint, createCompositeStopSymbol(stopList.size) ) ) } else if (addBarrierButton.isChecked) { // create a buffered polygon around the clicked point val bufferedBarrierPolygon = GeometryEngine.buffer(mapPoint, 200.0) // create a polygon barrier for the routing task, and add it to the list of barriers barrierList.add(PolygonBarrier(bufferedBarrierPolygon)) // build graphics for the barrier and add it to the graphics overlay barriersGraphicsOverlay.graphics.add(Graphic(bufferedBarrierPolygon, barrierSymbol)) } createAndDisplayRoute() } /** * Create route parameters and a route task from them. Display the route result geometry as a * graphic and call showDirectionsInBottomSheet which shows directions in a list view. */ private fun createAndDisplayRoute() { if (stopList.size < 2) { // clear the directions list since no route is displayed directionsList.clear() return } // clear the previous route from the graphics overlay, if it exists routeGraphicsOverlay.graphics.clear() // clear the directions list from the directions list view, if they exist directionsList.clear() routeParameters?.apply { // add the existing stops and barriers to the route parameters setStops(stopList) setPolygonBarriers(barrierList) // apply the requested route finding parameters isFindBestSequence = reorderCheckBox.isChecked isPreserveFirstStop = preserveFirstStopCheckBox.isChecked isPreserveLastStop = preserveLastStopCheckBox.isChecked } // solve the route task val routeResultFuture = routeTask?.solveRouteAsync(routeParameters) routeResultFuture?.addDoneListener { try { val routeResult: RouteResult = routeResultFuture.get() if (routeResult.routes.isNotEmpty()) { // get the first route result val firstRoute: Route = routeResult.routes[0] // create a graphic for the route and add it to the graphics overlay val routeGraphic = Graphic(firstRoute.routeGeometry) routeGraphicsOverlay.graphics.add(routeGraphic) // get the direction text for each maneuver and add them to the list to display directionsList.addAll(firstRoute.directionManeuvers) showDirectionsInBottomSheet() } else { Toast.makeText(this, "No routes found.", Toast.LENGTH_LONG).show() } } catch (e: Exception) { val error = "Solve route task failed: " + e.message Log.e(TAG, error) Toast.makeText(this, error, Toast.LENGTH_LONG).show() } // show the reset button resetButton.visibility = VISIBLE } } /** * Clear all stops and polygon barriers from the route parameters, stop and barrier * lists and all graphics overlays. Also hide the directions list view and show the control * layout. * * @param reset button which calls this method */ fun clearRouteAndGraphics(reset: View) { // clear stops from route parameters and stops list routeParameters?.clearStops() stopList.clear() // clear barriers from route parameters and barriers list routeParameters?.clearPolygonBarriers() barrierList.clear() // clear the directions list directionsList.clear() // clear all graphics overlays mapView.graphicsOverlays.forEach { it.graphics.clear() } // hide the reset button and directions list resetButton.visibility = GONE // hide the directions directionsTextView.visibility = GONE directionsListView.visibility = GONE } /** * Create a composite symbol consisting of a pin graphic overlaid with a particular stop number. * * @param stopNumber to overlay the pin symbol * @return a composite symbol consisting of the pin graphic overlaid with an the stop number */ private fun createCompositeStopSymbol(stopNumber: Int): CompositeSymbol { // determine the stop number and create a new label val stopTextSymbol = TextSymbol( 16f, stopNumber.toString(), -0x1, TextSymbol.HorizontalAlignment.CENTER, TextSymbol.VerticalAlignment.BOTTOM ) stopTextSymbol.offsetY = pinSymbol?.height as Float / 2 // construct a composite symbol out of the pin and text symbols, and return it return CompositeSymbol(listOf(pinSymbol, stopTextSymbol)) } /** * Creates a bottom sheet to display a list of direction maneuvers. */ private fun showDirectionsInBottomSheet() { // show the directions list view directionsTextView.visibility = VISIBLE directionsListView.visibility = VISIBLE // create a bottom sheet behavior from the bottom sheet view in the main layout bottomSheetBehavior?.apply { // animate the arrow when the bottom sheet slides addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { override fun onSlide(bottomSheet: View, slideOffset: Float) { imageView.rotation = slideOffset * 180f } override fun onStateChanged(bottomSheet: View, newState: Int) { imageView.rotation = when (newState) { BottomSheetBehavior.STATE_EXPANDED -> 180f else -> imageView.rotation } } }) } directionsListView.apply { // Set the adapter for the list view adapter = ArrayAdapter( this@MainActivity, android.R.layout.simple_list_item_1, directionsList.map { it.directionText }) // when the user taps a maneuver, set the viewpoint to that portion of the route onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> // remove any graphics that are not the original (blue) route graphic if (routeGraphicsOverlay.graphics.size > 1) { routeGraphicsOverlay.graphics.removeAt(routeGraphicsOverlay.graphics.size - 1) } // set the viewpoint to the selected maneuver val geometry = directionsList[position].geometry mapView.setViewpointAsync(Viewpoint(geometry.extent, 20.0), 1f) // create a graphic with a symbol for the maneuver and add it to the graphics overlay val selectedRouteSymbol = SimpleLineSymbol( SimpleLineSymbol.Style.SOLID, Color.GREEN, 5f ) routeGraphicsOverlay.graphics.add(Graphic(geometry, selectedRouteSymbol)) // collapse the bottom sheet bottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED } // allow the list view to scroll within bottom sheet isNestedScrollingEnabled = true } } override fun onPause() { mapView.pause() super.onPause() } override fun onResume() { super.onResume() mapView.resume() } override fun onDestroy() { mapView.dispose() super.onDestroy() } }
kotlin/route-around-barriers/src/main/java/com/esri/arcgisruntime/sample/routearoundbarriers/MainActivity.kt
4058707727