content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.keenencharles.unsplash.models import com.google.gson.annotations.SerializedName data class SearchResults<T>( var total: Int? = null, var results: List<T> = listOf(), @SerializedName("total_pages") var totalPages: Int? = null )
androidunsplash/src/main/java/com/keenencharles/unsplash/models/SearchResults.kt
3885651449
package org.jetbrains.settingsRepository import com.intellij.credentialStore.Credentials import com.intellij.testFramework.ApplicationRule import org.assertj.core.api.Assertions.assertThat import org.eclipse.jgit.storage.file.FileRepositoryBuilder import org.eclipse.jgit.transport.CredentialItem import org.eclipse.jgit.transport.URIish import org.jetbrains.settingsRepository.git.JGitCredentialsProvider import org.junit.ClassRule import org.junit.Test import java.io.File internal class IcsCredentialTest { companion object { @JvmField @ClassRule val projectRule = ApplicationRule() } private fun createProvider(credentialsStore: IcsCredentialsStore): JGitCredentialsProvider { return JGitCredentialsProvider(lazyOf(credentialsStore), FileRepositoryBuilder().setBare().setGitDir(File("/tmp/fake")).build()) } private fun createStore() = IcsCredentialsStore() @Test fun explicitSpecifiedInURL() { val credentialsStore = createStore() val username = CredentialItem.Username() val password = CredentialItem.Password() val uri = URIish("https://develar:[email protected]/develar/settings-repository.git") assertThat(createProvider(credentialsStore).get(uri, username, password)).isTrue() assertThat(username.value).isEqualTo("develar") assertThat(String(password.value!!)).isEqualTo("bike") // ensure that credentials store was not used assertThat(credentialsStore.get(uri.host, null, null)).isNull() } @Test fun gitCredentialHelper() { val credentialStore = createStore() credentialStore.set("bitbucket.org", null, Credentials("develar", "bike")) val username = CredentialItem.Username() val password = CredentialItem.Password() val uri = URIish("https://[email protected]/develar/test-ics.git") assertThat(createProvider(credentialStore).get(uri, username, password)).isTrue() assertThat(username.value).isEqualTo("develar") assertThat(String(password.value!!)).isNotEmpty() } @Test fun userByServiceName() { val credentialStore = createStore() credentialStore.set("bitbucket.org", null, Credentials("develar", "bike")) val username = CredentialItem.Username() val password = CredentialItem.Password() val uri = URIish("https://bitbucket.org/develar/test-ics.git") assertThat(createProvider(credentialStore).get(uri, username, password)).isTrue() assertThat(username.value).isEqualTo("develar") assertThat(String(password.value!!)).isNotEmpty() } }
plugins/settings-repository/testSrc/IcsCredentialTest.kt
4054039827
/* * Copyright 2022 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.grpc.examples.helloworld import io.grpc.testing.GrpcServerRule import kotlinx.coroutines.runBlocking import org.junit.Rule import kotlin.test.Test import kotlin.test.assertEquals class HelloWorldServerTest { @get:Rule val grpcServerRule: GrpcServerRule = GrpcServerRule().directExecutor() @Test fun sayHello() = runBlocking { val service = HelloWorldServer.HelloWorldService() grpcServerRule.serviceRegistry.addService(service) val stub = GreeterGrpcKt.GreeterCoroutineStub(grpcServerRule.channel) val testName = "test name" val reply = stub.sayHello(helloRequest { name = testName }) assertEquals("Hello $testName", reply.message) } }
examples/server/src/test/kotlin/io/grpc/examples/helloworld/HelloWorldServerTest.kt
787010731
package com.fsck.k9.storage.migrations import android.database.sqlite.SQLiteDatabase /** * Add 'new_message' column to 'messages' table. */ internal class MigrationTo82(private val db: SQLiteDatabase) { fun addNewMessageColumn() { db.execSQL("ALTER TABLE messages ADD new_message INTEGER DEFAULT 0") db.execSQL("DROP INDEX IF EXISTS new_messages") db.execSQL("CREATE INDEX IF NOT EXISTS new_messages ON messages(new_message)") db.execSQL( "CREATE TRIGGER new_message_reset " + "AFTER UPDATE OF read ON messages " + "FOR EACH ROW WHEN NEW.read = 1 AND NEW.new_message = 1 " + "BEGIN " + "UPDATE messages SET new_message = 0 WHERE ROWID = NEW.ROWID; " + "END" ) // Mark messages with existing notifications as "new" db.execSQL("UPDATE messages SET new_message = 1 WHERE id in (SELECT message_id FROM notifications)") } }
app/storage/src/main/java/com/fsck/k9/storage/migrations/MigrationTo82.kt
1960561798
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.util.RadioUpDownListener import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtEnumEntry import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import java.awt.BorderLayout import javax.swing.* internal class KotlinSelectNestedClassRefactoringDialog private constructor( project: Project, private val nestedClass: KtClassOrObject, private val targetContainer: PsiElement? ) : DialogWrapper(project, true) { private val moveToUpperLevelButton = JRadioButton() private val moveMembersButton = JRadioButton() init { title = RefactoringBundle.message("select.refactoring.title") init() } override fun createNorthPanel() = JLabel(RefactoringBundle.message("what.would.you.like.to.do")) override fun getPreferredFocusedComponent() = moveToUpperLevelButton override fun getDimensionServiceKey(): String { return "#org.jetbrains.kotlin.idea.refactoring.move.moveTopLevelDeclarations.ui.KotlinSelectInnerOrMembersRefactoringDialog" } override fun createCenterPanel(): JComponent { moveToUpperLevelButton.text = KotlinBundle.message("button.text.move.nested.class.0.to.upper.level", nestedClass.name.toString()) moveToUpperLevelButton.isSelected = true moveMembersButton.text = KotlinBundle.message("button.text.move.nested.class.0.to.another.class", nestedClass.name.toString()) ButtonGroup().apply { add(moveToUpperLevelButton) add(moveMembersButton) } RadioUpDownListener(moveToUpperLevelButton, moveMembersButton) return JPanel(BorderLayout()).apply { val box = Box.createVerticalBox().apply { add(Box.createVerticalStrut(5)) add(moveToUpperLevelButton) add(moveMembersButton) } add(box, BorderLayout.CENTER) } } fun getNextDialog(): DialogWrapper? { return when { moveToUpperLevelButton.isSelected -> MoveKotlinNestedClassesToUpperLevelDialog(nestedClass, targetContainer) moveMembersButton.isSelected -> MoveKotlinNestedClassesDialog(nestedClass, targetContainer) else -> null } } companion object { private fun MoveKotlinNestedClassesToUpperLevelDialog( nestedClass: KtClassOrObject, targetContainer: PsiElement? ): MoveKotlinNestedClassesToUpperLevelDialog? { val outerClass = nestedClass.containingClassOrObject ?: return null val newTarget = targetContainer ?: outerClass.containingClassOrObject ?: outerClass.containingFile.let { it.containingDirectory ?: it } return MoveKotlinNestedClassesToUpperLevelDialog(nestedClass.project, nestedClass, newTarget) } private fun MoveKotlinNestedClassesDialog( nestedClass: KtClassOrObject, targetContainer: PsiElement? ): MoveKotlinNestedClassesDialog { return MoveKotlinNestedClassesDialog( nestedClass.project, listOf(nestedClass), nestedClass.containingClassOrObject!!, targetContainer as? KtClassOrObject ?: nestedClass.containingClassOrObject!!, targetContainer as? PsiDirectory, null ) } fun chooseNestedClassRefactoring(nestedClass: KtClassOrObject, targetContainer: PsiElement?) { val project = nestedClass.project val dialog = when { targetContainer.isUpperLevelFor(nestedClass) -> MoveKotlinNestedClassesToUpperLevelDialog(nestedClass, targetContainer) nestedClass is KtEnumEntry -> return else -> { val selectionDialog = KotlinSelectNestedClassRefactoringDialog( project, nestedClass, targetContainer ) selectionDialog.show() if (selectionDialog.exitCode != OK_EXIT_CODE) return selectionDialog.getNextDialog() ?: return } } dialog?.show() } private fun PsiElement?.isUpperLevelFor(nestedClass: KtClassOrObject) = this != null && this !is KtClassOrObject && this !is PsiDirectory || nestedClass is KtClass && nestedClass.isInner() } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ui/KotlinSelectNestedClassRefactoringDialog.kt
2005062625
package org.hexworks.zircon.api.builder.fragment import org.hexworks.zircon.api.Beta import org.hexworks.zircon.api.component.Component import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.fragment.builder.FragmentBuilder import org.hexworks.zircon.internal.dsl.ZirconDsl import org.hexworks.zircon.internal.fragment.impl.TableColumn import kotlin.jvm.JvmStatic @ZirconDsl @Beta class TableColumnBuilder<T : Any, V : Any, C : Component> private constructor( /** * The name of this column. It will be used as table header. */ var name: String = "", /** * The width of this column. The component created by [cellRenderer] * may not be wider than this. */ var width: Int = 0, /** * This function will be used to extract the column value out of the * table model object */ var valueProvider: ((T) -> V)? = null, /** * This function will be used to create a component to display the * cell. */ var cellRenderer: ((V) -> C)? = null ) : FragmentBuilder<TableColumn<T, V, C>, TableColumnBuilder<T, V, C>> { override fun build(): TableColumn<T, V, C> { require(width > 0) { "The minimum column width is 1. $width was provided." } return TableColumn( name = name, width = width, valueProvider = valueProvider ?: error("Value provider is missing"), cellRenderer = cellRenderer ?: error("Cell renderer is missing") ) } companion object { @JvmStatic fun <T : Any, V : Any, C : Component> newBuilder() = TableColumnBuilder<T, V, C>() } override fun createCopy() = TableColumnBuilder( name = name, width = width, valueProvider = valueProvider, cellRenderer = cellRenderer ) override fun withPosition(position: Position): TableColumnBuilder<T, V, C> { error("Can't set the position of a table column") } }
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/fragment/TableColumnBuilder.kt
200851986
package ktn.pe class Pe9 : Pe { private var limit = 1000 override val problemNumber: Int get() = 9 fun pe9(limit: Int): Int { val last = (limit shr 1) + 1 for (x in 1 until last) { val x2 = x * x for (y in x until last) { val z = limit - x - y if (x2 + y * y == z * z) { return x * y * z } } } return 0 } override fun setArgs(args: Array<String>) { if (args.isNotEmpty()) { limit = args[0].toInt() } } override fun solve() { System.out.println(PeUtils.format(this, pe9(limit))) } override fun run() { solve() } }
kt/pe/src/main/kotlin/ktn/pe/Pe9.kt
2941240188
package com.ismail_s.jtime.android internal object Constants { @JvmField val MASJID_ID = "com.ismail_s.jtime.android.MASJID_ID" @JvmField val MASJID_NAME = "com.ismail_s.jtime.android.MASJID_NAME" }
JTime-android/src/main/kotlin/com/ismail_s/jtime/android/Constants.kt
4149267596
package org.hexworks.zircon.internal.dsl @DslMarker annotation class ZirconDsl
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/dsl/ZirconDsl.kt
635126207
package org.wordpress.android.ui.photopicker object MediaPickerConstants { const val EXTRA_MEDIA_URIS = "media_uris" const val EXTRA_MEDIA_QUEUED_URIS = "queued_media_uris" const val EXTRA_MEDIA_ID = "media_id" const val EXTRA_LAUNCH_WPSTORIES_CAMERA_REQUESTED = "launch_wpstories_camera_requested" const val EXTRA_LAUNCH_WPSTORIES_MEDIA_PICKER_REQUESTED = "launch_wpstories_media_picker_requested" const val EXTRA_SAVED_MEDIA_MODEL_LOCAL_IDS = "saved_media_model_local_ids" // the enum name of the source will be returned as a string in EXTRA_MEDIA_SOURCE const val EXTRA_MEDIA_SOURCE = "media_source" const val LOCAL_POST_ID = "local_post_id" }
WordPress/src/main/java/org/wordpress/android/ui/photopicker/MediaPickerConstants.kt
2185297024
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeInsight import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl import com.intellij.openapi.editor.Document import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.rt.execution.junit.FileComparisonFailure import com.intellij.testFramework.ExpectedHighlightingData import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.UsefulTestCase import junit.framework.TestCase import org.jetbrains.kotlin.idea.highlighter.markers.TestableLineMarkerNavigator import org.jetbrains.kotlin.idea.navigation.NavigationTestUtils import org.jetbrains.kotlin.idea.test.* import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.util.renderAsGotoImplementation import org.junit.Assert import java.io.File abstract class AbstractLineMarkersTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor { return KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE } fun doTest(path: String) = doTest(path) {} protected fun doAndCheckHighlighting( psiFile: PsiFile, documentToAnalyze: Document, expectedHighlighting: KotlinExpectedHighlightingData, expectedFile: File ): List<LineMarkerInfo<*>> { myFixture.doHighlighting() return checkHighlighting(psiFile, documentToAnalyze, expectedHighlighting, expectedFile) } fun doTest(unused: String, additionalCheck: () -> Unit) { val fileText = FileUtil.loadFile(dataFile()) try { ConfigLibraryUtil.configureLibrariesByDirective(myFixture.module, fileText) if (InTextDirectivesUtils.findStringWithPrefixes(fileText, "METHOD_SEPARATORS") != null) { DaemonCodeAnalyzerSettings.getInstance().SHOW_METHOD_SEPARATORS = true } val dependencySuffixes = listOf(".dependency.kt", ".dependency.java", ".dependency1.kt", ".dependency2.kt") for (suffix in dependencySuffixes) { val dependencyPath = fileName().replace(".kt", suffix) if (File(testDataDirectory, dependencyPath).exists()) { myFixture.configureByFile(dependencyPath) } } myFixture.configureByFile(fileName()) val project = myFixture.project val document = myFixture.editor.document val ktFile = myFixture.file as KtFile val data = KotlinExpectedHighlightingData(document) data.init() PsiDocumentManager.getInstance(project).commitAllDocuments() val markers = doAndCheckHighlighting(ktFile, document, data, dataFile()) assertNavigationElements(myFixture.project, ktFile, markers) additionalCheck() } catch (exc: Exception) { throw RuntimeException(exc) } finally { ConfigLibraryUtil.unconfigureLibrariesByDirective(module, fileText) DaemonCodeAnalyzerSettings.getInstance().SHOW_METHOD_SEPARATORS = false } } companion object { @Suppress("SpellCheckingInspection") private const val LINE_MARKER_PREFIX = "LINEMARKER:" private const val TARGETS_PREFIX = "TARGETS" fun assertNavigationElements(project: Project, file: KtFile, markers: List<LineMarkerInfo<*>>) { val navigationDataComments = KotlinTestUtils.getLastCommentsInFile( file, KotlinTestUtils.CommentType.BLOCK_COMMENT, false ) if (navigationDataComments.isEmpty()) return val markerCodeMetaInfos = markers.map { InnerLineMarkerCodeMetaInfo(InnerLineMarkerConfiguration.configuration, it) } for ((navigationCommentIndex, navigationComment) in navigationDataComments.reversed().withIndex()) { val description = getLineMarkerDescription(navigationComment) val navigateMarkers = markerCodeMetaInfos.filter { it.asString() == description } val navigateMarker = navigateMarkers.singleOrNull() ?: navigateMarkers.getOrNull(navigationCommentIndex) TestCase.assertNotNull( String.format("Can't find marker for navigation check with description \"%s\"\n\navailable: \n\n%s", description, markerCodeMetaInfos.joinToString("\n\n") { it.asString() }), navigateMarker ) val lineMarker = navigateMarker!!.lineMarker val handler = lineMarker.navigationHandler if (handler is TestableLineMarkerNavigator) { val navigateElements = handler.getTargetsPopupDescriptor(lineMarker.element)?.targets?.sortedBy { it.renderAsGotoImplementation() } val actualNavigationData = NavigationTestUtils.getNavigateElementsText(project, navigateElements) UsefulTestCase.assertSameLines(getExpectedNavigationText(navigationComment), actualNavigationData) } else { Assert.fail("Only TestableLineMarkerNavigator are supported in navigate check") } } } private fun getLineMarkerDescription(navigationComment: String): String { val firstLineEnd = navigationComment.indexOf("\n") TestCase.assertTrue( "The first line in block comment must contain description of marker for navigation check", firstLineEnd != -1 ) var navigationMarkerText = navigationComment.substring(0, firstLineEnd) TestCase.assertTrue( String.format("Add %s directive in first line of comment", LINE_MARKER_PREFIX), navigationMarkerText.startsWith(LINE_MARKER_PREFIX) ) navigationMarkerText = navigationMarkerText.substring(LINE_MARKER_PREFIX.length) return navigationMarkerText.trim { it <= ' ' } } private fun getExpectedNavigationText(navigationComment: String): String { val firstLineEnd = navigationComment.indexOf("\n") var expectedNavigationText = navigationComment.substring(firstLineEnd + 1) TestCase.assertTrue( String.format("Marker %s is expected before navigation data", TARGETS_PREFIX), expectedNavigationText.startsWith(TARGETS_PREFIX) ) expectedNavigationText = expectedNavigationText.substring(expectedNavigationText.indexOf("\n") + 1) return expectedNavigationText } fun checkHighlighting( psiFile: PsiFile, documentToAnalyze: Document, expectedHighlighting: ExpectedHighlightingData, expectedFile: File ): MutableList<LineMarkerInfo<*>> { val markers = DaemonCodeAnalyzerImpl.getLineMarkers(documentToAnalyze, psiFile.project) try { expectedHighlighting.checkLineMarkers(psiFile, markers, documentToAnalyze.text) // This is a workaround for sad bug in ExpectedHighlightingData: // the latter doesn't throw assertion error when some line markers are expected, but none are present. if (FileUtil.loadFile(expectedFile).contains("<lineMarker") && markers.isEmpty()) { throw AssertionError("Some line markers are expected, but nothing is present at all") } } catch (error: AssertionError) { try { val actualTextWithTestData = TagsTestDataUtil.insertInfoTags(markers, true, documentToAnalyze.text) KotlinTestUtils.assertEqualsToFile(expectedFile, actualTextWithTestData) } catch (failure: FileComparisonFailure) { throw FileComparisonFailure( error.message + "\n" + failure.message, failure.expected, failure.actual, failure.filePath ) } } return markers } } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/AbstractLineMarkersTest.kt
3487352310
// WITH_STDLIB fun test(list: List<Int>?): List<Int>? { return list?.filter { it > 1 }!!.<caret>filter { it > 2 }.filter { it > 3 } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/nullable2.kt
3951589577
// Using class is important // Test for EA-82700 open class A val test = object : A() { }
plugins/kotlin/live-templates/tests/testData/object_ForClass.exp.kt
3800515915
// 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 import com.intellij.lexer.Lexer import com.intellij.psi.impl.cache.impl.OccurrenceConsumer import com.intellij.psi.impl.cache.impl.id.LexerBasedIdIndexer import com.jetbrains.python.lexer.PythonLexer class PyIdIndexer : LexerBasedIdIndexer() { override fun createLexer(consumer: OccurrenceConsumer): Lexer { return createIndexingLexer(consumer) } companion object { fun createIndexingLexer(consumer: OccurrenceConsumer): Lexer { return PyFilterLexer(PythonLexer(), consumer) } } }
python/src/com/jetbrains/python/PyIdIndexer.kt
3966113167
package com.kelsos.mbrc.changelog import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.core.text.HtmlCompat import androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY import androidx.core.text.HtmlCompat.TO_HTML_PARAGRAPH_LINES_CONSECUTIVE import androidx.recyclerview.widget.RecyclerView class VersionAdapter(private val changeLog: List<ChangeLogEntry>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { class VersionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val version: TextView = itemView.findViewById(R.id.changelog_version__version) private val release: TextView = itemView.findViewById(R.id.changelog_version__release) fun bind(version: ChangeLogEntry.Version) { this.version.text = version.version this.release.text = version.release } companion object { fun from(parent: ViewGroup): VersionViewHolder { val inflater = LayoutInflater.from(parent.context) val itemView = inflater.inflate(R.layout.changelog_dialog__header, parent, false) return VersionViewHolder(itemView) } } } class EntryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val text: TextView = itemView.findViewById(R.id.changelog_entry__text) private val type: TextView = itemView.findViewById(R.id.changelog_entry__type) fun bind(entry: ChangeLogEntry.Entry) { val typeResId = when (entry.type) { is EntryType.BUG -> R.string.entry__bug is EntryType.FEATURE -> R.string.entry__feature is EntryType.REMOVED -> R.string.entry__removed } type.setText(typeResId) text.text = HtmlCompat.fromHtml(entry.text, FROM_HTML_MODE_LEGACY) } companion object { fun from(parent: ViewGroup): EntryViewHolder { val inflater = LayoutInflater.from(parent.context) val itemView = inflater.inflate(R.layout.changelog_dialog__entry, parent, false) return EntryViewHolder(itemView) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return when (viewType) { ITEM_VIEW_TYPE_HEADER -> VersionViewHolder.from(parent) ITEM_VIEW_TYPE_ITEM -> EntryViewHolder.from(parent) else -> throw ClassCastException("Unknown viewType $viewType") } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val version = changeLog[position] when (holder) { is VersionViewHolder -> holder.bind(version as ChangeLogEntry.Version) is EntryViewHolder -> holder.bind(version as ChangeLogEntry.Entry) } } override fun getItemViewType(position: Int): Int { return when (changeLog[position]) { is ChangeLogEntry.Version -> ITEM_VIEW_TYPE_HEADER is ChangeLogEntry.Entry -> ITEM_VIEW_TYPE_ITEM } } override fun getItemCount(): Int { return changeLog.size } companion object { private const val ITEM_VIEW_TYPE_HEADER = 0 private const val ITEM_VIEW_TYPE_ITEM = 1 } }
changelog/src/main/java/com/kelsos/mbrc/changelog/VersionAdapter.kt
2437448591
// 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.gradle.configuration.klib import com.intellij.util.containers.orNull import com.intellij.util.io.isFile import org.jetbrains.kotlin.library.KLIB_MANIFEST_FILE_NAME import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.zip.ZipEntry import java.util.zip.ZipFile internal fun interface KlibManifestProvider { fun getManifest(libraryPath: Path): Properties? companion object { fun default(): KlibManifestProvider { return CachedKlibManifestProvider( cache = mutableMapOf(), provider = CompositeKlibManifestProvider( listOf(DirectoryKlibManifestProvider(), ZipKlibManifestProvider) ) ) } } } internal interface KlibManifestFileFinder { fun getManifestFile(libraryPath: Path): Path? } internal class CompositeKlibManifestProvider( private val providers: List<KlibManifestProvider> ) : KlibManifestProvider { override fun getManifest(libraryPath: Path): Properties? { return providers.asSequence() .map { it.getManifest(libraryPath) } .filterNotNull() .firstOrNull() } } internal class CachedKlibManifestProvider( private val cache: MutableMap<Path, Properties> = mutableMapOf(), private val provider: KlibManifestProvider ) : KlibManifestProvider { override fun getManifest(libraryPath: Path): Properties? { return cache.getOrPut(libraryPath) { provider.getManifest(libraryPath) ?: return null } } } internal class DirectoryKlibManifestProvider( private val manifestFileFinder: KlibManifestFileFinder = DefaultKlibManifestFileFinder, ) : KlibManifestProvider { override fun getManifest(libraryPath: Path): Properties? { val file = manifestFileFinder.getManifestFile(libraryPath) ?: return null val properties = Properties() try { Files.newInputStream(file).use { properties.load(it) } return properties } catch (_: IOException) { return null } } } internal object ZipKlibManifestProvider : KlibManifestProvider { private val manifestEntryRegex = Regex("""(.+/manifest|manifest)""") override fun getManifest(libraryPath: Path): Properties? { if (!libraryPath.isFile()) return null try { val properties = Properties() val zipFile = ZipFile(libraryPath.toFile()) zipFile.use { val manifestEntry = zipFile.findManifestEntry() ?: return null zipFile.getInputStream(manifestEntry).use { manifestStream -> properties.load(manifestStream) } } return properties } catch (_: Exception) { return null } } private fun ZipFile.findManifestEntry(): ZipEntry? { return this.stream().filter { entry -> entry.name.matches(manifestEntryRegex) }.findFirst().orNull() } } private object DefaultKlibManifestFileFinder : KlibManifestFileFinder { override fun getManifestFile(libraryPath: Path): Path? { libraryPath.resolve(KLIB_MANIFEST_FILE_NAME).let { propertiesPath -> // KLIB layout without components if (Files.isRegularFile(propertiesPath)) return propertiesPath } if (!Files.isDirectory(libraryPath)) return null // look up through all components and find all manifest files val candidates = Files.newDirectoryStream(libraryPath).use { stream -> stream.mapNotNull { componentPath -> val candidate = componentPath.resolve(KLIB_MANIFEST_FILE_NAME) if (Files.isRegularFile(candidate)) candidate else null } } return when (candidates.size) { 0 -> null 1 -> candidates.single() else -> { // there are multiple components, let's take just the first one alphabetically candidates.minByOrNull { it.getName(it.nameCount - 2).toString() }!! } } } }
plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/configuration/klib/KlibManifestProvider.kt
294556720
package com.intellij.codeInsight.codeVision.ui.model import com.intellij.codeInsight.codeVision.CodeVisionEntry import com.intellij.codeInsight.codeVision.CodeVisionEntryExtraActionModel import com.intellij.openapi.util.NlsContexts @NlsContexts.Tooltip fun CodeVisionEntry.tooltipText(): String = [email protected] fun CodeVisionEntry.contextAvailable(): Boolean = [email protected]() fun CodeVisionEntryExtraActionModel.isEnabled(): Boolean = [email protected] != null
platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/model/Additional.kt
1363786109
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.perf.synthetic import com.intellij.testFramework.UsefulTestCase import com.intellij.usages.Usage import org.jetbrains.kotlin.idea.testFramework.Parameter import org.jetbrains.kotlin.idea.perf.profilers.ProfilerConfig import org.jetbrains.kotlin.idea.perf.suite.DefaultProfile import org.jetbrains.kotlin.idea.perf.suite.PerformanceSuite import org.jetbrains.kotlin.idea.perf.suite.StatsScopeConfig import org.jetbrains.kotlin.idea.perf.suite.suite import org.jetbrains.kotlin.idea.perf.util.* import org.jetbrains.kotlin.idea.perf.util.registerLoadingErrorsHeadlessNotifier import org.jetbrains.kotlin.idea.test.JUnit3RunnerWithInners import org.junit.runner.RunWith @RunWith(JUnit3RunnerWithInners::class) open class PerformanceStressTest : UsefulTestCase() { protected open fun profileConfig(): ProfilerConfig = ProfilerConfig() protected open fun outputConfig(): OutputConfig = OutputConfig() protected open fun suiteWithConfig(suiteName: String, name: String? = null, block: PerformanceSuite.StatsScope.() -> Unit) { suite( suiteName, config = StatsScopeConfig(name = name, outputConfig = outputConfig(), profilerConfig = profileConfig()), block = block ) } override fun setUp() { super.setUp() testRootDisposable.registerLoadingErrorsHeadlessNotifier() } fun testFindUsages() = doFindUsagesTest(false) fun testFindUsagesWithCompilerReferenceIndex() = doFindUsagesTest(true) private fun doFindUsagesTest(withCompilerIndex: Boolean) { // 1. Create 2 classes with the same name, but in a different packages // 2. Create 50 packages with a class that uses 50 times one of class from p.1 // 3. Use one of the classes from p.1 in the only one class at p.2 // 4. Run find usages of class that has limited usages // // Find usages have to resolve each reference due to the fact they have same names val numberOfFuns = 50 for (numberOfPackagesWithCandidates in arrayOf(30, 50, 100)) { val name = "findUsages${numberOfFuns}_$numberOfPackagesWithCandidates" + if (withCompilerIndex) "_with_cri" else "" suiteWithConfig(name) { app { warmUpProject() project { descriptor { name(name) module { kotlinStandardLibrary() for (index in 1..2) { kotlinFile("DataClass") { pkg("pkg$index") topClass("DataClass") { dataClass() ctorParameter(Parameter("name", "String")) ctorParameter(Parameter("value", "Int")) } } } for (pkgIndex in 1..numberOfPackagesWithCandidates) { kotlinFile("SomeService") { pkg("pkgX$pkgIndex") // use pkg1 for `pkgX1.SomeService`, and pkg2 for all other `pkgX*.SomeService` import("pkg${if (pkgIndex == 1) 1 else 2}.DataClass") topClass("SomeService") { for (index in 1..numberOfFuns) { function("foo$index") { returnType("DataClass") param("data", "DataClass") body("return DataClass(data.name, data.value + $index)") } } } } } } } profile(DefaultProfile) if (withCompilerIndex) { withCompiler() rebuildProject() } fixture("pkg1/DataClass.kt").use { fixture -> with(fixture.cursorConfig) { marker = "DataClass" } with(config) { warmup = 8 iterations = 15 } measure<Set<Usage>>(fixture, "findUsages") { before = { fixture.moveCursor() } test = { val findUsages = findUsages(fixture.cursorConfig) // 1 from import // + numberOfUsages as function argument // + numberOfUsages as return type functions // + numberOfUsages as new instance in a body of function // in a SomeService assertEquals(1 + 3 * numberOfFuns, findUsages.size) findUsages } } } } } } } } fun testBaseClassAndLotsOfSubClasses() { // there is a base class with several open functions // and lots of subclasses of it // KTIJ-21027 suiteWithConfig("Base class and lots of subclasses project", "ktij-21027 project") { app { warmUpProject() project { descriptor { name("ktij-21027") val baseClassFunctionNames = (0..10).map { "foo$it" } module { kotlinStandardLibrary() src("src/main/java/") kotlinFile("BaseClass") { pkg("pkg") topClass("BaseClass") { openClass() for (fnName in baseClassFunctionNames) { function(fnName) { openFunction() returnType("String") body("TODO()") } } } } for (classIndex in 0..5) { val superClassName = "SomeClass$classIndex" kotlinFile(superClassName) { pkg("pkg") topClass(superClassName) { openClass() superClass("BaseClass") for (fnName in baseClassFunctionNames) { function(fnName) { overrideFunction() returnType("String") body("TODO()") } } } } for (subclassIndex in 0..10) { val subClassName = "SubClass${classIndex}0${subclassIndex}" kotlinFile(subClassName) { pkg("pkg") topClass(subClassName) { superClass(superClassName) for (fnName in baseClassFunctionNames) { function(fnName) { overrideFunction() returnType("String") body("TODO()") } } } } } } } } profile(DefaultProfile) fixture("src/main/java/pkg/BaseClass.kt").use { fixture -> with(config) { warmup = 8 iterations = 15 } measureHighlight(fixture) } } } } } fun testLotsOfOverloadedMethods() { // KT-35135 val generatedTypes = mutableListOf(listOf<String>()) generateTypes(arrayOf("Int", "String", "Long", "List<Int>", "Array<Int>"), generatedTypes) suiteWithConfig("Lots of overloaded method project", "kt-35135 project") { app { warmUpProject() project { descriptor { name("kt-35135") module { kotlinStandardLibrary() src("src/main/java/") kotlinFile("OverloadX") { pkg("pkg") topClass("OverloadX") { openClass() for (types in generatedTypes) { function("foo") { openFunction() returnType("String") for ((index, type) in types.withIndex()) { param("arg$index", type) } body("TODO()") } } } } kotlinFile("SomeClass") { pkg("pkg") topClass("SomeClass") { superClass("OverloadX") body("ov") } } } } profile(DefaultProfile) fixture("src/main/java/pkg/SomeClass.kt").use { fixture -> with(fixture.typingConfig) { marker = "ov" insertString = "override fun foo(): String = TODO()" delayMs = 50 } with(config) { warmup = 8 iterations = 15 } measureTypeAndHighlight(fixture, "type override fun foo()") } } } } } private tailrec fun generateTypes(types: Array<String>, results: MutableList<List<String>>, index: Int = 0, maxCount: Int = 3000) { val newResults = mutableListOf<List<String>>() for (list in results) { if (list.size < index) continue for (t in types) { val newList = mutableListOf<String>() newList.addAll(list) newList.add(t) newResults.add(newList.toList()) if (results.size + newResults.size >= maxCount) { results.addAll(newResults) return } } } results.addAll(newResults) generateTypes(types, results, index + 1, maxCount) } fun testManyModulesExample() { suiteWithConfig("10 modules", "10 modules") { app { warmUpProject() project { descriptor { name("ten_modules") for(index in 0 until 10) { module("module$index") { kotlinStandardLibrary() for (libIndex in 0 until 10) { library("log4j$libIndex", "log4j:log4j:1.2.17") } kotlinFile("SomeService$index") { pkg("pkg") topClass("SomeService$index") { } } } } } } } } } }
plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/synthetic/PerformanceStressTest.kt
1173039908
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.createFromUsage import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.psi.KtElement abstract class CreateFromUsageFixBase<T : KtElement>(element: T) : KotlinQuickFixAction<T>(element) { override fun getFamilyName(): String = KotlinBundle.message("fix.create.from.usage.family") }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/CreateFromUsageFixBase.kt
3530530121
/* * Copyright 2021 Google LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.subscriptions.data.network.retrofit.authentication import com.example.subscriptions.BuildConfig import com.google.gson.GsonBuilder import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import okhttp3.logging.HttpLoggingInterceptor.Level import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.converter.scalars.ScalarsConverterFactory import java.util.concurrent.TimeUnit /** * Creates Retrofit instances that [ServerFunctionImpl] * uses to make authenticated HTTPS requests. * * @param <S> */ class RetrofitClient<S>(baseUrl: String, serviceClass: Class<S>) { private val service: S init { val gson = GsonBuilder().create() val loggingInterceptor = HttpLoggingInterceptor() loggingInterceptor.level = if (BuildConfig.DEBUG) Level.BASIC else Level.NONE val okHttpClient = OkHttpClient.Builder() .connectTimeout(NETWORK_TIMEOUT_SECONDS, TimeUnit.SECONDS) .readTimeout(NETWORK_TIMEOUT_SECONDS, TimeUnit.SECONDS) .writeTimeout(NETWORK_TIMEOUT_SECONDS, TimeUnit.SECONDS) .addInterceptor(loggingInterceptor) .addInterceptor(UserIdTokenInterceptor()) .build() val retrofit = Retrofit.Builder() .baseUrl(baseUrl) .client(okHttpClient) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .build() service = retrofit.create(serviceClass) } fun getService(): S { return service } companion object { private const val NETWORK_TIMEOUT_SECONDS: Long = 60 } }
ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/data/network/retrofit/authentication/RetrofitClient.kt
1060970292
package net.squanchy.eventdetails import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.transition.TransitionManager import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.activity_event_details.* import net.squanchy.R import net.squanchy.eventdetails.widget.EventDetailsRootLayout import net.squanchy.navigation.Navigator import net.squanchy.notification.scheduleNotificationWork import net.squanchy.schedule.domain.view.Event import net.squanchy.signin.SignInOrigin import net.squanchy.speaker.domain.view.Speaker import timber.log.Timber class EventDetailsActivity : AppCompatActivity() { private val subscriptions = CompositeDisposable() private lateinit var service: EventDetailsService private lateinit var navigator: Navigator private lateinit var eventId: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_event_details) setupToolbar() with(eventDetailsComponent(this)) { service = service() navigator = navigator() } } private fun setupToolbar() { setSupportActionBar(toolbar) supportActionBar!!.setDisplayShowTitleEnabled(false) supportActionBar!!.setDisplayHomeAsUpEnabled(true) } override fun onStart() { super.onStart() eventId = intent.getStringExtra(EXTRA_EVENT_ID) subscribeToEvent(eventId) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_CODE_SIGNIN) { subscribeToEvent(eventId) } else { super.onActivityResult(requestCode, resultCode, data) } } private fun subscribeToEvent(eventId: String) { subscriptions.add( service.event(eventId) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this@EventDetailsActivity::onDataReceived, Timber::e) ) } private fun onDataReceived(event: Event) { TransitionManager.beginDelayedTransition(eventDetailsRoot) eventDetailsRoot.updateWith(event, onEventDetailsClickListener(event)) } private fun onEventDetailsClickListener(event: Event): EventDetailsRootLayout.OnEventDetailsClickListener = object : EventDetailsRootLayout.OnEventDetailsClickListener { override fun onSpeakerClicked(speaker: Speaker) { navigator.toSpeakerDetails(speaker.id) } override fun onFavoriteClick() { subscriptions.add( service.toggleFavorite(event) .subscribe(::onFavouriteStateChange, Timber::e) ) } } private fun onFavouriteStateChange(result: EventDetailsService.FavoriteResult) { if (result === EventDetailsService.FavoriteResult.MUST_AUTHENTICATE) { requestSignIn() } else { triggerNotificationService() } } private fun requestSignIn() { navigator.toSignInForResult(REQUEST_CODE_SIGNIN, SignInOrigin.EVENT_DETAILS) unsubscribeFromUpdates() } private fun triggerNotificationService() { scheduleNotificationWork() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.event_details, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_search -> { navigator.toSearch(); true } android.R.id.home -> { finish(); true } else -> super.onOptionsItemSelected(item) } } override fun onStop() { super.onStop() unsubscribeFromUpdates() } private fun unsubscribeFromUpdates() { subscriptions.clear() } companion object { private val EXTRA_EVENT_ID = "${EventDetailsActivity::class.java.name}.event_id" private const val REQUEST_CODE_SIGNIN = 1235 fun createIntent(context: Context, eventId: String) = Intent(context, EventDetailsActivity::class.java).apply { putExtra(EXTRA_EVENT_ID, eventId) } } }
app/src/main/java/net/squanchy/eventdetails/EventDetailsActivity.kt
2666542704
package ireland.politics.root.politics import android.os.Bundle import android.support.v7.app.AppCompatActivity import hugo.weaving.DebugLog /** * Created by root on 21/01/17. */ class MainActivity : AppCompatActivity(){ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) getName("Jim","Stephens") } @DebugLog fun getName(first: String, last: String): String { return first + " " + last } }
app/src/main/java/ireland/politics/root/politics/MainActivity.kt
897620034
// 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.configurationStore import com.intellij.application.options.CodeStyle import com.intellij.openapi.util.JDOMUtil import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.codeStyle.CodeStyleSettingsProvider import com.intellij.psi.codeStyle.CustomCodeStyleSettings import com.intellij.testFramework.DisposableRule import com.intellij.testFramework.ExtensionTestUtil import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.util.containers.ContainerUtil import org.jdom.Element import org.junit.ClassRule import org.junit.Rule import org.junit.Test internal class CodeStyleTest { companion object { @JvmField @ClassRule val projectRule = ProjectRule(runPostStartUpActivities = false) } @JvmField @Rule val disposableRule = DisposableRule() @Test fun `do not remove unknown`() { val settings = CodeStyle.createTestSettings() val loaded = """ <code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}"> <UnknownDoNotRemoveMe> <option name="ALIGN_OBJECT_PROPERTIES" value="2" /> </UnknownDoNotRemoveMe> <codeStyleSettings language="CoffeeScript"> <option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" /> </codeStyleSettings> <codeStyleSettings language="DB2"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="Derby"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="Gherkin"> <indentOptions> <option name="USE_TAB_CHARACTER" value="true" /> </indentOptions> </codeStyleSettings> <codeStyleSettings language="H2"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="HSQLDB"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="MySQL"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="Oracle"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="PostgreSQL"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="SQL"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="SQLite"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="Sybase"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="TSQL"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> </code_scheme>""".trimIndent() settings.readExternal(JDOMUtil.load(loaded)) val serialized = Element("code_scheme").setAttribute("name", "testSchemeName") settings.writeExternal(serialized) assertThat(serialized).isEqualTo(loaded) } @Test fun `do not duplicate known extra sections`() { val newProvider: CodeStyleSettingsProvider = object : CodeStyleSettingsProvider() { override fun createCustomSettings(settings: CodeStyleSettings): CustomCodeStyleSettings { return object : CustomCodeStyleSettings("NewComponent", settings) { override fun getKnownTagNames(): List<String> { return ContainerUtil.concat(super.getKnownTagNames(), listOf("NewComponent-extra")) } override fun writeExternal(parentElement: Element?, parentSettings: CustomCodeStyleSettings) { super.writeExternal(parentElement, parentSettings) writeMain(parentElement) writeExtra(parentElement) } private fun writeMain(parentElement: Element?) { var extra = parentElement!!.getChild(tagName) if (extra == null) { extra = Element(tagName) parentElement.addContent(extra) } val option = Element("option") option.setAttribute("name", "MAIN") option.setAttribute("value", "3") extra.addContent(option) } private fun writeExtra(parentElement: Element?) { val extra = Element("NewComponent-extra") val option = Element("option") option.setAttribute("name", "EXTRA") option.setAttribute("value", "3") extra.addContent(option) parentElement!!.addContent(extra) } } } } ExtensionTestUtil.maskExtensions(CodeStyleSettingsProvider.EXTENSION_POINT_NAME, listOf(newProvider), disposableRule.disposable) val settings = CodeStyle.createTestSettings() fun text(param: String): String { return """ <code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}"> <NewComponent> <option name="MAIN" value="${param}" /> </NewComponent> <NewComponent-extra> <option name="EXTRA" value="${param}" /> </NewComponent-extra> <codeStyleSettings language="CoffeeScript"> <option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" /> </codeStyleSettings> <codeStyleSettings language="DB2"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="Derby"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="Gherkin"> <indentOptions> <option name="USE_TAB_CHARACTER" value="true" /> </indentOptions> </codeStyleSettings> <codeStyleSettings language="H2"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="HSQLDB"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="MySQL"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="Oracle"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="PostgreSQL"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="SQL"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="SQLite"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="Sybase"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> <codeStyleSettings language="TSQL"> <option name="KEEP_LINE_BREAKS" value="false" /> </codeStyleSettings> </code_scheme>""".trimIndent() } settings.readExternal(JDOMUtil.load(text("2"))) val serialized = Element("code_scheme").setAttribute("name", "testSchemeName") settings.writeExternal(serialized) assertThat(serialized).isEqualTo(text("3")) } @Test fun `reset deprecations`() { val settings = CodeStyle.createTestSettings() val initial = """ <code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}"> <option name="RIGHT_MARGIN" value="64" /> <option name="USE_FQ_CLASS_NAMES_IN_JAVADOC" value="false" /> </code_scheme>""".trimIndent() val expected = """ <code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}"> <option name="RIGHT_MARGIN" value="64" /> </code_scheme>""".trimIndent() settings.readExternal(JDOMUtil.load(initial)) settings.resetDeprecatedFields() val serialized = Element("code_scheme").setAttribute("name", "testSchemeName") settings.writeExternal(serialized) assertThat(serialized).isEqualTo(expected) } }
platform/configuration-store-impl/testSrc/CodeStyleTest.kt
2384842640
package com.intellij.xdebugger.impl.ui.attach.dialog.items.tree import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.UserDataHolder import com.intellij.ui.ColoredTreeCellRenderer import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.render.RenderingUtil import com.intellij.util.ui.JBUI import com.intellij.xdebugger.XDebuggerBundle import com.intellij.xdebugger.impl.ui.attach.dialog.AttachDialogProcessItem import com.intellij.xdebugger.impl.ui.attach.dialog.AttachDialogState import com.intellij.xdebugger.impl.ui.attach.dialog.items.AttachSelectionIgnoredNode import com.intellij.xdebugger.impl.ui.attach.dialog.items.AttachToProcessElement import com.intellij.xdebugger.impl.ui.attach.dialog.items.AttachToProcessElementsFilters import com.intellij.xdebugger.impl.ui.attach.dialog.items.separators.AttachTreeGroupColumnRenderer import com.intellij.xdebugger.impl.ui.attach.dialog.items.separators.AttachTreeGroupFirstColumnRenderer import com.intellij.xdebugger.impl.ui.attach.dialog.items.separators.AttachTreeGroupLastColumnRenderer import java.awt.Component import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JTree import javax.swing.table.TableCellRenderer internal abstract class AttachTreeNode(defaultIndentLevel: Int = 0): AttachToProcessElement { private val children = mutableListOf<AttachTreeNode>() private var parent: AttachTreeNode? = null private var myIndentLevel: Int = defaultIndentLevel private var myTree: AttachToProcessTree? = null fun addChild(child: AttachTreeNode) { children.add(child) child.parent = this child.updateIndentLevel(myIndentLevel + 1) } fun getChildNodes(): List<AttachTreeNode> = children fun getParent(): AttachTreeNode? = parent fun getIndentLevel(): Int = myIndentLevel var tree: AttachToProcessTree get() = myTree ?: throw IllegalStateException("Parent tree is not yet set") set(value) { myTree = value for (child in children) { child.tree = value } } abstract fun getValueAtColumn(column: Int): Any abstract fun getRenderer(column: Int): TableCellRenderer? private fun updateIndentLevel(newIndentLevel: Int) { myIndentLevel = newIndentLevel for (child in children) { child.updateIndentLevel(newIndentLevel + 1) } } abstract fun getTreeCellRendererComponent(tree: JTree?, value: AttachTreeNode, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): Component override fun getProcessItem(): AttachDialogProcessItem? = null } internal class AttachTreeRecentProcessNode(item: AttachDialogProcessItem, dialogState: AttachDialogState, dataHolder: UserDataHolder) : AttachTreeProcessNode(item, dialogState, dataHolder) { override fun isRecentItem(): Boolean = true } internal open class AttachTreeProcessNode(val item: AttachDialogProcessItem, val dialogState: AttachDialogState, val dataHolder: UserDataHolder) : AttachTreeNode() { companion object { private val logger = Logger.getInstance(AttachTreeProcessNode::class.java) } private val renderer = object : ColoredTreeCellRenderer() { override fun customizeCellRenderer(tree: JTree, value: Any?, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean) { val cell = ExecutableCell(this@AttachTreeProcessNode, dialogState) val (text, tooltip) = cell.getPresentation(this, (cell.node.getIndentLevel() + 1) * JBUI.scale(18)) this.append(text, modifyAttributes(cell.getTextAttributes(), [email protected], row)) this.toolTipText = tooltip } private fun modifyAttributes(attributes: SimpleTextAttributes, tree: AttachToProcessTree, row: Int): SimpleTextAttributes { //We should not trust the selected value as the TreeTableTree // is inserted into table and usually has wrong selection information val isTableRowSelected = tree.isRowSelected(row) return if (!isTableRowSelected) attributes else SimpleTextAttributes(attributes.style, RenderingUtil.getSelectionForeground(tree)) } } open fun isRecentItem(): Boolean = false override fun getValueAtColumn(column: Int): Any = when (column) { 0 -> this 1 -> PidCell(this, dialogState) 2 -> DebuggersCell(this, dialogState) 3 -> CommandLineCell(this, dialogState) else -> { logger.error("Unexpected column index: $column") Any() } } override fun getRenderer(column: Int): TableCellRenderer? = null override fun getTreeCellRendererComponent(tree: JTree?, value: AttachTreeNode, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): Component { return renderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus) } override fun visit(filters: AttachToProcessElementsFilters): Boolean { return filters.accept(item) } override fun getProcessItem(): AttachDialogProcessItem = item } internal class AttachTreeRecentNode(recentItemNodes: List<AttachTreeRecentProcessNode>) : AttachTreeNode(), AttachSelectionIgnoredNode { init { for (recentItemNode in recentItemNodes) { addChild(recentItemNode) } } override fun getValueAtColumn(column: Int): Any { return this } override fun getRenderer(column: Int): TableCellRenderer? = null override fun getTreeCellRendererComponent(tree: JTree?, value: AttachTreeNode, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): JComponent { return JLabel(XDebuggerBundle.message("xdebugger.attach.dialog.recently.attached.message")) } override fun visit(filters: AttachToProcessElementsFilters): Boolean { return getChildNodes().any { filters.matches(it) } } } internal class AttachTreeSeparatorNode(private val relatedNodes: List<AttachTreeRecentProcessNode>) : AttachTreeNode(), AttachSelectionIgnoredNode { companion object { private val logger = Logger.getInstance(AttachTreeSeparatorNode::class.java) private val leftColumnRenderer = AttachTreeGroupFirstColumnRenderer() private val middleColumnRenderer = AttachTreeGroupColumnRenderer() private val rightColumnRenderer = AttachTreeGroupLastColumnRenderer() } override fun getValueAtColumn(column: Int): Any { return this } override fun getRenderer(column: Int): TableCellRenderer? { return when (column) { 0 -> leftColumnRenderer 1 -> middleColumnRenderer 2 -> middleColumnRenderer 3 -> rightColumnRenderer else -> { logger.error("Unexpected column index: $column") null } } } override fun getTreeCellRendererComponent(tree: JTree?, value: AttachTreeNode, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): JComponent { return leftColumnRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus) } override fun visit(filters: AttachToProcessElementsFilters): Boolean { return relatedNodes.any { filters.matches(it) } } } internal class AttachTreeRootNode(items: List<AttachTreeNode>) : AttachTreeNode(-1), AttachSelectionIgnoredNode { init { for (item in items) { addChild(item) } } override fun getValueAtColumn(column: Int): Any { return this } override fun getRenderer(column: Int): TableCellRenderer? = null override fun getTreeCellRendererComponent(tree: JTree?, value: AttachTreeNode, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): JComponent { return JLabel() } override fun visit(filters: AttachToProcessElementsFilters): Boolean { return true } }
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/attach/dialog/items/tree/AttachTreeNodes.kt
4242271855
// "Change function signature to 'fun f(a: Int)'" "true" open class A { open fun f(a: Int) {} } class B : A(){ <caret>override fun f(a: String) {} }
plugins/kotlin/idea/tests/testData/quickfix/override/nothingToOverride/changeParameterType.kt
2939758587
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.roots.impl import com.intellij.ide.impl.runUnderModalProgressIfIsEdt import com.intellij.openapi.module.ModuleManager.Companion.getInstance import com.intellij.openapi.roots.DependencyScope import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.HeavyPlatformTestCase import com.intellij.testFramework.UsefulTestCase import java.io.IOException import java.util.* class DirectoryIndexForUnloadedModuleTest : DirectoryIndexTestCase() { @Throws(IOException::class) fun testUnloadedModule() { val unloadedModule = createModule("unloaded") val root = createTempDirectory() val contentRoot = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(root) ModuleRootModificationUtil.addContentRoot(unloadedModule, contentRoot!!.path) val file = HeavyPlatformTestCase.createChildData(contentRoot, "a.txt") assertInProject(file) runUnderModalProgressIfIsEdt { getInstance(myProject).setUnloadedModules(Arrays.asList("unloaded")) } assertFromUnloadedModule(file, "unloaded") assertFromUnloadedModule(contentRoot, "unloaded") } fun testDependentUnloadedModules() { val unloadedModule = createModule("unloaded") val main = createModule("main") val util = createModule("util") val common = createModule("common") ModuleRootModificationUtil.addDependency(unloadedModule, main) ModuleRootModificationUtil.addDependency(main, util) ModuleRootModificationUtil.addDependency(main, common, DependencyScope.COMPILE, true) runUnderModalProgressIfIsEdt { getInstance(myProject).setUnloadedModules(Arrays.asList("unloaded")) } UsefulTestCase.assertSameElements(myIndex.getDependentUnloadedModules(main), "unloaded") UsefulTestCase.assertEmpty(myIndex.getDependentUnloadedModules(util)) UsefulTestCase.assertSameElements(myIndex.getDependentUnloadedModules(common), "unloaded") } private fun assertFromUnloadedModule(file: VirtualFile?, moduleName: String) { val info = myIndex.getInfoForFile(file!!) assertTrue(info.toString(), info.isExcluded(file)) assertNull(info.module) assertEquals(moduleName, info.unloadedModuleName) } }
java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexForUnloadedModuleTest.kt
825007347
package org.bottiger.podcast.fragments.subscription import android.arch.lifecycle.ViewModel import android.app.Application import android.arch.lifecycle.ViewModelProvider import org.bottiger.podcast.model.Library /** * Created by aplb on 23-06-2017. */ class SubscriptionsViewModelFactory(application: Application, library: Library) : ViewModelProvider.NewInstanceFactory() { val application: Application val library: Library init { this.application = application this.library = library } override fun <T : ViewModel> create(modelClass: Class<T>): T { return SubscriptionsViewModel(application, library) as T } }
app/src/main/kotlin/org/bottiger/podcast/fragments/subscription/SubscriptionsViewModelFactory.kt
2851117287
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fastbootmobile import android.hardware.usb.UsbDevice import android.hardware.usb.UsbDeviceConnection import android.hardware.usb.UsbInterface import com.google.android.fastbootmobile.transport.UsbTransport import java.lang.ref.WeakReference typealias DeviceId = String object FastbootDeviceManager { private const val USB_CLASS = 0xff private const val USB_SUBCLASS = 0x42 private const val USB_PROTOCOL = 0x03 private val connectedDevices = HashMap<DeviceId, FastbootDeviceContext>() private val usbDeviceManager: UsbDeviceManager = UsbDeviceManager( WeakReference(FastbootMobile.getApplicationContext())) private val listeners = ArrayList<FastbootDeviceManagerListener>() private val usbDeviceManagerListener = object : UsbDeviceManagerListener { override fun filterDevice(device: UsbDevice): Boolean = [email protected](device) @Synchronized override fun onUsbDeviceAttached(device: UsbDevice) { listeners.forEach { it.onFastbootDeviceAttached(device.serialNumber) } } @Synchronized override fun onUsbDeviceDetached(device: UsbDevice) { if (connectedDevices.containsKey(device.serialNumber)) { connectedDevices[device.serialNumber]?.close() } connectedDevices.remove(device.serialNumber) listeners.forEach { it.onFastbootDeviceDetached(device.serialNumber) } } @Synchronized override fun onUsbDeviceConnected(device: UsbDevice, connection: UsbDeviceConnection) { val deviceContext = FastbootDeviceContext( UsbTransport(findFastbootInterface(device)!!, connection)) connectedDevices[device.serialNumber]?.close() connectedDevices[device.serialNumber] = deviceContext listeners.forEach { it.onFastbootDeviceConnected(device.serialNumber, deviceContext) } } } private fun filterDevice(device: UsbDevice): Boolean { if (device.deviceClass == USB_CLASS && device.deviceSubclass == USB_SUBCLASS && device.deviceProtocol == USB_PROTOCOL) { return true } return findFastbootInterface(device) != null } @Synchronized fun addFastbootDeviceManagerListener( listener: FastbootDeviceManagerListener) { listeners.add(listener) if (listeners.size == 1) usbDeviceManager.addUsbDeviceManagerListener( usbDeviceManagerListener) } @Synchronized fun removeFastbootDeviceManagerListener( listener: FastbootDeviceManagerListener) { listeners.remove(listener) if (listeners.size == 0) usbDeviceManager.removeUsbDeviceManagerListener( usbDeviceManagerListener) } @Synchronized fun connectToDevice(deviceId: DeviceId) { val device = usbDeviceManager.getDevices().values .filter(::filterDevice).firstOrNull { it.serialNumber == deviceId } if (device != null) usbDeviceManager.connectToDevice(device) } @Synchronized fun getAttachedDeviceIds(): List<DeviceId> { return usbDeviceManager.getDevices().values .filter(::filterDevice).map { it.serialNumber }.toList() } @Synchronized fun getConnectedDeviceIds(): List<DeviceId> { return connectedDevices.keys.toList() } @Synchronized fun getDeviceContext( deviceId: DeviceId): Pair<DeviceId, FastbootDeviceContext>? { return connectedDevices.entries.firstOrNull { it.key == deviceId }?.toPair() } private fun findFastbootInterface(device: UsbDevice): UsbInterface? { for (i: Int in 0 until device.interfaceCount) { val deviceInterface = device.getInterface(i) if (deviceInterface.interfaceClass == USB_CLASS && deviceInterface.interfaceSubclass == USB_SUBCLASS && deviceInterface.interfaceProtocol == USB_PROTOCOL) { return deviceInterface } } return null } }
lib/src/main/java/com/google/android/fastbootmobile/FastbootDeviceManager.kt
1862594493
package com.darrenatherton.droidcommunity.common.injection.module import android.support.v7.app.AppCompatActivity import com.darrenatherton.droidcommunity.common.injection.scope.PerScreen import com.darrenatherton.droidcommunity.features.main.MainViewPagerAdapter import dagger.Module import dagger.Provides @Module class MainViewModule(private val activity: AppCompatActivity) { @Provides @PerScreen internal fun provideMainViewPagerAdapter(): MainViewPagerAdapter { return MainViewPagerAdapter(activity.supportFragmentManager) } }
app/src/main/kotlin/com/darrenatherton/droidcommunity/common/injection/module/MainViewModule.kt
2759633828
package api.doc.swagger /** * Created by kk on 17/4/5. */ class ExternalDocumentation { // A short description of the target documentation. GFM syntax can be used for rich text representation. var description: String? = null // Required. The URL for the target documentation. Value MUST be in the format of a URL. var url: String = "" }
src/main/kotlin/api/doc/swagger/ExternalDocumentation.kt
2032133737
package lt.markmerkk.export.executor /** * Responsible for generating CLI arguments for execution */ interface JBundlerScriptProvider { /** * Prints out arguments used for bundling * For debugging purposes */ fun debugPrint() /** * Script as list of CLI arguments */ fun scriptCommand(): List<String> /** * Executes bundling script as external process */ fun bundle(): String }
buildSrc/src/main/java/lt/markmerkk/export/executor/JBundlerScriptProvider.kt
3540073741
/* * Copyright © 2016 dvbviewer-controller 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 org.dvbviewer.controller.ui.base import android.content.Context import android.os.Bundle import android.text.TextUtils import android.widget.Toast import androidx.appcompat.app.AppCompatDialogFragment import org.dvbviewer.controller.R import org.dvbviewer.controller.data.api.io.exception.AuthenticationException import org.dvbviewer.controller.data.api.io.exception.DefaultHttpException import org.xml.sax.SAXException /** * @author RayBa82 on 24.01.2016 * * Base class for Fragments */ open class BaseDialogFragment : AppCompatDialogFragment() { /** * Generic method to catch an Exception. * It shows a toast to inform the user. * This method is safe to be called from non UI threads. * * @param e the Excetpion to catch */ protected fun catchException(e: Exception) { if (e is AuthenticationException) { showToast(context, getStringSafely(R.string.error_invalid_credentials)) } else if (e is DefaultHttpException) { showToast(context, e.message) } else if (e is SAXException) { showToast(context, getStringSafely(R.string.error_parsing_xml)) } else { showToast(context, getStringSafely(R.string.error_common) + "\n\n" + if (e.message != null) e.message else e.javaClass.name) } } /** * Possibility to show a Toastmessage from non UI threads. * * @param context the context to show the toast * @param message the message to display */ /** * Possibility to show a Toastmessage from non UI threads. * * @param context the context to show the toast * @param message the message to display */ protected fun showToast(context: Context?, message: String?) { if (context != null && !isDetached) { val errorRunnable = Runnable { if (!TextUtils.isEmpty(message)) { Toast.makeText(context, message, Toast.LENGTH_LONG).show() } } activity!!.runOnUiThread(errorRunnable) } } /** * Possibility for sublasses to provide a LayouRessource * before constructor is called. * * @param resId the resource id * * @return the String for the resource id */ protected fun getStringSafely(resId: Int): String { var result = "" if (!isDetached && isVisible && isAdded) { try { result = getString(resId) } catch (e: Exception) { // Dirty Exception Handling, because this keeps and keeps crashing... e.printStackTrace() } } return result } fun logEvent(category: String, bundle: Bundle?){ val baseActivity = activity as BaseActivity? baseActivity?.mFirebaseAnalytics?.logEvent(category, bundle) } }
dvbViewerController/src/main/java/org/dvbviewer/controller/ui/base/BaseDialogFragment.kt
2930703337
/* * io_buffer_risc.kt * * Created on: 24.12.2020 * Author: Alexander Antonov <[email protected]> * License: See LICENSE file for details */ package reordex import hwast.* internal class io_buffer_risc(cyclix_gen : cyclix.Generic, ExUnit_name : String, ExUnit_num : Int, name_prefix : String, TRX_BUF_SIZE : Int, MultiExu_CFG : Reordex_CFG, exu_id_num: hw_imm, iq_exu: Boolean, CDB_index : Int, cdb_num : Int, busreq_mem_struct : hw_struct, commit_cdb : hw_var ) : io_buffer_coproc(cyclix_gen, ExUnit_name, ExUnit_num, name_prefix, TRX_BUF_SIZE, MultiExu_CFG, exu_id_num, iq_exu, CDB_index, cdb_num, busreq_mem_struct, commit_cdb) { var mem_req = AdduStageVar("mem_req", 0, 0, "0") var mem_we = AdduStageVar("mem_we", 0, 0, "0") var mem_addr = AdduStageVar("mem_addr", 31, 0, "0") var mem_wdata = AdduStageVar("mem_wdata", 31, 0, "0") var mem_be = AdduStageVar("mem_be", 3, 0, "0") var mem_load_signext = AdduStageVar("mem_load_signext", 0, 0, "0") var mem_ctrlflow_enb = AdduStageVar("mem_ctrlflow_enb", 0, 0, "0") var mem_addr_generated = AdduStageVar("mem_addr_generated", 0, 0, "0") var mem_addr_generate = cyclix_gen.ulocal("mem_addr_generate", 0, 0, "0") var mem_addr_generate_trx = cyclix_gen.ulocal("mem_addr_generate_trx", GetWidthToContain(TRX_BUF_SIZE) -1, 0, "0") val data_name_prefix = "genmcopipe_data_mem_" var rd_struct = hw_struct("genpmodule_" + cyclix_gen.name + "_" + data_name_prefix + "genstruct_fifo_wdata") var data_req_fifo = cyclix_gen.fifo_out((data_name_prefix + "req"), rd_struct) var data_resp_fifo = cyclix_gen.ufifo_in((data_name_prefix + "resp"), 31, 0) var mem_data_wdata = cyclix_gen.local("mem_data_wdata", data_req_fifo.vartype, "0") var mem_data_rdata = cyclix_gen.local("mem_data_rdata", data_resp_fifo.vartype, "0") var lsu_iq_done = cyclix_gen.ulocal("lsu_iq_done", 0, 0, "0") var lsu_iq_num = cyclix_gen.ulocal("lsu_iq_num", GetWidthToContain(TRX_BUF.GetWidth()) -1, 0, "0") var io_iq_cmd = TRX_BUF.GetFracRef(lsu_iq_num) var exu_cdb_inst_enb = commit_cdb.GetFracRef("enb") var exu_cdb_inst_data = commit_cdb.GetFracRef("data") var exu_cdb_inst_trx_id = exu_cdb_inst_data.GetFracRef("trx_id") var exu_cdb_inst_req = exu_cdb_inst_data.GetFracRef("rd0_req") // TODO: fix var exu_cdb_inst_tag = exu_cdb_inst_data.GetFracRef("rd0_tag") // TODO: fix var exu_cdb_inst_wdata = exu_cdb_inst_data.GetFracRef("rd0_wdata") // TODO: fix var resp_buf = io_buffer_resp_risc(cyclix_gen, "LSU_resp", 4, MultiExu_CFG, data_resp_fifo.vartype.dimensions) var search_active = cyclix_gen.ulocal("search_active", 0, 0, "1") init { rd_struct.addu("we", 0, 0, "0") rd_struct.add("wdata", hw_type(busreq_mem_struct), "0") } override fun ProcessIO(io_cdb_buf : hw_var, io_cdb_rs1_wdata_buf : hw_var, rob_buf : rob) { cyclix_gen.MSG_COMMENT("I/O IQ processing...") preinit_ctrls() init_locals() resp_buf.preinit_ctrls() var io_cdb_enb = io_cdb_buf.GetFracRef("enb") var io_cdb_data = io_cdb_buf.GetFracRef("data") var io_cdb_trx_id = io_cdb_data.GetFracRef("trx_id") var io_cdb_req = io_cdb_data.GetFracRef("rd0_req") var io_cdb_tag = io_cdb_data.GetFracRef("rd0_tag") var io_cdb_wdata = io_cdb_data.GetFracRef("rd0_wdata") cyclix_gen.assign(io_cdb_enb, 0) cyclix_gen.assign(io_cdb_data, 0) cyclix_gen.assign(mem_addr, src_rsrv[0].src_data) cyclix_gen.assign(mem_wdata, src_rsrv[1].src_data) cyclix_gen.MSG_COMMENT("Returning I/O to CDB...") var resp_buf_head = resp_buf.TRX_BUF.GetFracRef(0) var resp_buf_head_rdy = resp_buf_head.GetFracRef("rdy") var resp_buf_head_trx_id = resp_buf_head.GetFracRef("trx_id") var resp_buf_head_rd0_req = resp_buf_head.GetFracRef("rd0_req") var resp_buf_head_rd0_tag = resp_buf_head.GetFracRef("rd0_tag") var resp_buf_head_mem_be = resp_buf_head.GetFracRef("mem_be") var resp_buf_head_mem_load_signext = resp_buf_head.GetFracRef("mem_load_signext") var resp_buf_head_mem_data_rdata = resp_buf_head.GetFracRef("mem_data_rdata") cyclix_gen.begif(resp_buf.TRX_BUF_COUNTER_NEMPTY) run { cyclix_gen.begif(resp_buf_head_rdy) run { cyclix_gen.assign(exu_cdb_inst_enb, 1) cyclix_gen.assign(exu_cdb_inst_trx_id, resp_buf_head_trx_id) cyclix_gen.assign(exu_cdb_inst_req, resp_buf_head_rd0_req) cyclix_gen.assign(exu_cdb_inst_tag, resp_buf_head_rd0_tag) cyclix_gen.assign(exu_cdb_inst_wdata, resp_buf_head_mem_data_rdata) resp_buf.pop_trx() }; cyclix_gen.endif() }; cyclix_gen.endif() cyclix_gen.MSG_COMMENT("Returning I/O to CDB: done") cyclix_gen.MSG_COMMENT("Fetching I/O response...") cyclix_gen.begif(cyclix_gen.fifo_rd_unblk(data_resp_fifo, mem_data_rdata)) run { cyclix_gen.begif(cyclix_gen.eq2(resp_buf_head_mem_be, 0x1)) run { cyclix_gen.begif(resp_buf_head_mem_load_signext) run { mem_data_rdata.assign(cyclix_gen.signext(mem_data_rdata[7, 0], 32)) }; cyclix_gen.endif() cyclix_gen.begelse() run { mem_data_rdata.assign(cyclix_gen.zeroext(mem_data_rdata[7, 0], 32)) }; cyclix_gen.endif() }; cyclix_gen.endif() cyclix_gen.begif(cyclix_gen.eq2(resp_buf_head_mem_be, 0x3)) run { cyclix_gen.begif(resp_buf_head_mem_load_signext) run { mem_data_rdata.assign(cyclix_gen.signext(mem_data_rdata[15, 0], 32)) }; cyclix_gen.endif() cyclix_gen.begelse() run { mem_data_rdata.assign(cyclix_gen.zeroext(mem_data_rdata[15, 0], 32)) }; cyclix_gen.endif() }; cyclix_gen.endif() cyclix_gen.assign(resp_buf_head_mem_data_rdata, mem_data_rdata) cyclix_gen.assign(resp_buf_head_rdy, 1) }; cyclix_gen.endif() cyclix_gen.MSG_COMMENT("Fetching I/O response: done") cyclix_gen.MSG_COMMENT("Initiating I/O request...") cyclix_gen.begif(cyclix_gen.band(ctrl_active, resp_buf.ctrl_rdy)) run { cyclix_gen.begif(mem_addr_generated) run { cyclix_gen.begif(mem_ctrlflow_enb) run { // data is ready identification cyclix_gen.assign(rdy, src_rsrv[0].src_rdy) cyclix_gen.begif(mem_we) run { cyclix_gen.band_gen(rdy, rdy, src_rsrv[1].src_rdy) }; cyclix_gen.endif() cyclix_gen.begif(rdy) run { cyclix_gen.assign(mem_data_wdata.GetFracRef("we"), mem_we) cyclix_gen.assign(mem_data_wdata.GetFracRef("wdata").GetFracRef("addr"), mem_addr) cyclix_gen.assign(mem_data_wdata.GetFracRef("wdata").GetFracRef("be"), mem_be) cyclix_gen.assign(mem_data_wdata.GetFracRef("wdata").GetFracRef("wdata"), mem_wdata) cyclix_gen.begif(cyclix_gen.fifo_wr_unblk(data_req_fifo, mem_data_wdata)) run { var resp_trx = resp_buf.GetPushTrx() var resp_trx_rdy = resp_trx.GetFracRef("rdy") var resp_trx_trx_id = resp_trx.GetFracRef("trx_id") var resp_trx_rd0_req = resp_trx.GetFracRef("rd0_req") var resp_trx_rd0_tag = resp_trx.GetFracRef("rd0_tag") var resp_trx_mem_be = resp_trx.GetFracRef("mem_be") var resp_trx_mem_load_signext = resp_trx.GetFracRef("mem_load_signext") var resp_trx_mem_data_rdata = resp_trx.GetFracRef("mem_data_rdata") cyclix_gen.assign(resp_trx_rdy, mem_we) cyclix_gen.assign(resp_trx_trx_id, trx_id) cyclix_gen.assign(resp_trx_rd0_req, !mem_we) cyclix_gen.assign(resp_trx_rd0_tag, rd_ctrls[0].tag) cyclix_gen.assign(resp_trx_mem_be, mem_be) cyclix_gen.assign(resp_trx_mem_load_signext, mem_load_signext) cyclix_gen.assign(resp_trx_mem_data_rdata, 0) resp_buf.push_trx(resp_trx) cyclix_gen.assign(pop, 1) pop_trx() }; cyclix_gen.endif() }; cyclix_gen.endif() }; cyclix_gen.endif() }; cyclix_gen.endif() }; cyclix_gen.endif() cyclix_gen.MSG_COMMENT("Initiating I/O request: done") cyclix_gen.MSG_COMMENT("Mem addr generating...") for (trx_idx in TRX_BUF.vartype.dimensions.last().msb downTo 0) { var entry_ptr = TRX_BUF.GetFracRef(trx_idx) cyclix_gen.begif(cyclix_gen.band(entry_ptr.GetFracRef("enb"), entry_ptr.GetFracRef("src0_rdy"), !entry_ptr.GetFracRef("mem_addr_generated"))) run { cyclix_gen.assign(mem_addr_generate, 1) cyclix_gen.assign(mem_addr_generate_trx, trx_idx) }; cyclix_gen.endif() } cyclix_gen.begif(mem_addr_generate) run { var entry_ptr = TRX_BUF.GetFracRef(mem_addr_generate_trx) cyclix_gen.add_gen(entry_ptr.GetFracRef("src0_data"), entry_ptr.GetFracRef("src0_data"), entry_ptr.GetFracRef("immediate")) cyclix_gen.assign(entry_ptr.GetFracRef("mem_addr_generated"), 1) }; cyclix_gen.endif() cyclix_gen.MSG_COMMENT("Mem addr generating: done") cyclix_gen.COMMENT("Memory flow control consistency identification...") var ROB_SEARCH_DEPTH = 4 for (rob_trx_idx in 0 until ROB_SEARCH_DEPTH) { for (rob_trx_entry_idx in 0 until rob_buf.TRX_BUF_MULTIDIM) { cyclix_gen.begif(search_active) run { var lsu_entry = TRX_BUF.GetFracRef(0) var rob_entry = rob_buf.TRX_BUF.GetFracRef(rob_trx_idx).GetFracRef(rob_trx_entry_idx) var break_val = (rob_entry.GetFracRef("cf_can_alter") as hw_param) if (rob_trx_idx == 0) { break_val = cyclix_gen.band(break_val, (rob_buf as rob_risc).entry_mask.GetFracRef(rob_trx_entry_idx)) } cyclix_gen.begif(break_val) run { search_active.assign(0) }; cyclix_gen.endif() cyclix_gen.begelse() run { var active_trx_id = rob_entry.GetFracRef("trx_id") cyclix_gen.begif(cyclix_gen.eq2(lsu_entry.GetFracRef("trx_id"), active_trx_id)) run { cyclix_gen.assign(lsu_entry.GetFracRef("mem_ctrlflow_enb"), 1) }; cyclix_gen.endif() }; cyclix_gen.endif() }; cyclix_gen.endif() } } cyclix_gen.COMMENT("Memory flow control consistency identification: done") cyclix_gen.MSG_COMMENT("I/O IQ processing: done") } } internal class io_buffer_resp_risc (cyclix_gen : cyclix.Generic, name_prefix : String, TRX_BUF_SIZE : Int, MultiExu_CFG : Reordex_CFG, data_dim : hw_dim_static ): trx_buffer(cyclix_gen, name_prefix, TRX_BUF_SIZE, 0, MultiExu_CFG) { var rdy = AdduStageVar("rdy", 0, 0, "0") var trx_id = AddStageVar(hw_structvar("trx_id", DATA_TYPE.BV_UNSIGNED, GetWidthToContain(MultiExu_CFG.trx_inflight_num)-1, 0, "0")) var rd0_req = AdduStageVar("rd0_req", 0, 0, "0") var rd0_tag = AdduStageVar("rd0_tag", 31, 0, "0") // TODO: fix dims var mem_be = AdduStageVar("mem_be", 3, 0, "0") var mem_load_signext = AdduStageVar("mem_load_signext", 0, 0, "0") var mem_data_rdata = AdduStageVar("mem_data_rdata", data_dim, "0") }
kernelip/reordex/src/io_buffer_risc.kt
3288551320
package io.casey.musikcube.remote.ui.category.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import io.casey.musikcube.remote.R import io.casey.musikcube.remote.ui.category.constant.Category.toDisplayString class AllCategoriesAdapter(private val listener: EventListener) : RecyclerView.Adapter<AllCategoriesAdapter.Holder>() { private var categories: List<String> = listOf() interface EventListener { fun onItemClicked(category: String) } class Holder(itemView: View): RecyclerView.ViewHolder(itemView) { private val title: TextView = itemView.findViewById(R.id.title) init { itemView.findViewById<View>(R.id.action).visibility = View.GONE itemView.findViewById<View>(R.id.subtitle).visibility = View.GONE } internal fun bindView(category: String) { title.text = toDisplayString(itemView.context, category) itemView.tag = category } } override fun onBindViewHolder(holder: Holder, position: Int) { holder.bindView(categories[position]) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { val inflater = LayoutInflater.from(parent.context) val view = inflater.inflate(R.layout.simple_list_item, parent, false) view.setOnClickListener { v -> listener.onItemClicked(v.tag as String) } return Holder(view) } override fun getItemCount(): Int { return categories.size } fun setModel(model: List<String>) { this.categories = model.filter { !BLACKLIST.contains(it) } this.notifyDataSetChanged() } companion object { val BLACKLIST = setOf("channels", "encoder", "path_id", "totaltracks") } }
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/category/adapter/AllCategoriesAdapter.kt
1528807443
/* * Copyright (C) 2017 Wiktor Nizio * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp */ package pl.org.seva.texter.settings import android.Manifest import android.annotation.SuppressLint import android.app.Dialog import android.content.DialogInterface import android.content.pm.PackageManager import android.database.Cursor import android.os.Bundle import android.preference.PreferenceManager import android.provider.ContactsContract import androidx.fragment.app.DialogFragment import androidx.loader.app.LoaderManager import androidx.core.content.ContextCompat import androidx.loader.content.CursorLoader import androidx.loader.content.Loader import androidx.cursoradapter.widget.SimpleCursorAdapter import androidx.appcompat.app.AlertDialog import android.view.LayoutInflater import android.view.View import android.widget.AdapterView import android.widget.EditText import android.widget.ListView import android.widget.Toast import java.util.ArrayList import pl.org.seva.texter.R import pl.org.seva.texter.main.Constants class PhoneNumberFragment : DialogFragment(), LoaderManager.LoaderCallbacks<Cursor> { private var toast: Toast? = null private var contactsEnabled: Boolean = false private lateinit var contactKey: String private var contactName: String? = null lateinit var adapter: SimpleCursorAdapter private lateinit var number: EditText @SuppressLint("InflateParams") private fun phoneNumberDialogView(inflater: LayoutInflater) : View { val v = inflater.inflate(R.layout.fragment_number, null) number = v.findViewById(R.id.number) val contacts: ListView = v.findViewById(R.id.contacts) contactsEnabled = ContextCompat.checkSelfPermission( requireActivity(), Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED if (!contactsEnabled) { contacts.visibility = View.GONE } else { contacts.onItemClickListener = AdapterView.OnItemClickListener { parent, _, position, _ -> this.onItemClick(parent, position) } adapter = SimpleCursorAdapter( activity, R.layout.item_contact, null, FROM_COLUMNS, TO_IDS, 0) contacts.adapter = adapter } return v } private val persistedString: String get() = checkNotNull(PreferenceManager.getDefaultSharedPreferences(activity) .getString(SettingsActivity.PHONE_NUMBER, Constants.DEFAULT_PHONE_NUMBER)) @SuppressLint("InflateParams") override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = AlertDialog.Builder(requireActivity()) // Get the layout inflater val inflater = requireActivity().layoutInflater // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout builder.setView(phoneNumberDialogView(inflater)) // Add action buttons .setPositiveButton(android.R.string.ok) { dialog, _ -> onOkPressedInDialog(dialog) } .setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() } setNumber(persistedString) return builder.create() } private fun onOkPressedInDialog(d: DialogInterface) { persistString(number.text.toString()) d.dismiss() } private fun persistString(`val`: String) = PreferenceManager.getDefaultSharedPreferences(activity).edit() .putString(SettingsActivity.PHONE_NUMBER, `val`).apply() override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) if (contactsEnabled) { loaderManager.initLoader(CONTACTS_QUERY_ID, null, this) } } override fun toString() = number.text.toString() override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> { when (id) { CONTACTS_QUERY_ID -> { val contactsSelectionArgs = arrayOf("1") return CursorLoader( requireActivity(), ContactsContract.Contacts.CONTENT_URI, CONTACTS_PROJECTION, CONTACTS_SELECTION, contactsSelectionArgs, CONTACTS_SORT) } DETAILS_QUERY_ID -> { val detailsSelectionArgs = arrayOf(contactKey) return CursorLoader( requireActivity(), ContactsContract.CommonDataKinds.Phone.CONTENT_URI, DETAILS_PROJECTION, DETAILS_SELECTION, detailsSelectionArgs, DETAILS_SORT) } else -> throw IllegalArgumentException() } } override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor) { when (loader.id) { CONTACTS_QUERY_ID -> adapter.swapCursor(data) DETAILS_QUERY_ID -> { val numbers = ArrayList<String>() while (data.moveToNext()) { val n = data.getString(DETAILS_NUMBER_INDEX) if (!numbers.contains(n)) { numbers.add(n) } } data.close() when { numbers.size == 1 -> this.number.setText(numbers[0]) numbers.isEmpty() -> { toast = Toast.makeText( context, R.string.no_number, Toast.LENGTH_SHORT) checkNotNull(toast).show() } else -> { val items = numbers.toTypedArray() AlertDialog.Builder(requireActivity()).setItems(items) { dialog, which -> dialog.dismiss() number.setText(numbers[which]) }.setTitle(contactName).setCancelable(true).setNegativeButton( android.R.string.cancel) { dialog, _ -> dialog.dismiss() }.show() } } } } } override fun onLoaderReset(loader: Loader<Cursor>) { when (loader.id) { CONTACTS_QUERY_ID -> adapter.swapCursor(null) DETAILS_QUERY_ID -> { } } } private fun onItemClick(parent: AdapterView<*>, position: Int) { toast?.cancel() val cursor = (parent.adapter as SimpleCursorAdapter).cursor cursor.moveToPosition(position) contactKey = cursor.getString(CONTACT_KEY_INDEX) contactName = cursor.getString(CONTACT_NAME_INDEX) loaderManager.restartLoader(DETAILS_QUERY_ID, null, this) } private fun setNumber(number: String?) = this.number.setText(number) companion object { private const val CONTACTS_QUERY_ID = 0 private const val DETAILS_QUERY_ID = 1 private val FROM_COLUMNS = arrayOf(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY) private val CONTACTS_PROJECTION = arrayOf( // SELECT ContactsContract.Contacts._ID, ContactsContract.Contacts.LOOKUP_KEY, ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, ContactsContract.Contacts.HAS_PHONE_NUMBER) private const val CONTACTS_SELECTION = // FROM ContactsContract.Contacts.HAS_PHONE_NUMBER + " = ?" private const val CONTACTS_SORT = // ORDER_BY ContactsContract.Contacts.DISPLAY_NAME_PRIMARY private val DETAILS_PROJECTION = arrayOf( // SELECT ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.LABEL) private const val DETAILS_SORT = // ORDER_BY ContactsContract.CommonDataKinds.Phone._ID private const val DETAILS_SELECTION = // WHERE ContactsContract.Data.LOOKUP_KEY + " = ?" // The column index for the LOOKUP_KEY column private const val CONTACT_KEY_INDEX = 1 private const val CONTACT_NAME_INDEX = 2 private const val DETAILS_NUMBER_INDEX = 1 private val TO_IDS = intArrayOf(android.R.id.text1) } }
texter/src/main/kotlin/pl/org/seva/texter/settings/PhoneNumberFragment.kt
203349038
package com.ridi.books.helper.text /** * Normalize the string to MAJOR.MINOR.PATCH format of SemVer. * 8 -> 8.0.0 * 8.4 -> 8.4.0 * 8.4.2_rc1 -> 8.4.2 * a.b.c (invalid) -> * */ fun String.normalizeAsSemVer(): String { val versionIntegers = Regex("^([0-9]+)(?:\\.([0-9]+)(?:\\.([0-9]+))?)?").find(this)?.groupValues ?: return "*" fun String.orZeroIfEmpty() = if (isEmpty()) "0" else this return versionIntegers.run { "${get(1).orZeroIfEmpty()}.${get(2).orZeroIfEmpty()}.${get(3).orZeroIfEmpty()}" } }
src/main/kotlin/com/ridi/books/helper/text/VersionHelper.kt
3260832479
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions import com.intellij.psi.PsiElement import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrSuperReferenceResolver.resolveSuperExpression import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrThisReferenceResolver.resolveThisExpression import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil import org.jetbrains.plugins.groovy.lang.resolve.GrReferenceResolveRunner import org.jetbrains.plugins.groovy.lang.resolve.GrResolverProcessor import org.jetbrains.plugins.groovy.lang.resolve.api.Argument import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyCachingReference import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyLValueProcessor import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyRValueProcessor import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolveKind import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolveKind.* import java.util.* abstract class GrReferenceExpressionReference(ref: GrReferenceExpressionImpl) : GroovyCachingReference<GrReferenceExpressionImpl>(ref) { override fun doResolve(incomplete: Boolean): Collection<GroovyResolveResult> { val staticResults = element.staticReference.resolve(incomplete) if (staticResults.isNotEmpty()) { return staticResults } return doResolveNonStatic() } protected open fun doResolveNonStatic(): Collection<GroovyResolveResult> { val expression = element val name = expression.referenceName ?: return emptyList() val kinds = expression.resolveKinds() val processor = buildProcessor(name, expression, kinds) GrReferenceResolveRunner(expression, processor).resolveReferenceExpression() return processor.results } protected abstract fun buildProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>): GrResolverProcessor<*> } class GrRValueExpressionReference(ref: GrReferenceExpressionImpl) : GrReferenceExpressionReference(ref) { override fun doResolveNonStatic(): Collection<GroovyResolveResult> { return element.handleSpecialCases() ?: super.doResolveNonStatic() } override fun buildProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>): GrResolverProcessor<*> { return GroovyRValueProcessor(name, place, kinds) } } class GrLValueExpressionReference(ref: GrReferenceExpressionImpl, private val argument: Argument) : GrReferenceExpressionReference(ref) { override fun buildProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>): GrResolverProcessor<*> { return GroovyLValueProcessor(name, place, kinds, listOf(argument)) } } private fun GrReferenceExpression.handleSpecialCases(): Collection<GroovyResolveResult>? { when (referenceNameElement?.node?.elementType) { GroovyElementTypes.KW_THIS -> return resolveThisExpression(this) GroovyElementTypes.KW_SUPER -> return resolveSuperExpression(this) GroovyElementTypes.KW_CLASS -> { if (!PsiUtil.isCompileStatic(this) && qualifier?.type == null) { return emptyList() } } } return null } private fun GrReferenceExpressionImpl.resolveKinds(): Set<GroovyResolveKind> { return if (isQualified) { EnumSet.of(FIELD, PROPERTY, VARIABLE) } else { EnumSet.of(FIELD, PROPERTY, VARIABLE, BINDING) } }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionReference.kt
3140083861
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto import com.intellij.debugger.PositionManager import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.NamedMethodFilter import com.intellij.openapi.application.ReadAction import com.intellij.util.Range import com.sun.jdi.LocalVariable import com.sun.jdi.Location import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.debugger.DebuggerUtils.trimIfMangledInBytecode import org.jetbrains.kotlin.idea.debugger.getInlineFunctionAndArgumentVariablesToBordersMap import org.jetbrains.kotlin.idea.debugger.safeMethod import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypesAndPredicate import org.jetbrains.kotlin.resolve.DescriptorUtils open class KotlinMethodFilter( declaration: KtDeclaration?, private val lines: Range<Int>?, private val methodInfo: CallableMemberInfo ) : NamedMethodFilter { private val declarationPtr = declaration?.createSmartPointer() override fun locationMatches(process: DebugProcessImpl, location: Location): Boolean { if (!nameMatches(location)) { return false } return ReadAction.nonBlocking<Boolean> { declarationMatches(process, location) }.executeSynchronously() } private fun declarationMatches(process: DebugProcessImpl, location: Location): Boolean { val (currentDescriptor, currentDeclaration) = getMethodDescriptorAndDeclaration(process.positionManager, location) if (currentDescriptor == null || currentDeclaration == null) { return false } if (currentDescriptor !is CallableMemberDescriptor) return false if (currentDescriptor.kind != CallableMemberDescriptor.Kind.DECLARATION) return false if (methodInfo.isInvoke) { // There can be only one 'invoke' target at the moment so consider position as expected. // Descriptors can be not-equal, say when parameter has type `(T) -> T` and lambda is `Int.() -> Int`. return true } // Element is lost. But we know that name matches, so stop. val declaration = declarationPtr?.element ?: return true val psiManager = currentDeclaration.manager if (psiManager.areElementsEquivalent(currentDeclaration, declaration)) { return true } return DescriptorUtils.getAllOverriddenDescriptors(currentDescriptor).any { baseOfCurrent -> val currentBaseDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(currentDeclaration.project, baseOfCurrent) psiManager.areElementsEquivalent(declaration, currentBaseDeclaration) } } override fun getCallingExpressionLines(): Range<Int>? = lines override fun getMethodName(): String = methodInfo.name private fun nameMatches(location: Location): Boolean { val method = location.safeMethod() ?: return false val targetMethodName = methodName val isNameMangledInBytecode = methodInfo.isNameMangledInBytecode val actualMethodName = method.name().trimIfMangledInBytecode(isNameMangledInBytecode) return actualMethodName == targetMethodName || actualMethodName == "$targetMethodName${JvmAbi.DEFAULT_PARAMS_IMPL_SUFFIX}" || // A correct way here is to memorize the original location (where smart step into was started) // and filter out ranges that contain that original location. // Otherwise, nested inline with the same method name will not work correctly. method.getInlineFunctionAndArgumentVariablesToBordersMap() .filter { location in it.value } .any { it.key.isInlinedFromFunction(targetMethodName, isNameMangledInBytecode) } } } private fun getMethodDescriptorAndDeclaration( positionManager: PositionManager, location: Location ): Pair<DeclarationDescriptor?, KtDeclaration?> { val actualMethodName = location.safeMethod()?.name() ?: return null to null val elementAt = positionManager.getSourcePosition(location)?.elementAt val declaration = elementAt?.getParentOfTypesAndPredicate(false, KtDeclaration::class.java) { it !is KtProperty || !it.isLocal } return if (declaration is KtClass && actualMethodName == "<init>") { declaration.resolveToDescriptorIfAny()?.unsubstitutedPrimaryConstructor to declaration } else { declaration?.resolveToDescriptorIfAny() to declaration } } private fun LocalVariable.isInlinedFromFunction(methodName: String, isNameMangledInBytecode: Boolean): Boolean { val variableName = name().trimIfMangledInBytecode(isNameMangledInBytecode) return variableName.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION) && variableName.substringAfter(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION) == methodName }
plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinMethodFilter.kt
1973473633
package katas.kotlin.shuntingYard import datsok.shouldEqual import org.junit.Test import java.util.LinkedList class ShuntingYard2 { @Test fun `convert infix expression into RPN`() { listOf("1", "+", "2").toRPN() shouldEqual listOf("1", "2", "+") listOf("1", "+", "2", "+", "3").toRPN() shouldEqual listOf("1", "2", "+", "3", "+") listOf("1", "*", "2", "+", "3").toRPN() shouldEqual listOf("1", "2", "*", "3", "+") listOf("1", "+", "2", "*", "3").toRPN() shouldEqual listOf("1", "2", "3", "*", "+") } private fun List<String>.toRPN(): List<String> { val result = ArrayList<String>(size) val stack = LinkedList<String>() forEach { token -> if (token.isOperator()) { if (stack.isNotEmpty() && token.precedence() <= stack.first().precedence()) { result.consume(stack) } stack.add(0, token) } else { result.add(token) } } result.consume(stack) return result } private val operators = mapOf( "*" to 20, "+" to 10 ) private fun String.isOperator() = operators.contains(this) private fun String.precedence() = operators[this]!! private fun <E> MutableList<E>.consume(list: MutableList<E>) = apply { addAll(list) list.clear() } }
kotlin/src/katas/kotlin/shuntingYard/ShuntingYard2.kt
3792766244
/* * wac-core * Copyright (C) 2016 Martijn Heil * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package tk.martijn_heil.wac_core.classes enum class PlayerClass { RECON, INFANTRY, TANKER, PILOT, ENGINEER, CIVILIAN, PARATROOPER, }
src/main/kotlin/tk/martijn_heil/wac_core/classes/PlayerClass.kt
3881209171
package me.serce.solidity.ide.run.ui import com.intellij.application.options.ModulesComboBox import com.intellij.execution.configuration.BrowseModuleValueActionListener import com.intellij.execution.testframework.SourceScope import com.intellij.execution.ui.CommonJavaParametersPanel import com.intellij.execution.ui.ConfigurationModuleSelector import com.intellij.execution.ui.DefaultJreSelector import com.intellij.execution.ui.JrePathEditor import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComponentWithBrowseButton import com.intellij.openapi.ui.LabeledComponent import com.intellij.openapi.ui.ex.MessagesEx import com.intellij.openapi.util.Condition import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.ui.EditorTextField import com.intellij.ui.PanelWithAnchor import com.intellij.util.ui.UIUtil import me.serce.solidity.ide.run.* import me.serce.solidity.lang.psi.SolContractDefinition import me.serce.solidity.lang.psi.SolFunctionDefinition import javax.swing.DefaultComboBoxModel import javax.swing.JComponent import javax.swing.JPanel class SolidityConfigurableEditorPanel(private val myProject: Project) : SettingsEditor<SolidityRunConfig>(), PanelWithAnchor { val moduleSelector: ConfigurationModuleSelector private val myContractLocations: Array<LabeledComponent<EditorTextFieldWithBrowseButton>> private val myModel: SolidityConfigurationModel private val myBrowsers: Array<BrowseModuleValueActionListener<JComponent>> private lateinit var myContract: LabeledComponent<EditorTextFieldWithBrowseButton> private lateinit var myFunction: LabeledComponent<EditorTextFieldWithBrowseButton> private lateinit var myWholePanel: JPanel private lateinit var myModule: LabeledComponent<ModulesComboBox> private lateinit var myCommonJavaParameters: CommonJavaParametersPanel private lateinit var myJrePathEditor: JrePathEditor private lateinit var anchor: JComponent private val modulesComponent: ModulesComboBox get() = myModule.component private val contractName: String get() = getContractLocation(SolidityConfigurationModel.CONTRACT).component.text init { myModel = SolidityConfigurationModel(myProject) moduleSelector = ConfigurationModuleSelector(myProject, modulesComponent) myJrePathEditor.setDefaultJreSelector(DefaultJreSelector.fromModuleDependencies(modulesComponent, false)) myCommonJavaParameters.setModuleContext(moduleSelector.module) myCommonJavaParameters.setHasModuleMacro() myModule.component.addActionListener { _ -> myCommonJavaParameters.setModuleContext(moduleSelector.module) } myBrowsers = arrayOf(ContractChooserActionListener(myProject), object : FunctionBrowser(myProject) { override val contractName: String get() = [email protected] override val moduleSelector: ConfigurationModuleSelector get() = [email protected] override fun getFilter(contract: SolContractDefinition?): Condition<SolFunctionDefinition> { return Condition { psiMethod -> SearchUtils.runnableFilter.invoke(psiMethod) } } }, object : BrowseModuleValueActionListener<JComponent>(myProject) { override fun showDialog(): String? { val virtualFile = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFolderDescriptor(), project, null) return if (virtualFile != null) { FileUtil.toSystemDependentName(virtualFile.path) } else null } }) myContractLocations = arrayOf(myContract, myFunction) // Done myModel.setListener(this) installDocuments() UIUtil.setEnabled(myCommonJavaParameters.programParametersComponent, false, true) myJrePathEditor.anchor = myModule.label myCommonJavaParameters.anchor = myModule.label val model = DefaultComboBoxModel<String>() model.addElement("All") val changeLists = ChangeListManager.getInstance(myProject).changeLists for (changeList in changeLists) { model.addElement(changeList.name) } } public override fun applyEditorTo(configuration: SolidityRunConfig) { myModel.apply(configuration) applyHelpersTo(configuration) configuration.alternativeJrePath = myJrePathEditor.jrePathOrName configuration.isAlternativeJrePathEnabled = myJrePathEditor.isAlternativeJreSelected myCommonJavaParameters.applyTo(configuration) } public override fun resetEditorFrom(configuration: SolidityRunConfig) { myModel.reset(configuration) myCommonJavaParameters.reset(configuration) moduleSelector.reset(configuration) myJrePathEditor .setPathOrName(configuration.alternativeJrePath, configuration.isAlternativeJrePathEnabled) } private fun installDocuments() { for (i in myContractLocations.indices) { val contractLocation = getContractLocation(i) @Suppress("UNCHECKED_CAST") val component = contractLocation.component as ComponentWithBrowseButton<JComponent> var document: Any document = (component.childComponent as EditorTextField).document myBrowsers[i].setField(component) if (myBrowsers[i] is FunctionBrowser) { val childComponent = component.childComponent as EditorTextField (myBrowsers[i] as FunctionBrowser).installCompletion(childComponent) document = childComponent.document } myModel.setContractDocument(i, document) } } private fun getContractLocation(index: Int): LabeledComponent<EditorTextFieldWithBrowseButton> { return myContractLocations[index] } private fun createUIComponents() { myContract = LabeledComponent() myContract.component = EditorTextFieldWithBrowseButton(myProject) myFunction = LabeledComponent() val textFieldWithBrowseButton = EditorTextFieldWithBrowseButton(myProject) myFunction.component = textFieldWithBrowseButton } override fun getAnchor(): JComponent? { return anchor } override fun setAnchor(anchor: JComponent?) { this.anchor = anchor!! myContract.anchor = anchor myFunction.anchor = anchor } public override fun createEditor(): JComponent { return myWholePanel } private fun applyHelpersTo(currentState: SolidityRunConfig) { myCommonJavaParameters.applyTo(currentState) moduleSelector.applyTo(currentState) } private inner class ContractChooserActionListener(project: Project) : ContractClassBrowser(project) { @Throws(ContractBrowser.NoFilterException::class) override fun filter(): IContractFilter.ContractFilterWithScope { try { return ContractFilter.create(SourceScope.wholeProject(project)) } catch (ignore: ContractFilter.NoContractException) { throw ContractBrowser.NoFilterException(MessagesEx.MessageInfo(project, ignore.message, "Can't Browse Inheritors")) } } } private open inner class ContractClassBrowser(project: Project) : ContractBrowser(project, "Choose Contract to execute") { override fun findContract(contractName: String): SolContractDefinition? { return SearchUtils.findContract(contractName, myProject) } @Throws(ContractBrowser.NoFilterException::class) override fun filter(): IContractFilter.ContractFilterWithScope { val contractFilter: IContractFilter.ContractFilterWithScope try { val configurationCopy = SolidityRunConfig(SolidityRunConfigModule(myProject), SolidityConfigurationType.getInstance().configurationFactories[0]) applyEditorTo(configurationCopy) contractFilter = ContractFilter .create(SourceScope.modulesWithDependencies(configurationCopy.modules)) } catch (e: ContractFilter.NoContractException) { throw ContractBrowser.NoFilterException(MessagesEx.MessageInfo(project, "Message", "title")) } return contractFilter } } }
src/main/kotlin/me/serce/solidity/ide/run/ui/SolidityConfigurableEditorPanel.kt
1558857508
class Doo { fun test() { topLevelFunction() } }
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/topLevel/extensionWithCustomFileName/Doo.kt
865019764
package org.livingdoc.repositories.model.scenario import org.livingdoc.repositories.model.Example data class Scenario( val steps: List<Step> ) : Example
livingdoc-repositories/src/main/kotlin/org/livingdoc/repositories/model/scenario/Scenario.kt
1129151216
// MOVE: down fun foo(x: Boolean) { val p = <caret>if (x) { 0 } else { 1 } if (x) { } }
plugins/kotlin/idea/tests/testData/codeInsight/moveUpDown/expressions/ifExprToBlock2.kt
1049392229
class Write { fun test() { with(Main) { companionVariable = 3 } } }
plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/fromCompanion/propertyWithBackingField/Write.kt
1564938944
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.repo import com.intellij.openapi.diagnostic.logger import org.ini4j.Ini import java.io.File import java.io.IOException import java.util.regex.Pattern class GitModulesFileReader { private val LOG = logger<GitModulesFileReader>() private val MODULE_SECTION = Pattern.compile("submodule \"(.*)\"", Pattern.CASE_INSENSITIVE) fun read(file: File): Collection<GitSubmoduleInfo> { if (!file.exists()) return listOf() val ini: Ini try { ini = loadIniFile(file) } catch (e: IOException) { return listOf() } val modules = mutableSetOf<GitSubmoduleInfo>() for ((sectionName, section) in ini) { val matcher = MODULE_SECTION.matcher(sectionName) if (matcher.matches() && matcher.groupCount() == 1) { val path = section["path"] val url = section["url"] if (path == null || url == null) { LOG.warn("Partially defined submodule: $section") } else { val module = GitSubmoduleInfo(path, url) LOG.debug("Found submodule $module") modules.add(module) } } } return modules } }
plugins/git4idea/src/git4idea/repo/GitModulesFileReader.kt
3685835290
package io.sadr.fwc import android.app.Application import android.test.ApplicationTestCase /** * [Testing Fundamentals](http://d.android.com/tools/testing/testing_android.html) */ class ApplicationTest : ApplicationTestCase<Application>(Application::class.java)
app/src/androidTest/kotlin/io/sadr/fwc/ApplicationTest.kt
3187444037
package jp.juggler.subwaytooter.table import android.content.ContentValues import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.provider.BaseColumns import jp.juggler.subwaytooter.api.TootParser import jp.juggler.subwaytooter.api.entity.Acct import jp.juggler.subwaytooter.api.entity.EntityId import jp.juggler.subwaytooter.api.entity.TootAccount import jp.juggler.subwaytooter.api.entity.TootRelationShip import jp.juggler.subwaytooter.global.appDatabase import jp.juggler.util.* class UserRelation { var following = false // 認証ユーザからのフォロー状態にある var followed_by = false // 認証ユーザは被フォロー状態にある var blocking = false // 認証ユーザからブロックした var blocked_by = false // 認証ユーザからブロックされた(Misskeyのみ。Mastodonでは常にfalse) var muting = false var requested = false // 認証ユーザからのフォローは申請中である var requested_by = false // 相手から認証ユーザへのフォローリクエスト申請中(Misskeyのみ。Mastodonでは常にfalse) var following_reblogs = 0 // このユーザからのブーストをTLに表示する var endorsed = false // ユーザをプロフィールで紹介する var notifying = false // ユーザの投稿を通知する var note: String? = null // 認証ユーザからのフォロー状態 fun getFollowing(who: TootAccount?): Boolean { return if (requested && !following && who != null && !who.locked) true else following } // 認証ユーザからのフォローリクエスト申請中状態 fun getRequested(who: TootAccount?): Boolean { return if (requested && !following && who != null && !who.locked) false else requested } companion object : TableCompanion { const val REBLOG_HIDE = 0 // don't show the boosts from target account will be shown on authorized user's home TL. const val REBLOG_SHOW = 1 // show the boosts from target account will be shown on authorized user's home TL. const val REBLOG_UNKNOWN = 2 // not following, or instance don't support hide reblog. private val mMemoryCache = androidx.collection.LruCache<String, UserRelation>(2048) private val log = LogCategory("UserRelationMisskey") override val table = "user_relation_misskey" val columnList: ColumnMeta.List = ColumnMeta.List(table, 30).apply { createExtra = { arrayOf( "create unique index if not exists ${table}_id on $table($COL_DB_ID,$COL_WHO_ID)", "create index if not exists ${table}_time on $table($COL_TIME_SAVE)", ) } deleteBeforeCreate = true } val COL_ID = ColumnMeta(columnList, 0, BaseColumns._ID, "INTEGER PRIMARY KEY", primary = true) private val COL_TIME_SAVE = ColumnMeta(columnList, 0, "time_save", "integer not null") // SavedAccount のDB_ID。 疑似アカウント用のエントリは -2L private val COL_DB_ID = ColumnMeta(columnList, 0, "db_id", "integer not null") // ターゲットアカウントのID val COL_WHO_ID = ColumnMeta(columnList, 0, "who_id", "text not null") private val COL_FOLLOWING = ColumnMeta(columnList, 0, "following", "integer not null") private val COL_FOLLOWED_BY = ColumnMeta(columnList, 0, "followed_by", "integer not null") private val COL_BLOCKING = ColumnMeta(columnList, 0, "blocking", "integer not null") private val COL_MUTING = ColumnMeta(columnList, 0, "muting", "integer not null") private val COL_REQUESTED = ColumnMeta(columnList, 0, "requested", "integer not null") private val COL_FOLLOWING_REBLOGS = ColumnMeta(columnList, 0, "following_reblogs", "integer not null") private val COL_ENDORSED = ColumnMeta(columnList, 32, "endorsed", "integer default 0") private val COL_BLOCKED_BY = ColumnMeta(columnList, 34, "blocked_by", "integer default 0") private val COL_REQUESTED_BY = ColumnMeta(columnList, 35, "requested_by", "integer default 0") private val COL_NOTE = ColumnMeta(columnList, 55, "note", "text default null") private val COL_NOTIFYING = ColumnMeta(columnList, 58, "notifying", "integer default 0") private const val DB_ID_PSEUDO = -2L override fun onDBCreate(db: SQLiteDatabase) = columnList.onDBCreate(db) override fun onDBUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) = columnList.onDBUpgrade(db, oldVersion, newVersion) fun deleteOld(now: Long) { try { val expire = now - 86400000L * 365 appDatabase.delete(table, "$COL_TIME_SAVE<?", arrayOf(expire.toString())) } catch (ex: Throwable) { log.e(ex, "deleteOld failed.") } try { // 旧型式のテーブルの古いデータの削除だけは時々回す val table = "user_relation" val COL_TIME_SAVE = "time_save" val expire = now - 86400000L * 365 appDatabase.delete(table, "$COL_TIME_SAVE<?", arrayOf(expire.toString())) } catch (_: Throwable) { } } private fun key(dbId: Long, whoId: String) = "$dbId:$whoId" private fun key(dbId: Long, whoId: EntityId) = key(dbId, whoId.toString()) private fun ContentValues.fromUserRelation(src: UserRelation) { put(COL_FOLLOWING, src.following) put(COL_FOLLOWED_BY, src.followed_by) put(COL_BLOCKING, src.blocking) put(COL_MUTING, src.muting) put(COL_REQUESTED, src.requested) put(COL_FOLLOWING_REBLOGS, src.following_reblogs) put(COL_ENDORSED, src.endorsed) put(COL_BLOCKED_BY, src.blocked_by) put(COL_REQUESTED_BY, src.requested_by) put(COL_NOTIFYING, src.notifying) put(COL_NOTE, src.note) // may null } private fun ContentValues.fromTootRelationShip(src: TootRelationShip) { put(COL_FOLLOWING, src.following) put(COL_FOLLOWED_BY, src.followed_by) put(COL_BLOCKING, src.blocking) put(COL_MUTING, src.muting) put(COL_REQUESTED, src.requested) put(COL_FOLLOWING_REBLOGS, src.showing_reblogs) put(COL_ENDORSED, src.endorsed) put(COL_BLOCKED_BY, src.blocked_by) put(COL_REQUESTED_BY, src.requested_by) put(COL_NOTIFYING, src.notifying) put(COL_NOTE, src.note) // may null } // マストドン用 fun save1Mastodon(now: Long, dbId: Long, src: TootRelationShip): UserRelation { val id: String = src.id.toString() try { ContentValues().apply { put(COL_TIME_SAVE, now) put(COL_DB_ID, dbId) put(COL_WHO_ID, id) fromTootRelationShip(src) }.let { appDatabase.replaceOrThrow(table, null, it) } mMemoryCache.remove(key(dbId, id)) } catch (ex: Throwable) { log.e(ex, "save failed.") } return load(dbId, id) } // マストドン用 fun saveListMastodon(now: Long, dbId: Long, srcList: Iterable<TootRelationShip>) { val db = appDatabase db.execSQL("BEGIN TRANSACTION") val bOK = try { val cv = ContentValues() cv.put(COL_TIME_SAVE, now) cv.put(COL_DB_ID, dbId) for (src in srcList) { val id = src.id.toString() cv.put(COL_WHO_ID, id) cv.fromTootRelationShip(src) db.replaceOrThrow(table, null, cv) } true } catch (ex: Throwable) { log.trace(ex) log.e(ex, "saveList failed.") false } when { !bOK -> db.execSQL("ROLLBACK TRANSACTION") else -> { db.execSQL("COMMIT TRANSACTION") for (src in srcList) { mMemoryCache.remove(key(dbId, src.id)) } } } } fun save1Misskey(now: Long, dbId: Long, whoId: String, src: UserRelation?) { src ?: return try { ContentValues().apply { put(COL_TIME_SAVE, now) put(COL_DB_ID, dbId) put(COL_WHO_ID, whoId) fromUserRelation(src) }.let { appDatabase.replaceOrThrow(table, null, it) } mMemoryCache.remove(key(dbId, whoId)) } catch (ex: Throwable) { log.e(ex, "save failed.") } } fun saveListMisskey( now: Long, dbId: Long, srcList: List<Map.Entry<EntityId, UserRelation>>, start: Int, end: Int, ) { val db = appDatabase db.execSQL("BEGIN TRANSACTION") val bOK = try { val cv = ContentValues() cv.put(COL_TIME_SAVE, now) cv.put(COL_DB_ID, dbId) for (i in start until end) { val entry = srcList[i] val id = entry.key val src = entry.value cv.put(COL_WHO_ID, id.toString()) cv.fromUserRelation(src) db.replaceOrThrow(table, null, cv) } true } catch (ex: Throwable) { log.trace(ex) log.e(ex, "saveList failed.") false } when { !bOK -> db.execSQL("ROLLBACK TRANSACTION") else -> { db.execSQL("COMMIT TRANSACTION") for (i in start until end) { val entry = srcList[i] val key = key(dbId, entry.key) mMemoryCache.remove(key) } } } } // Misskeyのリレーション取得APIから fun saveListMisskeyRelationApi(now: Long, dbId: Long, list: ArrayList<TootRelationShip>) { val db = appDatabase db.execSQL("BEGIN TRANSACTION") val bOK = try { val cv = ContentValues() cv.put(COL_TIME_SAVE, now) cv.put(COL_DB_ID, dbId) for (src in list) { val id = src.id.toString() cv.put(COL_WHO_ID, id) cv.fromTootRelationShip(src) db.replace(table, null, cv) } true } catch (ex: Throwable) { log.trace(ex) log.e(ex, "saveListMisskeyRelationApi failed.") false } when { !bOK -> db.execSQL("ROLLBACK TRANSACTION") else -> { db.execSQL("COMMIT TRANSACTION") for (src in list) { mMemoryCache.remove(key(dbId, src.id)) } } } } private val loadWhere = "$COL_DB_ID=? and $COL_WHO_ID=?" private val loadWhereArg = object : ThreadLocal<Array<String?>>() { override fun initialValue(): Array<String?> = Array(2) { null } } fun load(dbId: Long, whoId: EntityId): UserRelation { // val key = key(dbId, whoId) val cached: UserRelation? = mMemoryCache.get(key) if (cached != null) return cached val dst = load(dbId, whoId.toString()) mMemoryCache.put(key, dst) return dst } fun load(dbId: Long, whoId: String): UserRelation { try { val where_arg = loadWhereArg.get() ?: arrayOfNulls<String?>(2) where_arg[0] = dbId.toString() where_arg[1] = whoId appDatabase.query(table, null, loadWhere, where_arg, null, null, null) .use { cursor -> if (cursor.moveToNext()) { val dst = UserRelation() dst.following = cursor.getBoolean(COL_FOLLOWING) dst.followed_by = cursor.getBoolean(COL_FOLLOWED_BY) dst.blocking = cursor.getBoolean(COL_BLOCKING) dst.muting = cursor.getBoolean(COL_MUTING) dst.requested = cursor.getBoolean(COL_REQUESTED) dst.following_reblogs = cursor.getInt(COL_FOLLOWING_REBLOGS) dst.endorsed = cursor.getBoolean(COL_ENDORSED) dst.blocked_by = cursor.getBoolean(COL_BLOCKED_BY) dst.requested_by = cursor.getBoolean(COL_REQUESTED_BY) dst.notifying = cursor.getBoolean(COL_NOTIFYING) dst.note = cursor.getStringOrNull(COL_NOTE) return dst } } } catch (ex: Throwable) { log.trace(ex) log.e(ex, "load failed.") } return UserRelation() } // MisskeyはUserエンティティにユーザリレーションが含まれたり含まれなかったりする fun fromAccount(parser: TootParser, src: JsonObject, id: EntityId) { // アカウントのjsonがユーザリレーションを含まないなら何もしない src["isFollowing"] ?: return // プロフカラムで ユーザのプロフ(A)とアカウントTL(B)を順に取得すると // (A)ではisBlockingに情報が入っているが、(B)では情報が入っていない // 対策として(A)でリレーションを取得済みのユーザは(B)のタイミングではリレーションを読み捨てる val map = parser.misskeyUserRelationMap if (map.containsKey(id)) return map[id] = UserRelation().apply { following = src.optBoolean("isFollowing") followed_by = src.optBoolean("isFollowed") muting = src.optBoolean("isMuted") blocking = src.optBoolean("isBlocking") blocked_by = src.optBoolean("isBlocked") endorsed = false requested = src.optBoolean("hasPendingFollowRequestFromYou") requested_by = src.optBoolean("hasPendingFollowRequestToYou") } } fun loadPseudo(acct: Acct) = load(DB_ID_PSEUDO, acct.ascii) fun createCursorPseudo(): Cursor = appDatabase.query( table, arrayOf(COL_ID.name, COL_WHO_ID.name), "$COL_DB_ID=$DB_ID_PSEUDO and ( $COL_MUTING=1 or $COL_BLOCKING=1 )", null, null, null, "$COL_WHO_ID asc" ) fun deletePseudo(rowId: Long) { try { appDatabase.delete(table, "$COL_ID=$rowId", null) } catch (ex: Throwable) { log.trace(ex) } } } fun savePseudo(acct: String) = save1Misskey(System.currentTimeMillis(), DB_ID_PSEUDO, acct, this) }
app/src/main/java/jp/juggler/subwaytooter/table/UserRelation.kt
4176427764
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package vulkan.templates import org.lwjgl.generator.* import vulkan.* val QCOM_image_processing = "QCOMImageProcessing".nativeClassVK("QCOM_image_processing", type = "device", postfix = "QCOM") { documentation = """ GPUs are commonly used to process images for various applications from 3D graphics to UI and from composition to compute applications. Simple scaling and filtering can be done with bilinear filtering, which comes for free during texture sampling. However, as screen sizes get larger and more use-cases rely on GPU such as camera and video post-processing needs, there is increasing demand for GPU to support higher order filtering and other advanced image processing. This extension introduces a new set of SPIR-V built-in functions for image processing. It exposes the following new imaging operations <ul> <li>The {@code OpImageSampleWeightedQCOM} instruction takes 3 operands: <em>sampled image</em>, <em>weight image</em>, and texture coordinates. The instruction computes a weighted average of an MxN region of texels in the <em>sampled image</em>, using a set of MxN weights in the <em>weight image</em>.</li> <li>The {@code OpImageBoxFilterQCOM} instruction takes 3 operands: <em>sampled image</em>, <em>box size</em>, and texture coordinates. Note that <em>box size</em> specifies a floating point width and height in texels. The instruction computes a weighted average of all texels in the <em>sampled image</em> that are covered (either partially or fully) by a box with the specified size and centered at the specified texture coordinates.</li> <li>The {@code OpImageBlockMatchSADQCOM} and {@code OpImageBlockMatchSSDQCOM} instructions each takes 5 operands: <em>target image</em>, <em>target coordinates</em>, <em>reference image</em>, <em>reference coordinates</em>, and <em>block size</em>. Each instruction computes an error metric, that describes whether a block of texels in the <em>target image</em> matches a corresponding block of texels in the <em>reference image</em>. The error metric is computed per-component. {@code OpImageBlockMatchSADQCOM} computes "Sum Of Absolute Difference" and {@code OpImageBlockMatchSSDQCOM} computes "Sum of Squared Difference".</li> </ul> Each of the image processing instructions operate only on 2D images. The instructions do not-support sampling of mipmap, multi-plane, multi-layer, multi-sampled, or depth/stencil images. The instructions can be used in any shader stage. Implementations of this this extension should support these operations natively at the HW instruction level, offering potential performance gains as well as ease of development. <h5>VK_QCOM_image_processing</h5> <dl> <dt><b>Name String</b></dt> <dd>{@code VK_QCOM_image_processing}</dd> <dt><b>Extension Type</b></dt> <dd>Device extension</dd> <dt><b>Registered Extension Number</b></dt> <dd>441</dd> <dt><b>Revision</b></dt> <dd>1</dd> <dt><b>Extension and Version Dependencies</b></dt> <dd><ul> <li>Requires support for Vulkan 1.0</li> <li>Requires {@link KHRFormatFeatureFlags2 VK_KHR_format_feature_flags2} to be enabled for any device-level functionality</li> </ul></dd> <dt><b>Contact</b></dt> <dd><ul> <li>Jeff Leger <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_QCOM_image_processing]%20@jackohound%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_QCOM_image_processing%20extension%3E%3E">jackohound</a></li> </ul></dd> <dt><b>Extension Proposal</b></dt> <dd><a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/tree/main/proposals/VK_QCOM_image_processing.asciidoc">VK_QCOM_image_processing</a></dd> </dl> <h5>Other Extension Metadata</h5> <dl> <dt><b>Last Modified Date</b></dt> <dd>2022-07-08</dd> <dt><b>Interactions and External Dependencies</b></dt> <dd><ul> <li>This extension requires <a target="_blank" href="https://htmlpreview.github.io/?https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/QCOM/SPV_QCOM_image_processing.html">{@code SPV_QCOM_image_processing}</a></li> <li>This extension provides API support for <a target="_blank" href="https://github.com/KhronosGroup/GLSL/blob/master/extensions/qcom/GLSL_QCOM_image_processing.txt">{@code GL_QCOM_image_processing}</a></li> </ul></dd> <dt><b>Contributors</b></dt> <dd><ul> <li>Jeff Leger, Qualcomm Technologies, Inc.</li> <li>Ruihao Zhang, Qualcomm Technologies, Inc.</li> </ul></dd> </dl> """ IntConstant( "The extension specification version.", "QCOM_IMAGE_PROCESSING_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "QCOM_IMAGE_PROCESSING_EXTENSION_NAME".."VK_QCOM_image_processing" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_PROCESSING_FEATURES_QCOM".."1000440000", "STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_PROCESSING_PROPERTIES_QCOM".."1000440001", "STRUCTURE_TYPE_IMAGE_VIEW_SAMPLE_WEIGHT_CREATE_INFO_QCOM".."1000440002" ) EnumConstant( "Extends {@code VkSamplerCreateFlagBits}.", "SAMPLER_CREATE_IMAGE_PROCESSING_BIT_QCOM".enum(0x00000010) ) EnumConstant( "Extends {@code VkImageUsageFlagBits}.", "IMAGE_USAGE_SAMPLE_WEIGHT_BIT_QCOM".enum(0x00100000), "IMAGE_USAGE_SAMPLE_BLOCK_MATCH_BIT_QCOM".enum(0x00200000) ) EnumConstant( "Extends {@code VkDescriptorType}.", "DESCRIPTOR_TYPE_SAMPLE_WEIGHT_IMAGE_QCOM".."1000440000", "DESCRIPTOR_TYPE_BLOCK_MATCH_IMAGE_QCOM".."1000440001" ) EnumConstantLong( "Extends {@code VkFormatFeatureFlagBits2}.", "FORMAT_FEATURE_2_WEIGHT_IMAGE_BIT_QCOM".enum(0x400000000L), "FORMAT_FEATURE_2_WEIGHT_SAMPLED_IMAGE_BIT_QCOM".enum(0x800000000L), "FORMAT_FEATURE_2_BLOCK_MATCHING_BIT_QCOM".enum(0x1000000000L), "FORMAT_FEATURE_2_BOX_FILTER_SAMPLED_BIT_QCOM".enum(0x2000000000L) ) }
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/QCOM_image_processing.kt
3633047434
/* * Copyright 2017, Red Hat, Inc. and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.zanata.dao import org.hibernate.Session import org.zanata.model.ReviewCriteria import javax.enterprise.context.RequestScoped @RequestScoped class ReviewCriteriaDAO : AbstractDAOImpl<ReviewCriteria, Long> { constructor() : super(ReviewCriteria::class.java) constructor(session: Session) : super(ReviewCriteria::class.java, session) fun remove(reviewCriteria: ReviewCriteria) { session.delete(reviewCriteria) } }
server/services/src/main/java/org/zanata/dao/ReviewCriteriaDAO.kt
1411551971
package shitarabatogit import messageutil.* import java.nio.file.Files /** OSDN形式のセリフファイルを現行形式に直したものをプリントする. */ fun main(args: Array<String>) { for (oldFilePath in Files.list(messageutilDir.resolve("shitaraba/old"))) { println(oldFilePath) val messageString = try { parseShitarabaMessage(oldFilePath, strict = false) } catch (e: Exception) { throw RuntimeException("次のファイルでエラーがありました: $oldFilePath", e) } .let { zipBabyChild(it) } .let { renameCommentedMessages(it, shitarabaRenameMap) } .let { messageCollectionToYaml(it) } print(messageString) break } }
subprojects/messageutil/src/test/kotlin/shitarabatogit/Print.kt
230329045
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.remote.server import com.intellij.testGuiFramework.remote.transport.MessageType import com.intellij.testGuiFramework.remote.transport.TransportMessage import org.apache.log4j.Logger import java.io.InvalidClassException import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.net.ServerSocket import java.net.Socket import java.net.SocketException import java.util.* import java.util.concurrent.BlockingQueue import java.util.concurrent.CountDownLatch import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.TimeUnit /** * @author Sergey Karashevich */ class JUnitServerImpl : JUnitServer { private val SEND_THREAD = "JUnit Server Send Thread" private val RECEIVE_THREAD = "JUnit Server Receive Thread" private val postingMessages: BlockingQueue<TransportMessage> = LinkedBlockingQueue() private val receivingMessages: BlockingQueue<TransportMessage> = LinkedBlockingQueue() private val handlers: ArrayList<ServerHandler> = ArrayList() private var failHandler: ((Throwable) -> Unit)? = null private val LOG = Logger.getLogger("#com.intellij.testGuiFramework.remote.server.JUnitServerImpl") private val serverSocket = ServerSocket(0) private lateinit var serverSendThread: ServerSendThread private lateinit var serverReceiveThread: ServerReceiveThread private lateinit var connection: Socket private var isStarted = false private val IDE_STARTUP_TIMEOUT = 180000 private val port: Int init { port = serverSocket.localPort serverSocket.soTimeout = IDE_STARTUP_TIMEOUT } override fun start() { connection = serverSocket.accept() LOG.info("Server accepted client on port: ${connection.port}") serverSendThread = ServerSendThread() serverSendThread.start() serverReceiveThread = ServerReceiveThread() serverReceiveThread.start() isStarted = true } override fun isStarted(): Boolean = isStarted override fun send(message: TransportMessage) { postingMessages.put(message) LOG.info("Add message to send pool: $message ") } override fun receive(): TransportMessage { return receivingMessages.poll(IDE_STARTUP_TIMEOUT.toLong(), TimeUnit.MILLISECONDS) ?: throw SocketException("Client doesn't respond. Either the test has hanged or IDE crushed.") } override fun sendAndWaitAnswer(message: TransportMessage): Unit = sendAndWaitAnswerBase(message) override fun sendAndWaitAnswer(message: TransportMessage, timeout: Long, timeUnit: TimeUnit): Unit = sendAndWaitAnswerBase(message, timeout, timeUnit) private fun sendAndWaitAnswerBase(message: TransportMessage, timeout: Long = 0L, timeUnit: TimeUnit = TimeUnit.SECONDS) { val countDownLatch = CountDownLatch(1) val waitHandler = createCallbackServerHandler({ countDownLatch.countDown() }, message.id) addHandler(waitHandler) send(message) if (timeout == 0L) countDownLatch.await() else countDownLatch.await(timeout, timeUnit) removeHandler(waitHandler) } override fun addHandler(serverHandler: ServerHandler) { handlers.add(serverHandler) } override fun removeHandler(serverHandler: ServerHandler) { handlers.remove(serverHandler) } override fun removeAllHandlers() { handlers.clear() } override fun setFailHandler(failHandler: (Throwable) -> Unit) { this.failHandler = failHandler } override fun isConnected(): Boolean { return try { connection.isConnected && !connection.isClosed } catch (lateInitException: UninitializedPropertyAccessException) { false } } override fun getPort(): Int = port override fun stopServer() { if (!isStarted) return serverSendThread.interrupt() LOG.info("Server Send Thread joined") serverReceiveThread.interrupt() LOG.info("Server Receive Thread joined") connection.close() isStarted = false } private fun createCallbackServerHandler(handler: (TransportMessage) -> Unit, id: Long) = object : ServerHandler() { override fun acceptObject(message: TransportMessage) = message.id == id override fun handleObject(message: TransportMessage) { handler(message) } } private inner class ServerSendThread: Thread(SEND_THREAD) { override fun run() { LOG.info("Server Send Thread started") ObjectOutputStream(connection.getOutputStream()).use { outputStream -> try { while (!connection.isClosed) { val message = postingMessages.take() LOG.info("Sending message: $message ") outputStream.writeObject(message) } } catch (e: Exception) { when (e) { is InterruptedException -> { /* ignore */ } is InvalidClassException -> LOG.error("Probably client is down:", e) else -> { LOG.info(e) failHandler?.invoke(e) } } } } } } private inner class ServerReceiveThread: Thread(RECEIVE_THREAD) { override fun run() { LOG.info("Server Receive Thread started") ObjectInputStream(connection.getInputStream()).use { inputStream -> try { while (!connection.isClosed) { val obj = inputStream.readObject() LOG.debug("Receiving message (DEBUG): $obj") assert(obj is TransportMessage) val message = obj as TransportMessage if (message.type != MessageType.KEEP_ALIVE) LOG.info("Receiving message: $obj") receivingMessages.put(message) handlers.filter { it.acceptObject(message) }.forEach { it.handleObject(message) } } } catch (e: Exception) { when (e) { is InterruptedException -> { /* ignore */ } is InvalidClassException -> LOG.error("Probably serialization error:", e) else -> { LOG.info(e) failHandler?.invoke(e) } } } } } } }
platform/testGuiFramework/src/com/intellij/testGuiFramework/remote/server/JUnitServerImpl.kt
1881094401
package com.virtlink.editorservices.codefolding import java.io.Serializable /** * Folding information. */ interface IFoldingInfo : Serializable { /** * Gets a list of foldable regions. * * Folding regions may be nested in one another, but must not partially overlap. * The list must be ordered by start of the folded region. */ val regions: List<IFoldingRegion> }
aesi/src/main/kotlin/com/virtlink/editorservices/codefolding/IFoldingInfo.kt
3364457663
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.evaluate.variables import com.intellij.debugger.engine.JavaValue import com.intellij.debugger.engine.evaluation.EvaluationContextImpl import com.intellij.debugger.jdi.LocalVariableProxyImpl import com.intellij.debugger.jdi.StackFrameProxyImpl import com.sun.jdi.* import org.jetbrains.kotlin.codegen.AsmUtil import org.jetbrains.kotlin.codegen.AsmUtil.getCapturedFieldName import org.jetbrains.kotlin.codegen.AsmUtil.getLabeledThisName import org.jetbrains.kotlin.codegen.coroutines.CONTINUATION_VARIABLE_NAME import org.jetbrains.kotlin.codegen.coroutines.SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME import org.jetbrains.kotlin.codegen.inline.INLINE_FUN_VAR_SUFFIX import org.jetbrains.kotlin.codegen.inline.INLINE_TRANSFORMATION_SUFFIX import org.jetbrains.kotlin.idea.debugger.base.util.* import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.ExecutionContext import org.jetbrains.kotlin.idea.debugger.core.stackFrame.InlineStackFrameProxyImpl import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.CoroutineStackFrameProxyImpl import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CodeFragmentParameter import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CodeFragmentParameter.Kind import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.DebugLabelPropertyDescriptorProvider import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.utils.addToStdlib.safeAs import kotlin.coroutines.Continuation import com.sun.jdi.Type as JdiType import org.jetbrains.org.objectweb.asm.Type as AsmType class VariableFinder(val context: ExecutionContext) { private val frameProxy = context.frameProxy companion object { private val USE_UNSAFE_FALLBACK: Boolean get() = true private fun getCapturedVariableNameRegex(capturedName: String): Regex { val escapedName = Regex.escape(capturedName) val escapedSuffix = Regex.escape(INLINE_TRANSFORMATION_SUFFIX) return Regex("^$escapedName(?:$escapedSuffix)?$") } } val evaluatorValueConverter = EvaluatorValueConverter(context) val refWrappers: List<RefWrapper> get() = mutableRefWrappers private val mutableRefWrappers = mutableListOf<RefWrapper>() class RefWrapper(val localVariableName: String, val wrapper: Value?) sealed class VariableKind(val asmType: AsmType) { abstract fun capturedNameMatches(name: String): Boolean class Ordinary(val name: String, asmType: AsmType, val isDelegated: Boolean) : VariableKind(asmType) { private val capturedNameRegex = getCapturedVariableNameRegex(getCapturedFieldName(this.name)) override fun capturedNameMatches(name: String) = capturedNameRegex.matches(name) } // TODO Support overloaded local functions class LocalFunction(val name: String, asmType: AsmType) : VariableKind(asmType) { @Suppress("ConvertToStringTemplate") override fun capturedNameMatches(name: String) = name == "$" + name } class UnlabeledThis(asmType: AsmType) : VariableKind(asmType) { override fun capturedNameMatches(name: String) = (name == AsmUtil.CAPTURED_RECEIVER_FIELD || name.startsWith(getCapturedFieldName(AsmUtil.LABELED_THIS_FIELD))) } class OuterClassThis(asmType: AsmType) : VariableKind(asmType) { override fun capturedNameMatches(name: String) = false } class FieldVar(val fieldName: String, asmType: AsmType) : VariableKind(asmType) { // Captured 'field' are not supported yet override fun capturedNameMatches(name: String) = false } class ExtensionThis(val label: String, asmType: AsmType) : VariableKind(asmType) { val parameterName = getLabeledThisName(label, AsmUtil.LABELED_THIS_PARAMETER, AsmUtil.RECEIVER_PARAMETER_NAME) val fieldName = getLabeledThisName(label, getCapturedFieldName(AsmUtil.LABELED_THIS_FIELD), AsmUtil.CAPTURED_RECEIVER_FIELD) private val capturedNameRegex = getCapturedVariableNameRegex(fieldName) override fun capturedNameMatches(name: String) = capturedNameRegex.matches(name) } } class Result(val value: Value?) private class NamedEntity(val name: String, val lazyType: Lazy<JdiType?>, val lazyValue: Lazy<Value?>) { val type: JdiType? get() = lazyType.value val value: Value? get() = lazyValue.value companion object { fun of(field: Field, owner: ObjectReference): NamedEntity { val type = lazy(LazyThreadSafetyMode.PUBLICATION) { field.safeType() } val value = lazy(LazyThreadSafetyMode.PUBLICATION) { owner.getValue(field) } return NamedEntity(field.name(), type, value) } fun of(variable: LocalVariableProxyImpl, frameProxy: StackFrameProxyImpl): NamedEntity { val type = lazy(LazyThreadSafetyMode.PUBLICATION) { variable.safeType() } val value = lazy(LazyThreadSafetyMode.PUBLICATION) { frameProxy.getValue(variable) } return NamedEntity(variable.name(), type, value) } fun of(variable: JavaValue, context: EvaluationContextImpl): NamedEntity { val type = lazy(LazyThreadSafetyMode.PUBLICATION) { variable.descriptor.type } val value = lazy(LazyThreadSafetyMode.PUBLICATION) { variable.descriptor.safeCalcValue(context) } return NamedEntity(variable.name, type, value) } } } fun find(parameter: CodeFragmentParameter, asmType: AsmType): Result? { return when (parameter.kind) { Kind.ORDINARY -> findOrdinary(VariableKind.Ordinary(parameter.name, asmType, isDelegated = false)) Kind.DELEGATED -> findOrdinary(VariableKind.Ordinary(parameter.name, asmType, isDelegated = true)) Kind.FAKE_JAVA_OUTER_CLASS -> thisObject()?.let { Result(it) } Kind.EXTENSION_RECEIVER -> findExtensionThis(VariableKind.ExtensionThis(parameter.name, asmType)) Kind.LOCAL_FUNCTION -> findLocalFunction(VariableKind.LocalFunction(parameter.name, asmType)) Kind.DISPATCH_RECEIVER -> findDispatchThis(VariableKind.OuterClassThis(asmType)) Kind.COROUTINE_CONTEXT -> findCoroutineContext() Kind.FIELD_VAR -> findFieldVariable(VariableKind.FieldVar(parameter.name, asmType)) Kind.DEBUG_LABEL -> findDebugLabel(parameter.name) } } private fun findOrdinary(kind: VariableKind.Ordinary): Result? { val variables = frameProxy.safeVisibleVariables() // Local variables – direct search findLocalVariable(variables, kind, kind.name)?.let { return it } // Recursive search in local receiver variables findCapturedVariableInReceiver(variables, kind)?.let { return it } // Recursive search in captured this return findCapturedVariableInContainingThis(kind) } private fun findFieldVariable(kind: VariableKind.FieldVar): Result? { val thisObject = thisObject() if (thisObject != null) { val field = thisObject.referenceType().fieldByName(kind.fieldName) ?: return null return Result(thisObject.getValue(field)) } else { val containingType = frameProxy.safeLocation()?.declaringType() ?: return null val field = containingType.fieldByName(kind.fieldName) ?: return null return Result(containingType.getValue(field)) } } private fun findLocalFunction(kind: VariableKind.LocalFunction): Result? { val variables = frameProxy.safeVisibleVariables() // Local variables – direct search, new convention val newConventionName = AsmUtil.LOCAL_FUNCTION_VARIABLE_PREFIX + kind.name findLocalVariable(variables, kind, newConventionName)?.let { return it } // Local variables – direct search, old convention (before 1.3.30) findLocalVariable(variables, kind, kind.name + "$")?.let { return it } // Recursive search in local receiver variables findCapturedVariableInReceiver(variables, kind)?.let { return it } // Recursive search in captured this return findCapturedVariableInContainingThis(kind) } private fun findCapturedVariableInContainingThis(kind: VariableKind): Result? { if (frameProxy is CoroutineStackFrameProxyImpl && frameProxy.isCoroutineScopeAvailable()) { findCapturedVariable(kind, frameProxy.thisObject())?.let { return it } return findCapturedVariable(kind, frameProxy.continuation) } val containingThis = thisObject() ?: return null return findCapturedVariable(kind, containingThis) } private fun findExtensionThis(kind: VariableKind.ExtensionThis): Result? { val variables = frameProxy.safeVisibleVariables() // Local variables – direct search val namePredicate = fun(name: String) = name == kind.parameterName || name.startsWith(kind.parameterName + '$') findLocalVariable(variables, kind, namePredicate)?.let { return it } // Recursive search in local receiver variables findCapturedVariableInReceiver(variables, kind)?.let { return it } // Recursive search in captured this findCapturedVariableInContainingThis(kind)?.let { return it } if (USE_UNSAFE_FALLBACK) { // Find an unlabeled this with the compatible type findUnlabeledThis(VariableKind.UnlabeledThis(kind.asmType))?.let { return it } } return null } private fun findDispatchThis(kind: VariableKind.OuterClassThis): Result? { findCapturedVariableInContainingThis(kind)?.let { return it } if (isInsideDefaultImpls()) { val variables = frameProxy.safeVisibleVariables() findLocalVariable(variables, kind, AsmUtil.THIS_IN_DEFAULT_IMPLS)?.let { return it } } val variables = frameProxy.safeVisibleVariables() val inlineDepth = getInlineDepth(variables) if (inlineDepth > 0) { variables.namedEntitySequence() .filter { it.name.matches(INLINED_THIS_REGEX) && getInlineDepth(it.name) == inlineDepth && kind.typeMatches(it.type) } .mapNotNull { it.unwrapAndCheck(kind) } .firstOrNull() ?.let { return it } } if (USE_UNSAFE_FALLBACK) { // Find an unlabeled this with the compatible type findUnlabeledThis(VariableKind.UnlabeledThis(kind.asmType))?.let { return it } } return null } private fun findDebugLabel(name: String): Result? { val markupMap = DebugLabelPropertyDescriptorProvider.getMarkupMap(context.debugProcess) for ((value, markup) in markupMap) { if (markup.text == name) { return Result(value) } } return null } private fun findUnlabeledThis(kind: VariableKind.UnlabeledThis): Result? { val variables = frameProxy.safeVisibleVariables() // Recursive search in local receiver variables findCapturedVariableInReceiver(variables, kind)?.let { return it } return findCapturedVariableInContainingThis(kind) } private fun findLocalVariable(variables: List<LocalVariableProxyImpl>, kind: VariableKind, name: String): Result? { return findLocalVariable(variables, kind) { it == name } } private fun findLocalVariable( variables: List<LocalVariableProxyImpl>, kind: VariableKind, namePredicate: (String) -> Boolean ): Result? { val inlineDepth = frameProxy.safeAs<InlineStackFrameProxyImpl>()?.inlineDepth ?: getInlineDepth(variables) findLocalVariable(variables, kind, inlineDepth, namePredicate)?.let { return it } // Try to find variables outside of inline functions as well if (inlineDepth > 0 && USE_UNSAFE_FALLBACK) { findLocalVariable(variables, kind, 0, namePredicate)?.let { return it } } return null } private fun findLocalVariable( variables: List<LocalVariableProxyImpl>, kind: VariableKind, inlineDepth: Int, namePredicate: (String) -> Boolean ): Result? { val actualPredicate: (String) -> Boolean if (inlineDepth > 0) { actualPredicate = fun(name: String): Boolean { var endIndex = name.length var depth = 0 val suffixLen = INLINE_FUN_VAR_SUFFIX.length while (endIndex >= suffixLen) { if (name.substring(endIndex - suffixLen, endIndex) != INLINE_FUN_VAR_SUFFIX) { break } depth++ endIndex -= suffixLen } return namePredicate(name.take(endIndex)) && getInlineDepth(name) == inlineDepth } } else { actualPredicate = namePredicate } val namedEntities = variables.namedEntitySequence() + getCoroutineStackFrameNamedEntities() for (item in namedEntities) { if (!actualPredicate(item.name) || !kind.typeMatches(item.type)) { continue } val rawValue = item.value val result = evaluatorValueConverter.coerce(getUnwrapDelegate(kind, rawValue), kind.asmType) ?: continue if (!rawValue.isRefType && result.value.isRefType) { // Local variable was wrapped into a Ref instance mutableRefWrappers += RefWrapper(item.name, result.value) } return result } return null } private fun getCoroutineStackFrameNamedEntities() = if (frameProxy is CoroutineStackFrameProxyImpl) { frameProxy.spilledVariables.namedEntitySequence(context.evaluationContext) } else { emptySequence() } private fun isInsideDefaultImpls(): Boolean { val declaringType = frameProxy.safeLocation()?.declaringType() ?: return false return declaringType.name().endsWith(JvmAbi.DEFAULT_IMPLS_SUFFIX) } private fun findCoroutineContext(): Result? { val method = frameProxy.safeLocation()?.safeMethod() ?: return null val result = findCoroutineContextForLambda(method) ?: findCoroutineContextForMethod(method) ?: return null return Result(result) } private fun findCoroutineContextForLambda(method: Method): ObjectReference? { if (method.name() != "invokeSuspend" || method.signature() != "(Ljava/lang/Object;)Ljava/lang/Object;" || frameProxy !is CoroutineStackFrameProxyImpl) { return null } val continuation = frameProxy.continuation ?: return null val continuationType = continuation.referenceType() if (SUSPEND_LAMBDA_CLASSES.none { continuationType.isSubtype(it) }) { return null } return findCoroutineContextForContinuation(continuation) } private fun findCoroutineContextForMethod(method: Method): ObjectReference? { if (CONTINUATION_TYPE.descriptor + ")" !in method.signature()) { return null } val continuationVariable = frameProxy.safeVisibleVariableByName(CONTINUATION_VARIABLE_NAME) ?: frameProxy.safeVisibleVariableByName(SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME) ?: return null val continuation = frameProxy.getValue(continuationVariable) as? ObjectReference ?: return null return findCoroutineContextForContinuation(continuation) } private fun findCoroutineContextForContinuation(continuation: ObjectReference): ObjectReference? { val continuationType = (continuation.referenceType() as? ClassType) ?.allInterfaces()?.firstOrNull { it.name() == Continuation::class.java.name } ?: return null val getContextMethod = continuationType .methodsByName("getContext", "()Lkotlin/coroutines/CoroutineContext;").firstOrNull() ?: return null return context.invokeMethod(continuation, getContextMethod, emptyList()) as? ObjectReference } private fun findCapturedVariableInReceiver(variables: List<LocalVariableProxyImpl>, kind: VariableKind): Result? { fun isReceiverOrPassedThis(name: String) = name.startsWith(AsmUtil.LABELED_THIS_PARAMETER) || name == AsmUtil.RECEIVER_PARAMETER_NAME || name == AsmUtil.THIS_IN_DEFAULT_IMPLS || INLINED_THIS_REGEX.matches(name) // In the old backend captured variables are stored as fields of a generated lambda class. // In the IR backend SAM lambdas are generated as functions, and captured variables are // stored in the LVT table. if (kind is VariableKind.ExtensionThis || kind is VariableKind.Ordinary) { variables.namedEntitySequence() .filter { kind.capturedNameMatches(it.name) && kind.typeMatches(it.type) } .mapNotNull { it.unwrapAndCheck(kind) } .firstOrNull() ?.let { return it } } return variables.namedEntitySequence() .filter { isReceiverOrPassedThis(it.name) } .mapNotNull { findCapturedVariable(kind, it.value) } .firstOrNull() } private fun findCapturedVariable(kind: VariableKind, parentFactory: () -> Value?): Result? { val parent = getUnwrapDelegate(kind, parentFactory()) return findCapturedVariable(kind, parent) } private fun findCapturedVariable(kind: VariableKind, parent: Value?): Result? { val acceptsParentValue = kind is VariableKind.UnlabeledThis || kind is VariableKind.OuterClassThis if (parent != null && acceptsParentValue && kind.typeMatches(parent.type())) { return Result(parent) } val fields = (parent as? ObjectReference)?.referenceType()?.fields() ?: return null if (kind !is VariableKind.OuterClassThis) { // Captured variables - direct search fields.namedEntitySequence(parent) .filter { kind.capturedNameMatches(it.name) && kind.typeMatches(it.type) } .mapNotNull { it.unwrapAndCheck(kind) } .firstOrNull() ?.let { return it } // Recursive search in captured receivers fields.namedEntitySequence(parent) .filter { isCapturedReceiverFieldName(it.name) } .mapNotNull { findCapturedVariable(kind, it.value) } .firstOrNull() ?.let { return it } } // Recursive search in outer and captured this fields.namedEntitySequence(parent) .filter { it.name == AsmUtil.THIS_IN_DEFAULT_IMPLS || it.name == AsmUtil.CAPTURED_THIS_FIELD } .mapNotNull { findCapturedVariable(kind, it.value) } .firstOrNull() ?.let { return it } return null } private fun getUnwrapDelegate(kind: VariableKind, rawValue: Value?): Value? { if (kind !is VariableKind.Ordinary || !kind.isDelegated) { return rawValue } val delegateValue = rawValue as? ObjectReference ?: return rawValue val getValueMethod = delegateValue.referenceType() .methodsByName("getValue", "()Ljava/lang/Object;").firstOrNull() ?: return rawValue return context.invokeMethod(delegateValue, getValueMethod, emptyList()) } private fun isCapturedReceiverFieldName(name: String): Boolean { return name.startsWith(getCapturedFieldName(AsmUtil.LABELED_THIS_FIELD)) || name == AsmUtil.CAPTURED_RECEIVER_FIELD } private fun VariableKind.typeMatches(actualType: JdiType?): Boolean { if (this is VariableKind.Ordinary && isDelegated) { // We can't figure out the actual type of the value yet. // No worries: it will be checked again (and more carefully) in `unwrapAndCheck()`. return true } return evaluatorValueConverter.typeMatches(asmType, actualType) } private fun NamedEntity.unwrapAndCheck(kind: VariableKind): Result? { return evaluatorValueConverter.coerce(getUnwrapDelegate(kind, value), kind.asmType) } private fun List<Field>.namedEntitySequence(owner: ObjectReference): Sequence<NamedEntity> { return asSequence().map { NamedEntity.of(it, owner) } } private fun List<LocalVariableProxyImpl>.namedEntitySequence(): Sequence<NamedEntity> { return asSequence().map { NamedEntity.of(it, frameProxy) } } private fun List<JavaValue>.namedEntitySequence(context: EvaluationContextImpl): Sequence<NamedEntity> { return asSequence().map { NamedEntity.of(it, context) } } private fun thisObject(): ObjectReference? { val thisObjectFromEvaluation = context.evaluationContext.computeThisObject() as? ObjectReference if (thisObjectFromEvaluation != null) { return thisObjectFromEvaluation } return frameProxy.thisObject() } }
plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/variables/VariableFinder.kt
2201614590
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.evaluate import com.intellij.debugger.DebuggerManagerEx import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.JavaDebuggerEvaluator import com.intellij.debugger.engine.evaluation.CodeFragmentFactory import com.intellij.debugger.engine.evaluation.TextWithImports import com.intellij.debugger.engine.events.DebuggerCommandImpl import com.intellij.debugger.impl.DebuggerContextImpl import com.intellij.ide.highlighter.JavaFileType import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiTypesUtil import com.intellij.util.IncorrectOperationException import com.intellij.util.concurrency.Semaphore import com.sun.jdi.AbsentInformationException import com.sun.jdi.InvalidStackFrameException import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.base.projectStructure.hasKotlinJvmRuntime import org.jetbrains.kotlin.idea.core.syncNonBlockingReadAction import org.jetbrains.kotlin.idea.core.util.CodeFragmentUtils import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.KotlinDebuggerEvaluator import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.DebugLabelPropertyDescriptorProvider import org.jetbrains.kotlin.idea.debugger.core.getContextElement import org.jetbrains.kotlin.idea.debugger.base.util.hopelessAware import org.jetbrains.kotlin.idea.j2k.J2kPostProcessor import org.jetbrains.kotlin.idea.j2k.convertToKotlin import org.jetbrains.kotlin.idea.j2k.j2kText import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.j2k.AfterConversionPass import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.types.KotlinType import java.util.concurrent.atomic.AtomicReference class KotlinCodeFragmentFactory : CodeFragmentFactory() { override fun createCodeFragment(item: TextWithImports, context: PsiElement?, project: Project): JavaCodeFragment { val contextElement = getContextElement(context) val codeFragment = KtBlockCodeFragment(project, "fragment.kt", item.text, initImports(item.imports), contextElement) supplyDebugInformation(item, codeFragment, context) codeFragment.putCopyableUserData(CodeFragmentUtils.RUNTIME_TYPE_EVALUATOR) { expression: KtExpression -> val debuggerContext = DebuggerManagerEx.getInstanceEx(project).context val debuggerSession = debuggerContext.debuggerSession if (debuggerSession == null || debuggerContext.suspendContext == null) { null } else { val semaphore = Semaphore() semaphore.down() val nameRef = AtomicReference<KotlinType>() val worker = object : KotlinRuntimeTypeEvaluator( null, expression, debuggerContext, ProgressManager.getInstance().progressIndicator!! ) { override fun typeCalculationFinished(type: KotlinType?) { nameRef.set(type) semaphore.up() } } debuggerContext.debugProcess?.managerThread?.invoke(worker) for (i in 0..50) { ProgressManager.checkCanceled() if (semaphore.waitFor(20)) break } nameRef.get() } } if (contextElement != null && contextElement !is KtElement) { codeFragment.putCopyableUserData(KtCodeFragment.FAKE_CONTEXT_FOR_JAVA_FILE) { val emptyFile = createFakeFileWithJavaContextElement("", contextElement) val debuggerContext = DebuggerManagerEx.getInstanceEx(project).context val debuggerSession = debuggerContext.debuggerSession if ((debuggerSession == null || debuggerContext.suspendContext == null) && !isUnitTestMode() ) { LOG.warn("Couldn't create fake context element for java file, debugger isn't paused on breakpoint") return@putCopyableUserData emptyFile } val frameInfo = getFrameInfo(contextElement, debuggerContext) ?: run { val position = "${debuggerContext.sourcePosition?.file?.name}:${debuggerContext.sourcePosition?.line}" LOG.warn("Couldn't get info about 'this' and local variables for $position") return@putCopyableUserData emptyFile } val fakeFunctionText = buildString { append("fun ") val thisType = frameInfo.thisObject?.asProperty()?.typeReference?.typeElement?.unwrapNullableType() if (thisType != null) { append(thisType.text).append('.') } append(FAKE_JAVA_CONTEXT_FUNCTION_NAME).append("() {\n") for (variable in frameInfo.variables) { val text = variable.asProperty()?.text ?: continue append(" ").append(text).append("\n") } // There should be at least one declaration inside the function (or 'fakeContext' below won't work). append(" val _debug_context_val = 1\n") append("}") } val fakeFile = createFakeFileWithJavaContextElement(fakeFunctionText, contextElement) val fakeFunction = fakeFile.declarations.firstOrNull() as? KtFunction val fakeContext = fakeFunction?.bodyBlockExpression?.statements?.lastOrNull() return@putCopyableUserData fakeContext ?: emptyFile } } return codeFragment } private fun KtTypeElement.unwrapNullableType(): KtTypeElement { return if (this is KtNullableType) innerType ?: this else this } private fun supplyDebugInformation(item: TextWithImports, codeFragment: KtCodeFragment, context: PsiElement?) { val project = codeFragment.project val debugProcess = getDebugProcess(project, context) ?: return DebugLabelPropertyDescriptorProvider(codeFragment, debugProcess).supplyDebugLabels() val evaluationType = when (val evaluator = debugProcess.session.xDebugSession?.currentStackFrame?.evaluator) { is KotlinDebuggerEvaluator -> evaluator.getType(item) is JavaDebuggerEvaluator -> KotlinDebuggerEvaluator.EvaluationType.FROM_JAVA else -> KotlinDebuggerEvaluator.EvaluationType.UNKNOWN } codeFragment.putUserData(EVALUATION_TYPE, evaluationType) } private fun getDebugProcess(project: Project, context: PsiElement?): DebugProcessImpl? { return if (isUnitTestMode()) { context?.getCopyableUserData(DEBUG_CONTEXT_FOR_TESTS)?.debugProcess } else { DebuggerManagerEx.getInstanceEx(project).context.debugProcess } } private fun getFrameInfo(contextElement: PsiElement?, debuggerContext: DebuggerContextImpl): FrameInfo? { val semaphore = Semaphore() semaphore.down() var frameInfo: FrameInfo? = null val worker = object : DebuggerCommandImpl() { override fun action() { try { val frameProxy = hopelessAware { if (isUnitTestMode()) { contextElement?.getCopyableUserData(DEBUG_CONTEXT_FOR_TESTS)?.frameProxy } else { debuggerContext.frameProxy } } frameInfo = FrameInfo.from(debuggerContext.project, frameProxy) } catch (ignored: AbsentInformationException) { // Debug info unavailable } catch (ignored: InvalidStackFrameException) { // Thread is resumed, the frame we have is not valid anymore } finally { semaphore.up() } } } debuggerContext.debugProcess?.managerThread?.invoke(worker) for (i in 0..50) { if (semaphore.waitFor(20)) break } return frameInfo } private fun initImports(imports: String?): String? { if (!imports.isNullOrEmpty()) { return imports.split(KtCodeFragment.IMPORT_SEPARATOR) .mapNotNull { fixImportIfNeeded(it) } .joinToString(KtCodeFragment.IMPORT_SEPARATOR) } return null } private fun fixImportIfNeeded(import: String): String? { // skip arrays if (import.endsWith("[]")) { return fixImportIfNeeded(import.removeSuffix("[]").trim()) } // skip primitive types if (PsiTypesUtil.boxIfPossible(import) != import) { return null } return import } override fun createPresentationCodeFragment(item: TextWithImports, context: PsiElement?, project: Project): JavaCodeFragment { val kotlinCodeFragment = createCodeFragment(item, context, project) if (PsiTreeUtil.hasErrorElements(kotlinCodeFragment) && kotlinCodeFragment is KtCodeFragment) { val javaExpression = try { PsiElementFactory.getInstance(project).createExpressionFromText(item.text, context) } catch (e: IncorrectOperationException) { null } val importList = try { kotlinCodeFragment.importsAsImportList()?.let { (PsiFileFactory.getInstance(project).createFileFromText( "dummy.java", JavaFileType.INSTANCE, it.text ) as? PsiJavaFile)?.importList } } catch (e: IncorrectOperationException) { null } if (javaExpression != null && !PsiTreeUtil.hasErrorElements(javaExpression)) { var convertedFragment: KtExpressionCodeFragment? = null project.executeWriteCommand(KotlinDebuggerEvaluationBundle.message("j2k.expression")) { try { val (elementResults, _, conversionContext) = javaExpression.convertToKotlin() ?: return@executeWriteCommand val newText = elementResults.singleOrNull()?.text val newImports = importList?.j2kText() if (newText != null) { convertedFragment = KtExpressionCodeFragment( project, kotlinCodeFragment.name, newText, newImports, kotlinCodeFragment.context ) AfterConversionPass(project, J2kPostProcessor(formatCode = false)) .run( convertedFragment!!, conversionContext, range = null, onPhaseChanged = null ) } } catch (e: Throwable) { // ignored because text can be invalid LOG.error("Couldn't convert expression:\n`${javaExpression.text}`", e) } } return convertedFragment ?: kotlinCodeFragment } } return kotlinCodeFragment } override fun isContextAccepted(contextElement: PsiElement?): Boolean = runReadAction { when { // PsiCodeBlock -> DummyHolder -> originalElement contextElement is PsiCodeBlock -> isContextAccepted(contextElement.context?.context) contextElement == null -> false contextElement.language == KotlinFileType.INSTANCE.language -> true contextElement.language == JavaFileType.INSTANCE.language -> { val project = contextElement.project val scope = contextElement.resolveScope syncNonBlockingReadAction(project) { scope.hasKotlinJvmRuntime(project) } } else -> false } } override fun getFileType(): KotlinFileType = KotlinFileType.INSTANCE override fun getEvaluatorBuilder() = KotlinEvaluatorBuilder companion object { private val LOG = Logger.getInstance(this::class.java) @get:TestOnly val DEBUG_CONTEXT_FOR_TESTS: Key<DebuggerContextImpl> = Key.create("DEBUG_CONTEXT_FOR_TESTS") val EVALUATION_TYPE: Key<KotlinDebuggerEvaluator.EvaluationType> = Key.create("DEBUG_EVALUATION_TYPE") const val FAKE_JAVA_CONTEXT_FUNCTION_NAME = "_java_locals_debug_fun_" } private fun createFakeFileWithJavaContextElement(funWithLocalVariables: String, javaContext: PsiElement): KtFile { val javaFile = javaContext.containingFile as? PsiJavaFile val sb = StringBuilder() javaFile?.packageName?.takeUnless { it.isBlank() }?.let { sb.append("package ").append(it.quoteIfNeeded()).append("\n") } javaFile?.importList?.let { sb.append(it.text).append("\n") } sb.append(funWithLocalVariables) return KtPsiFactory(javaContext.project).createAnalyzableFile("fakeFileForJavaContextInDebugger.kt", sb.toString(), javaContext) } }
plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinCodeFragmentFactory.kt
214008324
object Pangrams { fun isPangram(text: String): Boolean { return ('a' .. 'z').all { text.contains(it, ignoreCase = true) } } }
exercism/kotlin/pangram/src/main/kotlin/Pangram.kt
3196135298
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiComment import org.jetbrains.kotlin.idea.base.psi.getLineNumber import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.codeinsight.utils.isRedundantSemicolon import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespace import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespace sealed class ConvertLambdaLineIntention(private val toMultiLine: Boolean) : SelfTargetingIntention<KtLambdaExpression>( KtLambdaExpression::class.java, KotlinBundle.lazyMessage("intention.convert.lambda.line", 1.takeIf { toMultiLine } ?: 0), ) { override fun isApplicableTo(element: KtLambdaExpression, caretOffset: Int): Boolean { val functionLiteral = element.functionLiteral val body = functionLiteral.bodyBlockExpression ?: return false val startLine = functionLiteral.getLineNumber(start = true) val endLine = functionLiteral.getLineNumber(start = false) return if (toMultiLine) { startLine == endLine } else { if (startLine == endLine) return false val allChildren = body.allChildren if (allChildren.any { it is PsiComment && it.node.elementType == KtTokens.EOL_COMMENT }) return false val first = allChildren.first?.getNextSiblingIgnoringWhitespace(withItself = true) ?: return true val last = allChildren.last?.getPrevSiblingIgnoringWhitespace(withItself = true) first.getLineNumber(start = true) == last?.getLineNumber(start = false) } } override fun applyTo(element: KtLambdaExpression, editor: Editor?) { val functionLiteral = element.functionLiteral val body = functionLiteral.bodyBlockExpression ?: return val psiFactory = KtPsiFactory(element.project) if (toMultiLine) { body.allChildren.forEach { if (it.node.elementType == KtTokens.SEMICOLON) { body.addAfter(psiFactory.createNewLine(), it) if (isRedundantSemicolon(it)) it.delete() } } } val bodyText = body.text val startLineBreak = if (toMultiLine) "\n" else "" val endLineBreak = if (toMultiLine && bodyText != "") "\n" else "" element.replace( psiFactory.createLambdaExpression( functionLiteral.valueParameters.joinToString { it.text }, "$startLineBreak$bodyText$endLineBreak" ) ) } } class ConvertLambdaToMultiLineIntention : ConvertLambdaLineIntention(toMultiLine = true) class ConvertLambdaToSingleLineIntention : ConvertLambdaLineIntention(toMultiLine = false)
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertLambdaLineIntention.kt
76225293
import IdCacheKeyGenerator.toString import com.apollographql.apollo3.api.CompiledField import com.apollographql.apollo3.api.Executable import com.apollographql.apollo3.cache.normalized.api.CacheKey import com.apollographql.apollo3.cache.normalized.api.CacheKeyGenerator import com.apollographql.apollo3.cache.normalized.api.CacheKeyGeneratorContext import com.apollographql.apollo3.cache.normalized.api.CacheResolver import com.apollographql.apollo3.cache.normalized.api.FieldPolicyCacheResolver import com.apollographql.apollo3.cache.normalized.api.TypePolicyCacheKeyGenerator import com.apollographql.apollo3.testing.checkFile import com.apollographql.apollo3.testing.pathToJsonReader import com.apollographql.apollo3.testing.pathToUtf8 import kotlin.test.assertEquals fun checkTestFixture(actualText: String, name: String) = checkFile(actualText, "integration-tests/testFixtures/$name") fun testFixtureToUtf8(name: String) = pathToUtf8("integration-tests/testFixtures/$name") fun testFixtureToJsonReader(name: String) = pathToJsonReader("integration-tests/testFixtures/$name") /** * A helper function to reverse the order of the argument so that we can easily column edit the tests */ fun assertEquals2(actual: Any?, expected: Any?) = assertEquals(expected, actual) /** * A [CacheResolver] that looks for an "id" argument to resolve fields and delegates to [FieldPolicyCacheResolver] else */ object IdCacheResolver: CacheResolver { override fun resolveField(field: CompiledField, variables: Executable.Variables, parent: Map<String, Any?>, parentId: String): Any? { val id = field.resolveArgument("id", variables)?.toString() if (id != null) { return CacheKey(id) } return FieldPolicyCacheResolver.resolveField(field, variables, parent, parentId) } } /** * A [CacheKeyGenerator] that always uses the "id" field if it exists and delegates to [TypePolicyCacheKeyGenerator] else * * It will coerce Int, Floats and other types to String using [toString] */ object IdCacheKeyGenerator : CacheKeyGenerator { override fun cacheKeyForObject(obj: Map<String, Any?>, context: CacheKeyGeneratorContext): CacheKey? { return obj["id"]?.toString()?.let { CacheKey(it) } ?: TypePolicyCacheKeyGenerator.cacheKeyForObject(obj, context) } }
tests/integration-tests/src/commonTest/kotlin/Utils.kt
2565251281
package com.github.vhromada.catalog.web.mapper.impl import com.github.vhromada.catalog.web.connector.entity.ChangeProgramRequest import com.github.vhromada.catalog.web.connector.entity.Program import com.github.vhromada.catalog.web.fo.ProgramFO import com.github.vhromada.catalog.web.mapper.ProgramMapper import org.springframework.stereotype.Component /** * A class represents implementation of mapper for programs. * * @author Vladimir Hromada */ @Component("programMapper") class ProgramMapperImpl : ProgramMapper { override fun map(source: Program): ProgramFO { return ProgramFO( uuid = source.uuid, name = source.name, wikiEn = source.wikiEn, wikiCz = source.wikiCz, mediaCount = source.mediaCount.toString(), format = source.format, crack = source.crack, serialKey = source.serialKey, otherData = source.otherData, note = source.note ) } override fun mapRequest(source: ProgramFO): ChangeProgramRequest { return ChangeProgramRequest( name = source.name!!, wikiEn = source.wikiEn, wikiCz = source.wikiCz, mediaCount = source.mediaCount!!.toInt(), format = source.format!!, crack = source.crack!!, serialKey = source.serialKey!!, otherData = source.otherData, note = source.note ) } }
web/src/main/kotlin/com/github/vhromada/catalog/web/mapper/impl/ProgramMapperImpl.kt
1824110750
package com.github.vhromada.catalog.web.fo import org.hibernate.validator.constraints.Range import javax.validation.constraints.NotBlank import javax.validation.constraints.NotNull /** * A class represents FO for program. * * @author Vladimir Hromada */ data class ProgramFO( /** * UUID */ val uuid: String?, /** * Name */ @field:NotBlank val name: String?, /** * URL to english Wikipedia page about program */ val wikiEn: String?, /** * URL to czech Wikipedia page about program */ val wikiCz: String?, /** * Count of media */ @field:Range(min = 1, max = 100) val mediaCount: String?, /** * Format */ @field:NotNull val format: String?, /** * True if there is crack */ val crack: Boolean?, /** * True if there is serial key */ val serialKey: Boolean?, /** * Other data */ val otherData: String?, /** * Note */ val note: String? )
web/src/main/kotlin/com/github/vhromada/catalog/web/fo/ProgramFO.kt
2593299778
package org.stepik.android.view.course_info.ui.adapter.delegates import android.view.View import android.view.ViewGroup import by.kirich1409.viewbindingdelegate.viewBinding import org.stepic.droid.R import org.stepic.droid.databinding.ViewCourseInfoAboutBinding import org.stepik.android.view.course_info.model.CourseInfoItem import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder class CourseInfoAboutAdapterDelegate : AdapterDelegate<CourseInfoItem, DelegateViewHolder<CourseInfoItem>>() { override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CourseInfoItem> = ViewHolder(createView(parent, R.layout.view_course_info_about)) override fun isForViewType(position: Int, data: CourseInfoItem): Boolean = data is CourseInfoItem.AboutBlock inner class ViewHolder(root: View) : DelegateViewHolder<CourseInfoItem>(root) { private val viewBinding: ViewCourseInfoAboutBinding by viewBinding { ViewCourseInfoAboutBinding.bind(root) } init { viewBinding.aboutText.textView.setLineSpacing(0f, 1.33f) } override fun onBind(data: CourseInfoItem) { data as CourseInfoItem.AboutBlock viewBinding.aboutText.setText(data.text) } } }
app/src/main/java/org/stepik/android/view/course_info/ui/adapter/delegates/CourseInfoAboutAdapterDelegate.kt
2173850233
package org.stepik.android.cache.assignment.structure object DbStructureAssignment { const val TABLE_NAME = "assignment" object Columns { const val ID = "id" const val STEP = "step" const val UNIT = "unit" const val PROGRESS = "progress" const val CREATE_DATE = "create_date" const val UPDATE_DATE = "update_date" } }
app/src/main/java/org/stepik/android/cache/assignment/structure/DbStructureAssignment.kt
572569071
package org.stepic.droid.code.data import ru.nobird.app.core.model.isNotOrdered /** * Class for fast search strings with common prefix */ class AutocompleteDictionary( private val dict: Array<String>, needSort: Boolean = true, private val isCaseSensitive : Boolean = true ) { companion object { /** * Returns next in chars string. * e.g.: incrementString("aa") == "ab" */ fun incrementString(string: String): String { val chars = string.toCharArray() for (i in chars.size - 1 downTo 0) { if (chars[i] + 1 < chars[i]) { chars[i] = 0.toChar() } else { chars[i] = chars[i] + 1 break } } return if (chars.isEmpty() || chars[0] == 0.toChar()) { 1.toChar() + String(chars) } else { String(chars) } } /** * Kotlin's binarySearch provides element position or position where element should be multiplied by -1. * This method convert result in second case to positive position. */ private fun getBinarySearchPosition(pos: Int): Int = if (pos < 0) -(pos + 1) else pos } init { if (needSort) { dict.sort() } else { require(!dict.isNotOrdered()) { "Given array should be sorted" } } } fun getAutocompleteForPrefix(prefix: String): List<String> { val comparator = Comparator<String> { s1, s2 -> s1.compareTo(s2, ignoreCase = !isCaseSensitive) } val start = dict.binarySearch(prefix, comparator).let(::getBinarySearchPosition) val end = dict.binarySearch(incrementString(prefix), comparator).let(::getBinarySearchPosition) return dict.slice(start until end) } }
app/src/main/java/org/stepic/droid/code/data/AutocompleteDictionary.kt
639319170
package com.oneeyedmen.konsent import com.natpryce.hamkrest.equalTo import org.junit.runner.RunWith @RunWith(Konsent::class) class BetterEnglishTests : AcceptanceTest() { val driver = DummyDriver() val duncan = Actor.with("Duncan", "he", driver, recorder) val alice = Actor.with("Alice", "she", driver, recorder) @Scenario(1) fun `uses 'and' instead of repeating clause`() { Given(duncan).doesAThing("Duncan's thing") Given(alice).doesAThing("Alice's thing") Then(alice).shouldSee(theLastThingHappened, equalTo("Alice's thing happened")) Then(duncan).shouldSee(theLastThingHappened, equalTo("Alice's thing happened")) } @Scenario(2) fun `uses 'and' instead of repeating name and operation`() { Given(duncan).doesAThing("Duncan's thing") Then(duncan).shouldSee(theLastThingHappened, equalTo("Duncan's thing happened")) Then(duncan).shouldSee(theLastThingHappened, equalTo("Alice's thing happened").not()) Then(alice).shouldSee(theLastThingHappened, equalTo("Duncan's thing happened")) } @Scenario(3) fun `uses 'he' instead of repeating name`() { Then(duncan).doesAThing("Duncan's thing") Then(duncan).shouldSee(theLastThingHappened, equalTo("Duncan's thing happened")) } @Scenario(4) fun `uses 'he' instead of repeating name with anonymous term`() { duncan.he.doesAThing("Duncan's thing") duncan.he.shouldSee(theLastThingHappened, equalTo("Duncan's thing happened")) } } val theLastThingHappened = selector<DummyDriver, String?>("the last thing happened") { driver.state } private fun Steps<DummyDriver>.doesAThing(s: String) = describedBy("""does a thing named "$s"""") { driver.doThing(s) } class DummyDriver { var state: String? = null fun doThing(s: String) { state = "$s happened" } }
src/test/java/com/oneeyedmen/konsent/BetterEnglishTests.kt
4058060297
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.authentication.accounts import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.beans.newMetric import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.openapi.components.service import com.intellij.openapi.util.text.StringUtil import org.jetbrains.plugins.github.api.GithubServerPath internal class GithubAccountsStatisticsCollector : ApplicationUsagesCollector() { override fun getVersion() = 2 override fun getMetrics(): Set<MetricEvent> { val accountManager = service<GithubAccountManager>() val hasAccountsWithNonDefaultHost = accountManager.accounts.any { !StringUtil.equalsIgnoreCase(it.server.host, GithubServerPath.DEFAULT_HOST) } return setOf( newMetric("accounts", FeatureUsageData() .addCount(accountManager.accounts.size) .addData("has_enterprise", hasAccountsWithNonDefaultHost))) } override fun getGroupId(): String = "vcs.github" }
plugins/github/src/org/jetbrains/plugins/github/authentication/accounts/GithubAccountsStatisticsCollector.kt
2037978574
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui import com.intellij.ide.ui.UISettings import com.intellij.openapi.options.UnnamedConfigurable import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.checkin.CheckinHandlerUtil.disableWhenDumb import com.intellij.openapi.vcs.configurable.CommitOptionsConfigurable import com.intellij.openapi.vcs.ui.RefreshableOnComponent import com.intellij.ui.components.JBCheckBox import com.intellij.vcs.commit.isNonModalCommit import org.jetbrains.annotations.Nls import java.util.function.Consumer import javax.swing.JComponent import kotlin.reflect.KMutableProperty0 open class BooleanCommitOption( private val checkinPanel: CheckinProjectPanel, @Nls text: String, disableWhenDumb: Boolean, private val getter: () -> Boolean, private val setter: Consumer<Boolean> ) : RefreshableOnComponent, UnnamedConfigurable { constructor(panel: CheckinProjectPanel, @Nls text: String, disableWhenDumb: Boolean, property: KMutableProperty0<Boolean>) : this(panel, text, disableWhenDumb, { property.get() }, Consumer { property.set(it) }) protected val checkBox = JBCheckBox(text).apply { isFocusable = isInSettings || isInNonModalOptionsPopup || UISettings.shadowInstance.disableMnemonicsInControls if (disableWhenDumb && !isInSettings) disableWhenDumb(checkinPanel.project, this, VcsBundle.message("changes.impossible.until.indices.are.up.to.date")) } private val isInSettings get() = checkinPanel is CommitOptionsConfigurable.CheckinPanel private val isInNonModalOptionsPopup get() = checkinPanel.isNonModalCommit override fun refresh() { } override fun saveState() { setter.accept(checkBox.isSelected) } override fun restoreState() { checkBox.isSelected = getter() } override fun getComponent(): JComponent = checkBox override fun createComponent() = component override fun isModified() = checkBox.isSelected != getter() override fun apply() = saveState() override fun reset() = restoreState() }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/BooleanCommitOption.kt
1119750373
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.rebase.log import com.intellij.notification.NotificationType import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.VcsNotifier import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcs.log.VcsShortCommitDetails import com.intellij.vcs.log.data.VcsLogData import com.intellij.vcs.log.impl.VcsCommitMetadataImpl import com.intellij.vcs.log.util.VcsLogUtil import git4idea.i18n.GitBundle private val LOG = Logger.getInstance("Git.Rebase.Log.Action.CommitDetailsLoader") internal fun getOrLoadDetails(project: Project, data: VcsLogData, commitList: List<VcsShortCommitDetails>): List<VcsCommitMetadata> { val commitsToLoad = HashSet<VcsShortCommitDetails>(commitList) val result = HashMap<VcsShortCommitDetails, VcsCommitMetadata>() commitList.forEach { commit -> val commitMetadata = (commit as? VcsCommitMetadata) ?: getCommitDataFromCache(data, commit) if (commitMetadata != null) { result[commit] = commitMetadata } else { commitsToLoad.add(commit) } } val loadedDetails = loadDetails(project, data, commitsToLoad) result.putAll(loadedDetails) return commitList.map { result[it] ?: throw LoadCommitDetailsException() } } private fun getCommitDataFromCache(data: VcsLogData, commit: VcsShortCommitDetails): VcsCommitMetadata? { val commitIndex = data.getCommitIndex(commit.id, commit.root) val commitData = data.commitDetailsGetter.getCommitDataIfAvailable(commitIndex) if (commitData != null) { return commitData } val message = data.index.dataGetter?.getFullMessage(commitIndex) if (message != null) { return VcsCommitMetadataImpl(commit.id, commit.parents, commit.commitTime, commit.root, commit.subject, commit.author, message, commit.committer, commit.authorTime) } return null } private fun loadDetails( project: Project, data: VcsLogData, commits: Collection<VcsShortCommitDetails> ): Map<VcsShortCommitDetails, VcsCommitMetadata> { val result = HashMap<VcsShortCommitDetails, VcsCommitMetadata>() ProgressManager.getInstance().runProcessWithProgressSynchronously( { try { val commitList = commits.toList() if (commitList.isEmpty()) { return@runProcessWithProgressSynchronously } val root = commits.first().root val commitListData = VcsLogUtil.getDetails(data.getLogProvider(root), root, commitList.map { it.id.asString() }) result.putAll(commitList.zip(commitListData)) } catch (e: VcsException) { val error = GitBundle.message("rebase.log.action.loading.commit.message.failed.message", commits.size) LOG.warn(error, e) val notification = VcsNotifier.STANDARD_NOTIFICATION.createNotification( "", error, NotificationType.ERROR, null, "git.log.could.not.load.changes.of.commit" ) VcsNotifier.getInstance(project).notify(notification) } }, GitBundle.message("rebase.log.action.progress.indicator.loading.commit.message.title", commits.size), true, project ) return result } internal class LoadCommitDetailsException : Exception()
plugins/git4idea/src/git4idea/rebase/log/GitLogCommitDetailsLoader.kt
1450109582
package org.livingdoc.example import org.assertj.core.api.Assertions.assertThat import org.livingdoc.api.disabled.Disabled import org.livingdoc.api.documents.ExecutableDocument import org.livingdoc.api.fixtures.decisiontables.BeforeRow import org.livingdoc.api.fixtures.decisiontables.Check import org.livingdoc.api.fixtures.decisiontables.DecisionTableFixture import org.livingdoc.api.fixtures.decisiontables.Input /** * This [ExecutableDocument] demonstrates the [Disabled] annotation. It will not be run during the LivingDoc test execution. Instead its state will be recorded as `Disabled` * * @see Disabled * @see ExecutableDocument */ @Disabled("Skip this document") @ExecutableDocument("local://Calculator.html") class CalculatorDocumentDisabledExecutableDocument { /** * This [DecisionTableFixture] demonstrates that the [Disabled] annotation from above works and you are able to disable the document even if it contains fixtures. * Otherwise this would not be tested. * @see DecisionTableFixture */ @DecisionTableFixture class CalculatorDecisionTableFixture { private lateinit var sut: Calculator @Input("a") private var valueA: Float = 0f private var valueB: Float = 0f @BeforeRow fun beforeRow() { sut = Calculator() } @Input("b") fun setValueB(valueB: Float) { this.valueB = valueB } @Check("a + b = ?") fun checkSum(expectedValue: Float) { val result = sut.sum(valueA, valueB) assertThat(result).isEqualTo(expectedValue) } @Check("a - b = ?") fun checkDiff(expectedValue: Float) { val result = sut.diff(valueA, valueB) assertThat(result).isEqualTo(expectedValue) } @Check("a * b = ?") fun checkMultiply(expectedValue: Float) { val result = sut.multiply(valueA, valueB) assertThat(result).isEqualTo(expectedValue) } @Check("a / b = ?") fun checkDivide(expectedValue: Float) { val result = sut.divide(valueA, valueB) assertThat(result).isEqualTo(expectedValue) } } @DecisionTableFixture class CalculatorDecisionTableFixture2 { private lateinit var sut: Calculator @Input("x") private var valueA: Float = 0f private var valueB: Float = 0f @BeforeRow fun beforeRow() { sut = Calculator() } @Input("y") fun setValueB(valueB: Float) { this.valueB = valueB } @Check("a + b = ?") fun checkSum(expectedValue: Float) { val result = sut.sum(valueA, valueB) assertThat(result).isEqualTo(expectedValue) } @Check("a - b = ?") fun checkDiff(expectedValue: Float) { val result = sut.diff(valueA, valueB) assertThat(result).isEqualTo(expectedValue) } @Check("a * b = ?") fun checkMultiply(expectedValue: Float) { val result = sut.multiply(valueA, valueB) assertThat(result).isEqualTo(expectedValue) } @Check("a / b = ?") fun checkDivide(expectedValue: Float) { val result = sut.divide(valueA, valueB) assertThat(result).isEqualTo(expectedValue) } } }
livingdoc-tests/src/test/kotlin/org/livingdoc/example/CalculatorDocumentDisabledExecutableDocument.kt
3301026874
package com.frightanic.smn.api.geojson /** * Coordinate reference system (CRS) of a GeoJSON object */ class Crs(crs: CrsType) { val type = "name" val properties: Map<String, String> = mapOf("name" to crs.urn) }
src/main/kotlin/com/frightanic/smn/api/geojson/Crs.kt
395608961
package com.intellij.workspace.jps import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleComponent @State(name = "XXX") class TestModuleComponent: ModuleComponent, PersistentStateComponent<TestModuleComponent> { var testString: String = "" override fun getState(): TestModuleComponent? = this override fun loadState(state: TestModuleComponent) { testString = state.testString } companion object { fun getInstance(module: Module): TestModuleComponent = module.getComponent(TestModuleComponent::class.java) } }
platform/workspaceModel-ide-tests/testSrc/com/intellij/workspace/jps/TestModuleComponent.kt
3938041904
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.structureview import com.intellij.ide.projectView.PresentationData import com.intellij.ide.structureView.StructureViewTreeElement import com.intellij.ide.util.treeView.smartTree.SortableTreeElement import com.intellij.ide.util.treeView.smartTree.TreeElement import com.intellij.psi.NavigatablePsiElement import com.intellij.psi.util.PsiTreeUtil import org.editorconfig.language.psi.EditorConfigPsiFile import org.editorconfig.language.psi.EditorConfigRootDeclaration import org.editorconfig.language.psi.EditorConfigSection class EditorConfigStructureViewElement(private val element: NavigatablePsiElement) : StructureViewTreeElement, SortableTreeElement { override fun getValue() = element override fun navigate(requestFocus: Boolean) = element.navigate(requestFocus) override fun canNavigate() = element.canNavigate() override fun canNavigateToSource() = element.canNavigateToSource() override fun getAlphaSortKey() = element.name ?: "" override fun getPresentation() = element.presentation ?: PresentationData() override fun getChildren(): Array<out TreeElement> = when (element) { is EditorConfigPsiFile -> { val roots = PsiTreeUtil .getChildrenOfTypeAsList(element, EditorConfigRootDeclaration::class.java) .map(::EditorConfigStructureViewElement) val sections = element.sections .map(::EditorConfigStructureViewElement) .toTypedArray() (roots + sections).toTypedArray() } is EditorConfigSection -> element.optionList .map(::EditorConfigStructureViewElement) .toTypedArray() else -> emptyArray() } }
plugins/editorconfig/src/org/editorconfig/language/structureview/EditorConfigStructureViewElement.kt
1875016688
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.module.impl import com.intellij.openapi.Disposable import com.intellij.openapi.application.PathManager import com.intellij.openapi.module.UnloadedModuleDescription import com.intellij.openapi.vfs.pointers.VirtualFilePointer import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.module.JpsModuleDependency import org.jetbrains.jps.model.serialization.JpsGlobalLoader import org.jetbrains.jps.model.serialization.JpsProjectLoader import java.nio.file.Paths class UnloadedModuleDescriptionImpl(val modulePath: ModulePath, private val dependencyModuleNames: List<String>, private val contentRoots: List<VirtualFilePointer>) : UnloadedModuleDescription { override fun getGroupPath(): List<String> = modulePath.group?.split(ModuleManagerImpl.MODULE_GROUP_SEPARATOR) ?: emptyList() override fun getName(): String = modulePath.moduleName override fun getContentRoots(): List<VirtualFilePointer> = contentRoots override fun getDependencyModuleNames(): List<String> = dependencyModuleNames override fun equals(other: Any?): Boolean = other is UnloadedModuleDescriptionImpl && name == other.name override fun hashCode(): Int = name.hashCode() companion object { @JvmStatic fun createFromPaths(paths: Collection<ModulePath>, parentDisposable: Disposable): List<UnloadedModuleDescriptionImpl> { val pathVariables = JpsGlobalLoader.computeAllPathVariables(PathManager.getOptionsPath()) val modules = JpsProjectLoader.loadModules(paths.map { Paths.get(it.path) }, null, pathVariables) val pathsByName = paths.associateBy { it.moduleName } return modules.map { create(pathsByName[it.name]!!, it, parentDisposable) } } private fun create(path: ModulePath, module: JpsModule, parentDisposable: Disposable): UnloadedModuleDescriptionImpl { val dependencyModuleNames = module.dependenciesList.dependencies .filterIsInstance(JpsModuleDependency::class.java) .map { it.moduleReference.moduleName } val pointerManager = VirtualFilePointerManager.getInstance() return UnloadedModuleDescriptionImpl(path, dependencyModuleNames, module.contentRootsList.urls.map {pointerManager.create(it, parentDisposable, null)}) } } }
platform/projectModel-impl/src/com/intellij/openapi/module/impl/UnloadedModuleDescriptionImpl.kt
4016793820
package slatekit.requests import slatekit.common.types.ContentFile import java.io.InputStream /** * Support class for the abstract request */ interface RequestSupport { fun raw(): Any? fun getDoc(name: String?): ContentFile? fun getDoc(name: String?, callback: (InputStream) -> ContentFile): ContentFile? fun getFileStream(name: String?): InputStream? }
src/lib/kotlin/slatekit-requests/src/main/kotlin/slatekit/requests/RequestSupport.kt
1789965703
// IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME @JvmName("fooA") private fun String.foo(t: String?): String = this private fun String.foo(t: String): String = this fun runNoInline(fn: () -> String) = fn() fun box() = runNoInline { "O".foo("") } + runNoInline { "K".foo(null) }
backend.native/tests/external/codegen/box/syntheticAccessors/jvmNameForAccessors.kt
3441971175
package com.tristanwiley.chatse.network import android.content.Context import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import com.squareup.okhttp.OkHttpClient import com.squareup.okhttp.Request import com.squareup.okhttp.mockwebserver.MockResponse import com.squareup.okhttp.mockwebserver.MockWebServer import com.tristanwiley.chatse.getMockPrefs import com.tristanwiley.chatse.network.cookie.PersistentCookieStore import org.junit.Ignore import org.junit.Test import kotlin.test.assertEquals class ClientTest { @Test fun testClientCustomStore() { val cookieStore = givenCookieStore() val httpClient = OkHttpClient() val client = Client(httpClient, cookieStore) client.putCookie("http://stackexchange.com", "acct", "content") val expected = "content" val actual = client.getCookie("http://stackexchange.com", "acct") assertEquals(expected, actual) } @Ignore @Test fun testClientGetFromWeb() { val server = MockWebServer() server.enqueue(MockResponse().addHeader("Set-Cookie", "acct=content")) server.start() val cookieStore = givenCookieStore() val httpClient = OkHttpClient() val client = Client(httpClient, cookieStore) val request = Request.Builder().apply { url(server.getUrl("/")) }.build() client.newCall(request).execute() val expected = "content" val actual = client.getCookie(server.getUrl("/").toURI(), "acct") assertEquals(expected, actual) } private fun givenCookieStore(): PersistentCookieStore { val sharedPefs = getMockPrefs() val context = mock<Context>() whenever(context.getSharedPreferences(any(), any())).doReturn(sharedPefs) return PersistentCookieStore(context) } }
app/src/test/kotlin/com/tristanwiley/chatse/network/ClientTest.kt
574600347
// LANGUAGE_VERSION: 1.2 lateinit var ok: String fun box(): String { run { ok = "OK" } return ok }
backend.native/tests/external/codegen/box/properties/lateinit/topLevel/topLevelLateinit.kt
1965107567
/* * Copyright (c) 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.chromeos.videocompositionsample.presentation.ui.screens.player.core import dev.chromeos.videocompositionsample.presentation.opengl.CompositionGLSurfaceView import dev.chromeos.videocompositionsample.presentation.tools.info.MessageModel import dev.chromeos.videocompositionsample.presentation.ui.base.IBaseView import dev.chromeos.videocompositionsample.presentation.ui.custom.CustomSliderView import dev.chromeos.videocompositionsample.presentation.ui.custom.PlayerControlView import dev.chromeos.videocompositionsample.presentation.ui.custom.ResolutionView import dev.chromeos.videocompositionsample.domain.entity.Settings interface IPlayerView : IBaseView { fun onGetSettings(settings: Settings) fun toggleControlPanel() fun hideControlPanel() fun showHideSummary(settings: Settings) fun onPlayersError(notReadyMediaTrackIds: MutableSet<Int>) fun onPlayerPlay() fun onPlayerPause() fun onPlayerSeek() fun onPlayerExport() fun onExportSuccessFinished(messageModel: MessageModel) fun onTimeLineChanged(value: Float) fun getGLSurfaceView(): CompositionGLSurfaceView? fun getSliderTime(): CustomSliderView? fun getPlayerControlView(): PlayerControlView? fun getResolutionView(): ResolutionView? fun showFpsAverageList(fpsAverageList: List<Float>) fun onTestCasesFinished() fun toShare(absoluteFilePath: String) }
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/ui/screens/player/core/IPlayerView.kt
455891017
package runtime.basic.throw0 import kotlin.test.* @Test fun runTest() { val cond = 1 if (cond == 2) throw RuntimeException() if (cond == 3) throw NoSuchElementException("no such element") if (cond == 4) throw Error("error happens") println("Done") }
backend.native/tests/runtime/basic/throw0.kt
2651475789
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.KProperty import kotlin.reflect.KMutableProperty import kotlin.reflect.KMutableProperty1 import kotlin.reflect.full.* import kotlin.reflect.jvm.* object Delegate { operator fun getValue(thiz: My, property: KProperty<*>): String { if (property !is KMutableProperty<*>) return "Fail: property is not a KMutableProperty" property as KMutableProperty1<My, String> try { property.set(thiz, "") return "Fail: property.set should cause IllegalCallableAccessException" } catch (e: IllegalCallableAccessException) { // OK } property.isAccessible = true property.set(thiz, "") return "OK" } operator fun setValue(thiz: My, property: KProperty<*>, value: String) { } } class My { var delegate: String by Delegate private set } fun box() = My().delegate
backend.native/tests/external/codegen/box/delegatedProperty/privateSetterKPropertyIsNotMutable.kt
1087098930
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT open class C(val a: Any) fun box(): String { class L : C({}) { } val l = L() val javaClass = l.a.javaClass val enclosingMethod = javaClass.getEnclosingConstructor()!!.getName() if (enclosingMethod != "LambdaInLocalClassSuperCallKt\$box\$L") return "ctor: $enclosingMethod" val enclosingClass = javaClass.getEnclosingClass()!!.getName() if (enclosingClass != "LambdaInLocalClassSuperCallKt\$box\$L") return "enclosing class: $enclosingClass" if (enclosingMethod != enclosingClass) return "$enclosingClass != $enclosingMethod" val declaringClass = javaClass.getDeclaringClass() if (declaringClass != null) return "anonymous function has a declaring class: $declaringClass" return "OK" }
backend.native/tests/external/codegen/box/reflection/enclosing/lambdaInLocalClassSuperCall.kt
4101580647
class MyNumber(val i: Int) { operator fun inc(): MyNumber = MyNumber(i+1) } class MNR(var ref: MyNumber) {} fun test1() : Boolean { var m = MyNumber(42) m++ if (m.i != 43) return false return true } fun test2() : Boolean { var m = MyNumber(44) var m2 = m++ if (m2.i != 44) return false if (m.i != 45) return false return true } fun test3() : Boolean { var mnr = MNR(MyNumber(42)) mnr.ref++ if (mnr.ref.i != 43) return false return true } fun test4() : Boolean { var mnr = MNR(MyNumber(42)) val m3 = mnr.ref++ if (m3.i != 42) return false return true } fun test5() : Boolean { var mnr = Array<MyNumber>(2,{MyNumber(42)}) mnr[0]++ if (mnr[0].i != 43) return false return true } fun test6() : Boolean { var mnr = Array<MyNumber>(2,{it -> MyNumber(42-it)}) mnr[1] = mnr[0]++ if (mnr[0].i != 43) return false if (mnr[1].i != 42) return false return true } class MyArrayList<T>() { private var value17: T? = null private var value39: T? = null operator fun get(index: Int): T { if (index == 17) return value17!! if (index == 39) return value39!! throw Exception() } operator fun set(index: Int, value: T): T? { if (index == 17) value17 = value else if (index == 39) value39 = value else throw Exception() return null } } fun test7() : Boolean { var mnr = MyArrayList<MyNumber>() mnr[17] = MyNumber(42) mnr[17]++ if (mnr[17].i != 43) return false return true } fun test8() : Boolean { var mnr = MyArrayList<MyNumber>() mnr[17] = MyNumber(42) mnr[39] = mnr[17]++ if (mnr[17].i != 43) return false if (mnr[39].i != 42) return false return true } fun box() : String { var m = MyNumber(42) if (!test1()) return "fail test 1" if (!test2()) return "fail test 2" if (!test3()) return "fail test 3" if (!test4()) return "fail test 4" if (!test5()) return "fail test 5" if (!test6()) return "fail test 6" if (!test7()) return "fail test 7" if (!test8()) return "fail test 8" ++m if (m.i != 43) return "fail 0" var m1 = ++m if (m1.i != 44) return "fail 3" if (m.i != 44) return "fail 4" return "OK" }
backend.native/tests/external/codegen/box/classes/kt471.kt
983129313
// FILE: 1.kt package test inline fun foo(x: (String) -> String, z: String) = x(z) fun String.id() = this // FILE: 2.kt import test.* fun box() : String { var zeroSlot = "fail"; val z = "O" return foo(z::plus, "K") }
backend.native/tests/external/codegen/boxInline/callableReference/bound/intrinsic.kt
309215258
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tealcube.minecraft.bukkit.mythicdrops.api.settings import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.identification.IdentificationItems import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.identification.IdentificationOptions interface IdentifyingSettings { val version: String val options: IdentificationOptions val items: IdentificationItems }
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/api/settings/IdentifyingSettings.kt
4135043852
// FILE: soInlineLibFunInWhen.kt package soInlineLibFunInWhen fun main(args: Array<String>) { //Breakpoint! val l = listOf(1, 2, 3) when { l.any { it > 4 } -> nop() l.any { it > 2 } -> nop() } } fun nop() {} // STEP_OVER: 7 // Note: on the old JVM backend, debugger incorrectly steps into Collections.kt even though we're stepping over it. This is fixed in JVM_IR.
plugins/kotlin/jvm-debugger/test/testData/stepping/stepOver/soInlineLibFunInWhen.kt
965230151
fun foo() { <caret>1 == 2 }
plugins/kotlin/idea/tests/testData/codeInsight/surroundWith/not/booleanExprAtCaret.kt
386320416
package defaultParameterValues2 fun main() { Foo().foo() } interface IFoo { //Breakpoint! fun foo(a: Int = 1) } class Foo : IFoo { override fun foo(a: Int) {} } // EXPRESSION: Foo() // RESULT: instance of defaultParameterValues2.Foo(id=ID): LdefaultParameterValues2/Foo; // EXPRESSION: a // RESULT: Parameter evaluation is not supported for '$default' methods
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/defaultParameterValues2.kt
1126620673
// WITH_STDLIB import B.G fun test() { <caret>B.G.let { it } } class B { object G } class C { object G }
plugins/kotlin/idea/tests/testData/inspectionsLocal/removeRedundantQualifierName/asReceiver.kt
264349937
package my.koza class K fun kokoFun(){}
plugins/kotlin/completion/tests/testData/weighers/basic/Packages.Data.kt
189485979
package otheruse import javapackage.one.JavaClassOne import kotlinpackage.one.extensionSelf fun a() { val javaClassOne = JavaClassOne() println(javaClassOne.onlySuperMethod()) println(javaClassOne.superClassMethod()) println(javaClassOne.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() val d = JavaClassOne() println(d.onlySuperMethod()) println(d.superClassMethod()) println(d.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() d.let { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } d.also { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } with(d) { println(onlySuperMethod()) println(superClassMethod()) println(superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } with(d) out@{ with(4) { println([email protected]()) println([email protected]()) println([email protected]()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } } } fun a2() { val d: JavaClassOne? = null if (d != null) { println(d.onlySuperMethod()) println(d.superClassMethod()) println(d.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } d?.let { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } d?.also { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } with(d) { this?.let { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } } with(d) out@{ with(4) { this@out?.let { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } } } } fun a3() { val d: JavaClassOne? = null val a1 = d?.let { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } val a2 = d?.let { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } val a3 = d?.also { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } val a4 = with(d) { this?.let { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } } val a5 = with(d) out@{ with(4) { this@out?.let { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } } } } fun a4() { val d: JavaClassOne? = null d?.let { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() }?.dec() val a2 = d?.let { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } a2?.toLong() d?.also { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() }?.let { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() }?.and(4) val a4 = with(d) { this?.let { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } } val a5 = with(d) out@{ with(4) { this@out?.let { println(it.onlySuperMethod()) println(it.superClassMethod()) println(it.superClassMethod()) JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } } } val a6 = a4?.let { out -> a5?.let { out + it } } } fun JavaClassOne.b(): Int? { println(onlySuperMethod()) println(superClassMethod()) println(superClassMethod()) return JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } fun JavaClassOne.c(): Int { println(this.onlySuperMethod()) println(this.superClassMethod()) println(this.superClassMethod()) return JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() } fun d(d: JavaClassOne): Int? { println(d.onlySuperMethod()) println(d.superClassMethod()) println(d.superClassMethod()) return JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod() }
plugins/kotlin/idea/tests/testData/refactoring/inlineMultiFile/fromJavaToKotlin/inheritance/after/otherusage/main.kt
675482761
// INTENTION_TEXT: Add @TargetApi(LOLLIPOP) Annotation // INSPECTION_CLASS: com.android.tools.idea.lint.AndroidLintNewApiInspection import android.graphics.drawable.VectorDrawable class VectorDrawableProvider { companion object { val VECTOR_DRAWABLE = <caret>VectorDrawable() } }
plugins/kotlin/idea/tests/testData/android/lintQuickfix/targetApi/companion.kt
1358525533
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.devkit.module import com.intellij.icons.AllIcons import com.intellij.ide.fileTemplates.FileTemplateManager import com.intellij.ide.plugins.PluginManager import com.intellij.ide.starters.local.* import com.intellij.ide.starters.local.gradle.GradleResourcesProvider import com.intellij.ide.starters.local.wizard.StarterInitialStep import com.intellij.ide.starters.shared.* import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.intellij.ide.util.projectWizard.ProjectWizardUtil import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.module.Module import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.SdkTypeId import com.intellij.openapi.roots.ui.configuration.ModulesProvider import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.Strings import com.intellij.pom.java.LanguageLevel import com.intellij.ui.HyperlinkLabel import com.intellij.ui.layout.* import com.intellij.util.lang.JavaVersion import org.jetbrains.annotations.Nls import org.jetbrains.idea.devkit.DevKitBundle import org.jetbrains.idea.devkit.DevKitFileTemplatesFactory import org.jetbrains.idea.devkit.projectRoots.IdeaJdk import java.util.function.Supplier import javax.swing.Icon class DevKitModuleBuilder : StarterModuleBuilder() { private val PLUGIN_TYPE_KEY: Key<PluginType> = Key.create("devkit.plugin.type") override fun getBuilderId(): String = "idea-plugin" override fun getPresentableName(): String = DevKitBundle.message("module.builder.title") override fun getWeight(): Int = IJ_PLUGIN_WEIGHT override fun getNodeIcon(): Icon = AllIcons.Nodes.Plugin override fun getDescription(): String = DevKitBundle.message("module.description") override fun getProjectTypes(): List<StarterProjectType> = emptyList() override fun getTestFrameworks(): List<StarterTestRunner> = emptyList() override fun getMinJavaVersion(): JavaVersion = LanguageLevel.JDK_11.toJavaVersion() override fun getLanguages(): List<StarterLanguage> { return listOf( JAVA_STARTER_LANGUAGE, KOTLIN_STARTER_LANGUAGE ) } override fun getStarterPack(): StarterPack { return StarterPack("devkit", listOf( Starter("devkit", "DevKit", getDependencyConfig("/starters/devkit.pom"), emptyList()) )) } override fun createWizardSteps(context: WizardContext, modulesProvider: ModulesProvider): Array<ModuleWizardStep> { return emptyArray() } override fun createOptionsStep(contextProvider: StarterContextProvider): StarterInitialStep { return DevKitInitialStep(contextProvider) } override fun isSuitableSdkType(sdkType: SdkTypeId?): Boolean { val pluginType = starterContext.getUserData(PLUGIN_TYPE_KEY) ?: PluginType.PLUGIN if (pluginType == PluginType.PLUGIN) { return super.isSuitableSdkType(sdkType) } return sdkType == IdeaJdk.getInstance() } override fun setupModule(module: Module) { // manually set, we do not show the second page with libraries starterContext.starter = starterContext.starterPack.starters.first() starterContext.starterDependencyConfig = loadDependencyConfig()[starterContext.starter?.id] super.setupModule(module) } override fun getAssets(starter: Starter): List<GeneratorAsset> { val ftManager = FileTemplateManager.getInstance(ProjectManager.getInstance().defaultProject) val assets = mutableListOf<GeneratorAsset>() assets.add(GeneratorTemplateFile("build.gradle.kts", ftManager.getJ2eeTemplate(DevKitFileTemplatesFactory.BUILD_GRADLE_KTS))) assets.add(GeneratorTemplateFile("settings.gradle.kts", ftManager.getJ2eeTemplate(DevKitFileTemplatesFactory.SETTINGS_GRADLE_KTS))) assets.add(GeneratorTemplateFile("gradle/wrapper/gradle-wrapper.properties", ftManager.getJ2eeTemplate(DevKitFileTemplatesFactory.GRADLE_WRAPPER_PROPERTIES))) assets.addAll(GradleResourcesProvider().getGradlewResources()) val packagePath = getPackagePath(starterContext.group, starterContext.artifact) if (starterContext.language == JAVA_STARTER_LANGUAGE) { assets.add(GeneratorEmptyDirectory("src/main/java/${packagePath}")) } else if (starterContext.language == KOTLIN_STARTER_LANGUAGE) { assets.add(GeneratorEmptyDirectory("src/main/kotlin/${packagePath}")) } assets.add(GeneratorTemplateFile("src/main/resources/META-INF/plugin.xml", ftManager.getJ2eeTemplate(DevKitFileTemplatesFactory.PLUGIN_XML))) assets.add(GeneratorResourceFile("src/main/resources/META-INF/pluginIcon.svg", javaClass.getResource("/assets/devkit-pluginIcon.svg")!!)) assets.add(GeneratorResourceFile(".run/Run IDE with Plugin.run.xml", javaClass.getResource("/assets/devkit-Run_IDE_with_Plugin.run.xml")!!)) return assets } override fun getGeneratorContextProperties(sdk: Sdk?, dependencyConfig: DependencyConfig): Map<String, String> { return mapOf("pluginTitle" to Strings.capitalize(starterContext.artifact)) } override fun getFilePathsToOpen(): List<String> { return listOf( "src/main/resources/META-INF/plugin.xml", "build.gradle.kts" ) } private inner class DevKitInitialStep(contextProvider: StarterContextProvider) : StarterInitialStep(contextProvider) { private val typeProperty: GraphProperty<PluginType> = propertyGraph.graphProperty { PluginType.PLUGIN } override fun addFieldsBefore(layout: LayoutBuilder) { layout.row(DevKitBundle.message("module.builder.type")) { segmentedButton(listOf(PluginType.PLUGIN, PluginType.THEME), typeProperty) { it.messagePointer.get() } }.largeGapAfter() starterContext.putUserData(PLUGIN_TYPE_KEY, PluginType.PLUGIN) typeProperty.afterChange { pluginType -> starterContext.putUserData(PLUGIN_TYPE_KEY, pluginType) languageRow.visible = pluginType == PluginType.PLUGIN groupRow.visible = pluginType == PluginType.PLUGIN artifactRow.visible = pluginType == PluginType.PLUGIN // Theme / Plugin projects require different SDK type sdkComboBox.selectedJdk = null sdkComboBox.reloadModel() ProjectWizardUtil.preselectJdkForNewModule(wizardContext.project, null, sdkComboBox, Condition(::isSuitableSdkType)) } } override fun addFieldsAfter(layout: LayoutBuilder) { layout.row { hyperLink(DevKitBundle.message("module.builder.how.to.link"), "https://plugins.jetbrains.com/docs/intellij/intellij-platform.html") } layout.row { hyperLink(DevKitBundle.message("module.builder.github.template.link"), "https://github.com/JetBrains/intellij-platform-plugin-template") } if (PluginManager.isPluginInstalled(PluginId.findId("org.intellij.scala"))) { layout.row { hyperLink(DevKitBundle.message("module.builder.scala.github.template.link"), "https://github.com/JetBrains/sbt-idea-plugin") } } } } private fun Row.hyperLink(@Nls title: String, @NlsSafe url: String) { val hyperlinkLabel = HyperlinkLabel(title) hyperlinkLabel.setHyperlinkTarget(url) hyperlinkLabel.toolTipText = url this.component(hyperlinkLabel) } private enum class PluginType( val messagePointer: Supplier<String> ) { PLUGIN(DevKitBundle.messagePointer("module.builder.type.plugin")), THEME(DevKitBundle.messagePointer("module.builder.type.theme")) } }
plugins/devkit/devkit-core/src/module/DevKitModuleBuilder.kt
518414782
package org.ccci.gto.android.common.recyclerview.decorator import org.ccci.gto.android.common.androidx.recyclerview.decorator.MarginItemDecoration @Deprecated("Since v3.11.2, use MarginItemDecoration from gto-support-androidx-recyclerview instead.") typealias MarginItemDecoration = MarginItemDecoration
gto-support-recyclerview/src/main/kotlin/org/ccci/gto/android/common/recyclerview/decorator/MarginItemDecoration.kt
1439097340
val a = "something<caret>"
plugins/kotlin/idea/tests/testData/copyPaste/plainTextLiteral/MultiLine.kt
318873572
// 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.execution.ExecutionBundle import com.intellij.execution.Executor import com.intellij.execution.RunManager import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.configuration.ConfigurationFactoryEx import com.intellij.execution.configurations.* import com.intellij.execution.configurations.ConfigurationTypeUtil.isEditableInDumbMode import com.intellij.execution.impl.RunConfigurable.Companion.collectNodesRecursively import com.intellij.execution.impl.RunConfigurableNodeKind.* import com.intellij.execution.impl.statistics.RunConfigurationOptionUsagesCollector import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.IdeBundle import com.intellij.ide.dnd.TransferableList import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ReadAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.options.Configurable import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.options.SettingsEditorConfigurable import com.intellij.openapi.project.* import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsActions import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.Trinity import com.intellij.openapi.wm.IdeFocusManager import com.intellij.openapi.wm.IdeFocusManager.getGlobalInstance import com.intellij.ui.* import com.intellij.ui.RowsDnDSupport.RefinedDropSupport.Position.* import com.intellij.ui.SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES import com.intellij.ui.awt.RelativePoint import com.intellij.ui.components.JBPanelWithEmptyText import com.intellij.ui.mac.touchbar.Touchbar import com.intellij.ui.mac.touchbar.TouchbarActionCustomizations import com.intellij.ui.popup.PopupState import com.intellij.ui.treeStructure.Tree import com.intellij.util.* import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.containers.TreeTraversal import com.intellij.util.ui.EditableModel import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.util.ui.tree.TreeUtil import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap import net.miginfocom.swing.MigLayout import org.jetbrains.annotations.Nls import java.awt.BorderLayout import java.awt.datatransfer.Transferable import java.awt.event.KeyEvent import java.awt.event.MouseEvent import java.util.concurrent.Callable import java.util.function.ToIntFunction import javax.swing.* import javax.swing.event.DocumentEvent import javax.swing.event.TreeSelectionListener import javax.swing.tree.* import kotlin.math.max private val LOG = logger<RunConfigurable>() @Nls internal fun getUserObjectName(userObject: Any): String { @Suppress("HardCodedStringLiteral") return when (userObject) { is ConfigurationType -> userObject.displayName is ConfigurationFactory -> userObject.name is SingleConfigurationConfigurable<*> -> userObject.nameText is RunnerAndConfigurationSettingsImpl -> userObject.name // Folder objects are strings is String -> userObject else -> userObject.toString() } } fun createRunConfigurationConfigurable(project: Project): RunConfigurable { return when { project.isDefault -> RunConfigurable(project) else -> ProjectRunConfigurationConfigurable(project) } } open class RunConfigurable @JvmOverloads constructor(protected val project: Project, var runDialog: RunDialogBase? = null) : Configurable, Disposable, RunConfigurationCreator { @Volatile private var isDisposed: Boolean = false val root = DefaultMutableTreeNode("Root") val treeModel = MyTreeModel(root) val tree = Tree(treeModel) private val rightPanel = JPanel(BorderLayout()) private val splitter = JBSplitter("RunConfigurable.dividerProportion", 0.3f) private var wholePanel: JPanel? = null private var selectedConfigurable: Configurable? = null private val storedComponents = HashMap<ConfigurationFactory, Configurable>() protected var toolbarDecorator: ToolbarDecorator? = null private var isFolderCreating = false protected val toolbarAddAction = MyToolbarAddAction() private var isModified = false init { runDialog?.let { initTreeSelectionListener(it.getDisposable()) } } private lateinit var changeRunConfigurationNodeAlarm: SingleAlarm private val changeRunConfigurationListener = TreeSelectionListener { if (changeRunConfigurationNodeAlarm.isDisposed) return@TreeSelectionListener changeRunConfigurationNodeAlarm.cancelAndRequest() } companion object { fun collectNodesRecursively(parentNode: DefaultMutableTreeNode, nodes: MutableList<DefaultMutableTreeNode>, vararg allowed: RunConfigurableNodeKind) { for (i in 0 until parentNode.childCount) { val child = parentNode.getChildAt(i) as DefaultMutableTreeNode if (ArrayUtilRt.find(allowed, getKind(child)) != -1) { nodes.add(child) } collectNodesRecursively(child, nodes, *allowed) } } fun getKind(node: DefaultMutableTreeNode?): RunConfigurableNodeKind { if (node == null) { return UNKNOWN } return when (val userObject = node.userObject) { is SingleConfigurationConfigurable<*>, is RunnerAndConfigurationSettings -> { val settings = getSettings(node) ?: return UNKNOWN if (settings.isTemporary) TEMPORARY_CONFIGURATION else CONFIGURATION } is String -> FOLDER else -> if (userObject is ConfigurationType) CONFIGURATION_TYPE else UNKNOWN } } fun isVirtualConfiguration(node: DefaultMutableTreeNode?) = when (node?.userObject) { is SingleConfigurationConfigurable<*>, is RunnerAndConfigurationSettings -> { getSettings(node)?.type is VirtualConfigurationType } is VirtualConfigurationType -> true else -> false } fun configurationTypeSorted(project: Project, showApplicableTypesOnly: Boolean, allTypes: List<ConfigurationType>, hideVirtualConfigurations : Boolean = false): List<ConfigurationType> = getTypesToShow(project, showApplicableTypesOnly, allTypes, hideVirtualConfigurations) .sortedWith(kotlin.Comparator { type1, type2 -> compareTypesForUi(type1!!, type2!!) }) fun getTypesToShow(project: Project, showApplicableTypesOnly: Boolean, allTypes: List<ConfigurationType>, hideVirtualConfigurations : Boolean = false): List<ConfigurationType> { val allVisibleTypes = if (hideVirtualConfigurations) allTypes.filter { it !is VirtualConfigurationType } else allTypes if (showApplicableTypesOnly) { val applicableTypes = allVisibleTypes.filter { configurationType -> configurationType.configurationFactories.any { it.isApplicable(project) } } if (applicableTypes.isNotEmpty() && applicableTypes.size < (allTypes.size - 3)) { return applicableTypes } } return allVisibleTypes } } // https://youtrack.jetbrains.com/issue/TW-61353 fun getSelectedConfigurable() = selectedConfigurable override fun getDisplayName() = ExecutionBundle.message("run.configurable.display.name") protected fun initTree() { tree.isRootVisible = false tree.showsRootHandles = true tree.transferHandler = object : TransferHandler() { override fun createTransferable(component: JComponent): Transferable? { val tree = component as? JTree ?: return null val selection = tree.selectionPaths ?: return null if (selection.size <= 1) return null return object : TransferableList<TreePath>(*selection) { override fun toString(path: TreePath): String { return path.lastPathComponent.toString() } } } override fun getSourceActions(c: JComponent) = COPY_OR_MOVE } TreeUtil.installActions(tree) TreeSpeedSearch(tree) { o -> val node = o.lastPathComponent as DefaultMutableTreeNode when (val userObject = node.userObject) { is RunnerAndConfigurationSettingsImpl -> return@TreeSpeedSearch userObject.name is SingleConfigurationConfigurable<*> -> return@TreeSpeedSearch userObject.nameText else -> if (userObject is ConfigurationType) { return@TreeSpeedSearch userObject.displayName } else if (userObject is String) { return@TreeSpeedSearch userObject } } o.toString() } tree.cellRenderer = RunConfigurableTreeRenderer(runManager) addRunConfigurationsToModel(root) if (ApplicationManager.getApplication().isUnitTestMode) { tree.addTreeSelectionListener { selectRunConfiguration() } } tree.registerKeyboardAction({ clickDefaultButton() }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED) sortTopLevelBranches() tree.emptyText.appendText(ExecutionBundle.message("status.text.no.run.configurations.added")).appendLine( ExecutionBundle.message("status.text.add.new"), LINK_PLAIN_ATTRIBUTES) { toolbarAddAction.showAddPopup(true, it.source as MouseEvent)} val shortcut = KeymapUtil.getShortcutsText(toolbarAddAction.shortcutSet.shortcuts) if (shortcut.isNotEmpty()) tree.emptyText.appendText(" $shortcut") (tree.model as DefaultTreeModel).reload() } protected fun initTreeSelectionListener(parentDisposable: Disposable) { if (tree.treeSelectionListeners.any { it == changeRunConfigurationListener }) return val modalityState = ModalityState.stateForComponent(tree) // The listener is supposed to be registered for a dialog, so the modality state cannot be NON_MODAL if (modalityState == ModalityState.NON_MODAL) return changeRunConfigurationNodeAlarm = SingleAlarm( task = ::selectRunConfiguration, delay = 300, parentDisposable = parentDisposable, threadToUse = Alarm.ThreadToUse.SWING_THREAD, modalityState = modalityState ) tree.addTreeSelectionListener(changeRunConfigurationListener) } private fun selectRunConfiguration() { val selectionPath = tree.selectionPath if (selectionPath != null) { val node = selectionPath.lastPathComponent as DefaultMutableTreeNode when (val userObject = getSafeUserObject(node)) { is SingleConfigurationConfigurable<*> -> { @Suppress("UNCHECKED_CAST") updateRightPanel(userObject as SingleConfigurationConfigurable<RunConfiguration>) } is String -> { showFolderField(node, userObject) } is ConfigurationFactory, is ConfigurationType -> { typeOrFactorySelected(userObject) } } } updateDialog() } protected open fun typeOrFactorySelected(userObject: Any) { if (userObject is ConfigurationType && userObject.configurationFactories.size == 1) { showTemplateConfigurable(userObject.configurationFactories.first()) } else if (userObject is ConfigurationFactory) { showTemplateConfigurable(userObject) } else { updateRightPanel(null) } } protected open fun addRunConfigurationsToModel(model: DefaultMutableTreeNode) { } fun selectConfigurableOnShow() { ApplicationManager.getApplication().invokeLater({ if (isDisposed) { return@invokeLater } tree.requestFocusInWindow() val settings = getSelectedConfiguration() if (settings != null) { if (selectConfiguration(settings.configuration)) { return@invokeLater } } else { selectedConfigurable = null } drawPressAddButtonMessage(null) }, ModalityState.stateForComponent(wholePanel!!)) } protected open fun getSelectedConfiguration(): RunnerAndConfigurationSettings? { return runManager.selectedConfiguration } private fun selectConfiguration(configuration: RunConfiguration): Boolean { val node = findNode(configuration) ?: return false TreeUtil.selectInTree(node, true, tree) return true } private fun findNode(configuration: RunConfiguration): DefaultMutableTreeNode? { val enumeration = root.breadthFirstEnumeration() while (enumeration.hasMoreElements()) { val node = enumeration.nextElement() as DefaultMutableTreeNode var userObject = node.userObject if (userObject is SettingsEditorConfigurable<*>) { userObject = userObject.settings } if (userObject is RunnerAndConfigurationSettingsImpl) { val otherConfiguration = (userObject as RunnerAndConfigurationSettings).configuration if (otherConfiguration.factory?.type?.id == configuration.factory?.type?.id && otherConfiguration.name == configuration.name) { return node } } } return null } private fun showTemplateConfigurable(factory: ConfigurationFactory) { var configurable: Configurable? = storedComponents[factory] if (configurable == null) { configurable = TemplateConfigurable(runManager.getConfigurationTemplate(factory)) storedComponents[factory] = configurable configurable.reset() } updateRightPanel(configurable) } private fun showFolderField(node: DefaultMutableTreeNode, @Nls folderName: String) { rightPanel.removeAll() val p = JPanel(MigLayout("ins ${toolbarDecorator!!.actionsPanel.height} 5 0 0, flowx")) val textField = JTextField(folderName) textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { node.userObject = textField.text treeModel.reload(node) } }) textField.addActionListener { getGlobalInstance().doWhenFocusSettlesDown { getGlobalInstance().requestFocus(tree, true) } } p.add(JLabel(ExecutionBundle.message("run.configuration.folder.name")), "gapright 5") p.add(textField, "pushx, growx, wrap") p.add(JLabel(ExecutionBundle.message("run.configuration.rename.folder.disclaimer")), "gaptop 5, spanx 2") rightPanel.add(p) rightPanel.revalidate() rightPanel.repaint() if (isFolderCreating) { textField.selectAll() getGlobalInstance().doWhenFocusSettlesDown { getGlobalInstance().requestFocus(textField, true) } } } private fun getSafeUserObject(node: DefaultMutableTreeNode): Any { val userObject = node.userObject if (userObject is RunnerAndConfigurationSettingsImpl) { val configurationConfigurable = SingleConfigurationConfigurable.editSettings<RunConfiguration>(userObject as RunnerAndConfigurationSettings, null) installUpdateListeners(configurationConfigurable) node.userObject = configurationConfigurable return configurationConfigurable } return userObject } fun updateRightPanel(configurable: Configurable?) { rightPanel.removeAll() selectedConfigurable = configurable if (configurable == null) { rightPanel.repaint() return } val configurableComponent = if (!project.isDefault && DumbService.getInstance(project).isDumb && !mayBeEditedInDumbMode(configurable)) { JBPanelWithEmptyText().withEmptyText(IdeBundle.message("empty.text.this.view.is.not.available.until.indices.are.built")) } else { configurable.createComponent() } rightPanel.add(BorderLayout.CENTER, configurableComponent) if (configurable is SingleConfigurationConfigurable<*>) { rightPanel.add(configurable.validationComponent, BorderLayout.SOUTH) ApplicationManager.getApplication().invokeLater({ configurable.requestToUpdateWarning() }) { isDisposed } } setupDialogBounds() } private fun mayBeEditedInDumbMode(configurable: Configurable): Boolean = when (configurable) { is SingleConfigurationConfigurable<*> -> isEditableInDumbMode(configurable.configuration) is TemplateConfigurable -> isEditableInDumbMode(configurable.settings) else -> false } private fun sortTopLevelBranches() { val expandedPaths = TreeUtil.collectExpandedPaths(tree) TreeUtil.sortRecursively(root) { o1, o2 -> val userObject1 = o1.userObject val userObject2 = o2.userObject when { userObject1 is ConfigurationType && userObject2 is ConfigurationType -> (userObject1).displayName.compareTo(userObject2.displayName, true) else -> 0 } } TreeUtil.restoreExpandedPaths(tree, expandedPaths) } private fun update() { updateDialog() val selectionPath = tree.selectionPath if (selectionPath != null) { val node = selectionPath.lastPathComponent as DefaultMutableTreeNode treeModel.reload(node) } } private fun installUpdateListeners(info: SingleConfigurationConfigurable<RunConfiguration>) { var changed = false info.editor.addSettingsEditorListener { editor -> ApplicationManager.getApplication().invokeLater( { update() val configuration = info.configuration if (configuration is LocatableConfiguration) { if (configuration.isGeneratedName && !changed) { try { val snapshot = editor.snapshot.configuration as LocatableConfiguration val generatedName = snapshot.suggestedName() if (generatedName != null && generatedName.isNotEmpty()) { info.nameText = generatedName changed = false } } catch (ignore: ConfigurationException) { } } } setupDialogBounds() }, { isDisposed }) } info.addNameListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { changed = true update() } }) info.addSharedListener { changed = true update() } info.addValidationListener { val node = findNode(info.configuration) ?: return@addValidationListener treeModel.nodeChanged(node) } } protected fun drawPressAddButtonMessage(configurationType: ConfigurationType?) { val panel = JPanel(BorderLayout()) if (configurationType !is UnknownConfigurationType) { createTipPanelAboutAddingNewRunConfiguration(configurationType)?.let { panel.add(it, BorderLayout.CENTER) } } rightPanel.removeAll() rightPanel.add(ScrollPaneFactory.createScrollPane(panel, true), BorderLayout.CENTER) rightPanel.revalidate() rightPanel.repaint() } protected open fun createTipPanelAboutAddingNewRunConfiguration(configurationType: ConfigurationType?): JComponent? = null protected open fun createLeftPanel(): JComponent { initTree() return ScrollPaneFactory.createScrollPane(tree) } protected val selectedConfigurationType: ConfigurationType? get() { val configurationTypeNode = selectedConfigurationTypeNode return if (configurationTypeNode != null) configurationTypeNode.userObject as ConfigurationType else null } override fun createComponent(): JComponent? { wholePanel = JPanel(BorderLayout()) DataManager.registerDataProvider(wholePanel!!) { dataId -> when (dataId) { RunConfigurationSelector.KEY.name -> RunConfigurationSelector { configuration -> selectConfiguration(configuration) } CommonDataKeys.PROJECT.name -> project RunConfigurationCreator.KEY.name -> this else -> null } } if (SystemInfo.isMac) { val touchbarActions = DefaultActionGroup(toolbarAddAction) TouchbarActionCustomizations.setShowText(touchbarActions, true) TouchbarActionCustomizations.setCombineWithDlgButtons(touchbarActions, true) Touchbar.setActions(wholePanel!!, touchbarActions) } val leftPanel = createLeftPanel() leftPanel.border = IdeBorderFactory.createBorder(SideBorder.RIGHT) splitter.firstComponent = leftPanel splitter.setHonorComponentsMinimumSize(true) rightPanel.border = JBUI.Borders.empty(15, 5, 0, 15) splitter.secondComponent = rightPanel wholePanel!!.add(splitter, BorderLayout.CENTER) updateDialog() val d = wholePanel!!.preferredSize d.width = max(d.width, 800) d.height = max(d.height, 600) wholePanel!!.preferredSize = d return wholePanel } override fun reset() { isModified = false } @Throws(ConfigurationException::class) override fun apply() { val manager = runManager manager.fireBeginUpdate() try { val settingsToOrder = Object2IntOpenHashMap<RunnerAndConfigurationSettings>() var order = 0 val toDeleteSettings = HashSet(manager.allSettings) val selectedSettings = selectedSettings for (i in 0 until root.childCount) { val node = root.getChildAt(i) as DefaultMutableTreeNode val userObject = node.userObject if (userObject is ConfigurationType) { for (bean in applyByType(node, userObject, selectedSettings)) { settingsToOrder[bean.settings] = order++ toDeleteSettings.remove(bean.settings) } } } manager.removeConfigurations(toDeleteSettings) manager.setOrder(Comparator.comparingInt(ToIntFunction { settingsToOrder.getInt(it) }), isApplyAdditionalSortByTypeAndGroup = false) } finally { manager.fireEndUpdate() } updateActiveConfigurationFromSelected() isModified = false tree.repaint() } protected fun applyTemplates() { for (configurable in storedComponents.values) { if (configurable.isModified) { configurable.apply() } } } open fun updateActiveConfigurationFromSelected() { val selectedConfigurable = selectedConfigurable if (selectedConfigurable is SingleConfigurationConfigurable<*>) { runManager.selectedConfiguration = selectedConfigurable.settings } } @Throws(ConfigurationException::class) private fun applyByType(typeNode: DefaultMutableTreeNode, type: ConfigurationType, selectedSettings: RunnerAndConfigurationSettings?): List<RunConfigurationBean> { var indexToMove = -1 val configurationBeans = ArrayList<RunConfigurationBean>() val names = HashSet<String>() val configurationNodes = ArrayList<DefaultMutableTreeNode>() collectNodesRecursively(typeNode, configurationNodes, CONFIGURATION, TEMPORARY_CONFIGURATION) for (node in configurationNodes) { val userObject = node.userObject var configurationBean: RunConfigurationBean? = null var settings: RunnerAndConfigurationSettings? = null if (userObject is SingleConfigurationConfigurable<*>) { settings = userObject.settings applyConfiguration(typeNode, userObject) configurationBean = RunConfigurationBean(userObject) } else if (userObject is RunnerAndConfigurationSettingsImpl) { settings = userObject configurationBean = RunConfigurationBean(settings) } if (configurationBean != null) { val configurable = configurationBean.configurable val nameText = if (configurable != null) configurable.nameText else configurationBean.settings.name if (!names.add(nameText)) { TreeUtil.selectNode(tree, node) throw ConfigurationException( ExecutionBundle.message("dialog.message.run.configuration.already.exists", type.displayName, nameText)) } configurationBeans.add(configurationBean) if (settings === selectedSettings) { indexToMove = configurationBeans.size - 1 } } } val folderNodes = ArrayList<DefaultMutableTreeNode>() collectNodesRecursively(typeNode, folderNodes, FOLDER) names.clear() for (node in folderNodes) { val folderName = node.userObject as String if (folderName.isEmpty()) { TreeUtil.selectNode(tree, node) throw ConfigurationException(ExecutionBundle.message("dialog.message.folder.name.should.not.be.empty")) } if (!names.add(folderName)) { TreeUtil.selectNode(tree, node) throw ConfigurationException(ExecutionBundle.message("dialog.message.folders.have.same.name", folderName)) } } // try to apply all for (bean in configurationBeans) { applyConfiguration(typeNode, bean.configurable) } // just saved as 'stable' configuration shouldn't stay between temporary ones (here we order model to save) var shift = 0 if (selectedSettings != null && selectedSettings.type === type) { shift = adjustOrder() } if (shift != 0 && indexToMove != -1) { configurationBeans.add(indexToMove - shift, configurationBeans.removeAt(indexToMove)) } return configurationBeans } private fun getConfigurationTypeNode(type: ConfigurationType): DefaultMutableTreeNode? { for (i in 0 until root.childCount) { val node = root.getChildAt(i) as DefaultMutableTreeNode if (node.userObject === type) { return node } } return null } @Throws(ConfigurationException::class) private fun applyConfiguration(typeNode: DefaultMutableTreeNode, configurable: SingleConfigurationConfigurable<*>?) { try { if (configurable != null && configurable.isModified) { configurable.apply() } } catch (e: ConfigurationException) { for (i in 0 until typeNode.childCount) { val node = typeNode.getChildAt(i) as DefaultMutableTreeNode if (configurable == node.userObject) { TreeUtil.selectNode(tree, node) break } } throw e } } override fun isModified(): Boolean { if (isModified) { return true } val runManager = runManager val allSettings = runManager.allSettings var currentSettingCount = 0 for (i in 0 until root.childCount) { val typeNode = root.getChildAt(i) as DefaultMutableTreeNode val configurationType = typeNode.userObject as? ConfigurationType ?: continue val configurationNodes = ArrayList<DefaultMutableTreeNode>() collectNodesRecursively(typeNode, configurationNodes, CONFIGURATION, TEMPORARY_CONFIGURATION) val allTypeSettings = allSettings.filter { it.type == configurationType } if (allTypeSettings.size != configurationNodes.size) { return true } var currentTypeSettingsCount = 0 for (configurationNode in configurationNodes) { val userObject = configurationNode.userObject val settings: RunnerAndConfigurationSettings if (userObject is SingleConfigurationConfigurable<*>) { if (userObject.isModified) { return true } settings = userObject.settings } else if (userObject is RunnerAndConfigurationSettings) { settings = userObject } else { continue } currentSettingCount++ val index = currentTypeSettingsCount++ // we compare by instance, equals is not implemented and in any case object modification is checked by other logic // we compare by index among current types settings because indexes among all configurations may differ // since temporary configurations are stored in the end if (allTypeSettings.size <= index || allTypeSettings[index] !== settings) { return true } } } return allSettings.size != currentSettingCount || storedComponents.values.any { it.isModified } } override fun disposeUIResources() { Disposer.dispose(this) } override fun dispose() { isDisposed = true storedComponents.values.forEach { it.disposeUIResources() } storedComponents.clear() TreeUtil.treeNodeTraverser(root) .traverse(TreeTraversal.PRE_ORDER_DFS) .processEach { node -> ((node as? DefaultMutableTreeNode)?.userObject as? SingleConfigurationConfigurable<*>)?.disposeUIResources() true } rightPanel.removeAll() splitter.dispose() } private fun updateDialog() { val runDialog = runDialog val executor = runDialog?.executor ?: return val buffer = StringBuilder() buffer.append(executor.id) val configuration = selectedConfiguration if (configuration != null) { buffer.append(" - ") buffer.append(configuration.nameText) } ReadAction.nonBlocking(Callable { canRunConfiguration(configuration, executor) }) .finishOnUiThread(ModalityState.current()) { runDialog.setOKActionEnabled(it) } .submit(AppExecutorUtil.getAppExecutorService()) runDialog.setTitle(buffer.toString()) } private fun setupDialogBounds() { SwingUtilities.invokeLater { UIUtil.setupEnclosingDialogBounds(wholePanel!!) } } private val selectedConfiguration: SingleConfigurationConfigurable<RunConfiguration>? get() { val selectionPath = tree.selectionPath if (selectionPath != null) { val treeNode = selectionPath.lastPathComponent as DefaultMutableTreeNode val userObject = treeNode.userObject if (userObject is SingleConfigurationConfigurable<*>) { @Suppress("UNCHECKED_CAST") return userObject as SingleConfigurationConfigurable<RunConfiguration> } } return null } open val runManager: RunManagerImpl get() = RunManagerImpl.getInstanceImpl(project) override fun getHelpTopic(): String? { return selectedConfigurationType?.helpTopic ?: "reference.dialogs.rundebug" } private fun clickDefaultButton() { runDialog?.clickDefaultButton() } private val selectedConfigurationTypeNode: DefaultMutableTreeNode? get() { val selectionPath = tree.selectionPath var node: DefaultMutableTreeNode? = if (selectionPath != null) selectionPath.lastPathComponent as DefaultMutableTreeNode else null while (node != null) { val userObject = node.userObject if (userObject is ConfigurationType) { return node } node = node.parent as? DefaultMutableTreeNode } return null } private fun getNode(row: Int) = tree.getPathForRow(row).lastPathComponent as DefaultMutableTreeNode fun getAvailableDropPosition(direction: Int): Trinity<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>? { val rows = tree.selectionRows if (rows == null || rows.size != 1) { return null } val oldIndex = rows[0] var newIndex = oldIndex + direction if (!getKind(tree.getPathForRow(oldIndex).lastPathComponent as DefaultMutableTreeNode).supportsDnD()) { return null } while (newIndex > 0 && newIndex < tree.rowCount) { val targetPath = tree.getPathForRow(newIndex) val allowInto = getKind(targetPath.lastPathComponent as DefaultMutableTreeNode) == FOLDER && !tree.isExpanded(targetPath) val position = when { allowInto && treeModel.isDropInto(tree, oldIndex, newIndex) -> INTO direction > 0 -> BELOW else -> ABOVE } val oldNode = getNode(oldIndex) val newNode = getNode(newIndex) if (oldNode.parent !== newNode.parent && getKind(newNode) != FOLDER) { var copy = position if (position == BELOW) { copy = ABOVE } else if (position == ABOVE) { copy = BELOW } if (treeModel.canDrop(oldIndex, newIndex, copy)) { return Trinity.create(oldIndex, newIndex, copy) } } if (treeModel.canDrop(oldIndex, newIndex, position)) { return Trinity.create(oldIndex, newIndex, position) } when { position == BELOW && newIndex < tree.rowCount - 1 && treeModel.canDrop(oldIndex, newIndex + 1, ABOVE) -> return Trinity.create(oldIndex, newIndex + 1, ABOVE) position == ABOVE && newIndex > 1 && treeModel.canDrop(oldIndex, newIndex - 1, BELOW) -> return Trinity.create(oldIndex, newIndex - 1, BELOW) position == BELOW && treeModel.canDrop(oldIndex, newIndex, ABOVE) -> return Trinity.create(oldIndex, newIndex, ABOVE) position == ABOVE && treeModel.canDrop(oldIndex, newIndex, BELOW) -> return Trinity.create(oldIndex, newIndex, BELOW) else -> newIndex += direction } } return null } private fun createNewConfiguration(settings: RunnerAndConfigurationSettings, node: DefaultMutableTreeNode?, selectedNode: DefaultMutableTreeNode?): SingleConfigurationConfigurable<RunConfiguration> { val configurationConfigurable = SingleConfigurationConfigurable.editSettings<RunConfiguration>(settings, null) installUpdateListeners(configurationConfigurable) val nodeToAdd = DefaultMutableTreeNode(configurationConfigurable) treeModel.insertNodeInto(nodeToAdd, node!!, if (selectedNode != null) node.getIndex(selectedNode) + 1 else node.childCount) TreeUtil.selectNode(tree, nodeToAdd) IdeFocusManager.getInstance(project).requestFocus(configurationConfigurable.nameTextField, true) configurationConfigurable.nameTextField.selectionStart = 0 configurationConfigurable.nameTextField.selectionEnd = settings.name.length return configurationConfigurable } override fun createNewConfiguration(factory: ConfigurationFactory): SingleConfigurationConfigurable<RunConfiguration> { var typeNode = getConfigurationTypeNode(factory.type) if (typeNode == null) { typeNode = DefaultMutableTreeNode(factory.type) root.add(typeNode) sortTopLevelBranches() (tree.model as DefaultTreeModel).reload() } val selectedNode = tree.selectionPath?.lastPathComponent as? DefaultMutableTreeNode var node = typeNode if (selectedNode != null && typeNode.isNodeDescendant(selectedNode)) { node = selectedNode if (getKind(node).isConfiguration) { node = node.parent as DefaultMutableTreeNode } } val settings = runManager.createConfiguration("", factory) val configuration = settings.configuration configuration.name = createUniqueName(typeNode, suggestName(configuration), CONFIGURATION, TEMPORARY_CONFIGURATION) (configuration as? LocatableConfigurationBase<*>)?.setNameChangedByUser(false) callNewConfigurationCreated(factory, configuration) RunConfigurationOptionUsagesCollector.logAddNew(project, factory.type.id, ActionPlaces.RUN_CONFIGURATION_EDITOR) return createNewConfiguration(settings, node, selectedNode) } private fun suggestName(configuration: RunConfiguration): String? { if (configuration is LocatableConfiguration) { val name = configuration.suggestedName() if (name != null && name.isNotEmpty()) { return name } } return null } protected inner class MyToolbarAddAction : AnAction(ExecutionBundle.message("add.new.run.configuration.action2.name"), ExecutionBundle.message("add.new.run.configuration.action2.name"), IconUtil.getAddIcon()), AnActionButtonRunnable { private val myPopupState = PopupState.forPopup() init { registerCustomShortcutSet(CommonShortcuts.INSERT, tree) } override fun actionPerformed(e: AnActionEvent) { showAddPopup(true, null) } override fun run(button: AnActionButton) { showAddPopup(true, null) } fun showAddPopup(showApplicableTypesOnly: Boolean, clickEvent: MouseEvent?) { if (showApplicableTypesOnly && myPopupState.isRecentlyHidden) return // do not show new popup val allTypes = ConfigurationType.CONFIGURATION_TYPE_EP.extensionList val configurationTypes: MutableList<ConfigurationType?> = configurationTypeSorted(project, showApplicableTypesOnly, allTypes, true).toMutableList() val hiddenCount = allTypes.size - configurationTypes.size if (hiddenCount > 0) { configurationTypes.add(NewRunConfigurationPopup.HIDDEN_ITEMS_STUB) } val popup = NewRunConfigurationPopup.createAddPopup(project, configurationTypes, ExecutionBundle.message("show.irrelevant.configurations.action.name", hiddenCount), { factory -> createNewConfiguration(factory) }, selectedConfigurationType, { showAddPopup(false, null) }, true) //new TreeSpeedSearch(myTree); myPopupState.prepareToShow(popup) if (clickEvent == null) popup.showUnderneathOf(toolbarDecorator!!.actionsPanel) else popup.show(RelativePoint(clickEvent)) } } protected inner class MyRemoveAction : AnAction(ExecutionBundle.message("remove.run.configuration.action.name"), ExecutionBundle.message("remove.run.configuration.action.name"), IconUtil.getRemoveIcon()), AnActionButtonRunnable, AnActionButtonUpdater { init { registerCustomShortcutSet(CommonShortcuts.getDelete(), tree) } override fun actionPerformed(e: AnActionEvent) { doRemove() } override fun run(button: AnActionButton) { doRemove() } private fun doRemove() { val selections = tree.selectionPaths tree.clearSelection() var nodeIndexToSelect = -1 var parentToSelect: DefaultMutableTreeNode? = null val changedParents = HashSet<DefaultMutableTreeNode>() var wasRootChanged = false for (each in selections!!) { val node = each.lastPathComponent as DefaultMutableTreeNode val parent = node.parent as DefaultMutableTreeNode val kind = getKind(node) if (!kind.isConfiguration && kind != FOLDER || isVirtualConfiguration(node)) continue if (node.userObject is SingleConfigurationConfigurable<*>) { val configurable = node.userObject as SingleConfigurationConfigurable<*> RunConfigurationOptionUsagesCollector.logRemove(project, configurable.configuration.type.id, ActionPlaces.RUN_CONFIGURATION_EDITOR) configurable.disposeUIResources() } nodeIndexToSelect = parent.getIndex(node) parentToSelect = parent treeModel.removeNodeFromParent(node) changedParents.add(parent) if (kind == FOLDER) { val children = ArrayList<DefaultMutableTreeNode>() for (i in 0 until node.childCount) { val child = node.getChildAt(i) as DefaultMutableTreeNode val userObject = getSafeUserObject(child) if (userObject is SingleConfigurationConfigurable<*>) { userObject.folderName = null } children.add(0, child) } var confIndex = 0 for (i in 0 until parent.childCount) { if (getKind(parent.getChildAt(i) as DefaultMutableTreeNode).isConfiguration) { confIndex = i break } } for (child in children) { if (getKind(child) == CONFIGURATION) treeModel.insertNodeInto(child, parent, confIndex) } confIndex = parent.childCount for (i in 0 until parent.childCount) { if (getKind(parent.getChildAt(i) as DefaultMutableTreeNode) == TEMPORARY_CONFIGURATION) { confIndex = i break } } for (child in children) { if (getKind(child) == TEMPORARY_CONFIGURATION) { treeModel.insertNodeInto(child, parent, confIndex) } } } if (parent.childCount == 0 && parent.userObject is ConfigurationType) { changedParents.remove(parent) wasRootChanged = true nodeIndexToSelect = root.getIndex(parent) nodeIndexToSelect = max(0, nodeIndexToSelect - 1) parentToSelect = root parent.removeFromParent() } } if (wasRootChanged) { (tree.model as DefaultTreeModel).reload() } else { for (each in changedParents) { treeModel.reload(each) tree.expandPath(TreePath(each)) } } selectedConfigurable = null if (root.childCount == 0) { drawPressAddButtonMessage(null) } else { if (parentToSelect!!.childCount > 0) { val nodeToSelect = if (nodeIndexToSelect < parentToSelect.childCount) { parentToSelect.getChildAt(nodeIndexToSelect) } else { parentToSelect.getChildAt(nodeIndexToSelect - 1) } TreeUtil.selectInTree(nodeToSelect as DefaultMutableTreeNode, true, tree) } } } override fun update(e: AnActionEvent) { e.presentation.isEnabled = isEnabled(e) } override fun isEnabled(e: AnActionEvent): Boolean { var enabled = false val selections = tree.selectionPaths if (selections != null) { for (each in selections) { val node = each.lastPathComponent as DefaultMutableTreeNode val kind = getKind(node) if ((kind.isConfiguration || kind == FOLDER) && !isVirtualConfiguration(node)) { enabled = true break } } } return enabled } } protected inner class MyCopyAction : AnAction(ExecutionBundle.message("copy.configuration.action.name"), ExecutionBundle.message("copy.configuration.action.name"), PlatformIcons.COPY_ICON), PossiblyDumbAware { init { val action = ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_DUPLICATE) registerCustomShortcutSet(action.shortcutSet, tree) } override fun actionPerformed(e: AnActionEvent) { val configuration = selectedConfiguration!! try { val typeNode = selectedConfigurationTypeNode!! val settings = configuration.createSnapshot(true) val copyName = createUniqueName(typeNode, configuration.nameText, CONFIGURATION, TEMPORARY_CONFIGURATION) settings.name = copyName val factory = settings.factory @Suppress("UNCHECKED_CAST", "DEPRECATION") (factory as? ConfigurationFactoryEx<RunConfiguration>)?.onConfigurationCopied(settings.configuration) (settings.configuration as? ConfigurationCreationListener)?.onConfigurationCopied() val parentNode = selectedNode?.parent val node = (if ((parentNode as? DefaultMutableTreeNode)?.userObject is String) parentNode else typeNode) as DefaultMutableTreeNode val configurable = createNewConfiguration(settings, node, selectedNode) configurable.nameTextField.selectionStart = 0 configurable.nameTextField.selectionEnd = copyName.length RunConfigurationOptionUsagesCollector.logCopy(project, configurable.configuration.type.id, ActionPlaces.RUN_CONFIGURATION_EDITOR) } catch (e: ConfigurationException) { Messages.showErrorDialog(toolbarDecorator!!.actionsPanel, e.message, e.title) } } override fun update(e: AnActionEvent) { val configuration = selectedConfiguration e.presentation.isEnabled = configuration != null && configuration.configuration.type.isManaged } override fun isDumbAware(): Boolean { val configuration = selectedConfiguration return configuration != null && isEditableInDumbMode(configuration.configuration) } } protected inner class MySaveAction : DumbAwareAction(ExecutionBundle.message("action.name.save.configuration"), null, AllIcons.Actions.MenuSaveall) { override fun actionPerformed(e: AnActionEvent) { val configurationConfigurable = selectedConfiguration LOG.assertTrue(configurationConfigurable != null) val originalConfiguration = configurationConfigurable!!.settings if (originalConfiguration.isTemporary) { //todo Don't make 'stable' real configurations here but keep the set 'they want to be stable' until global 'Apply' action runManager.makeStable(originalConfiguration) adjustOrder() } tree.repaint() } override fun update(e: AnActionEvent) { val configuration = selectedConfiguration e.presentation.isEnabledAndVisible = when (configuration) { null -> false else -> configuration.settings.isTemporary } } } /** * Just saved as 'stable' configuration shouldn't stay between temporary ones (here we order nodes in JTree only) * @return shift (positive) for move configuration "up" to other stable configurations. Zero means "there is nothing to change" */ private fun adjustOrder(): Int { val selectionPath = tree.selectionPath ?: return 0 val treeNode = selectionPath.lastPathComponent as DefaultMutableTreeNode val selectedSettings = getSettings(treeNode) if (selectedSettings == null || selectedSettings.isTemporary) { return 0 } val parent = treeNode.parent as MutableTreeNode val initialPosition = parent.getIndex(treeNode) var position = initialPosition var node: DefaultMutableTreeNode? = treeNode.previousSibling while (node != null) { val settings = getSettings(node) if (settings != null && settings.isTemporary) { position-- } else { break } node = node.previousSibling } for (i in 0 until initialPosition - position) { TreeUtil.moveSelectedRow(tree, -1) } return initialPosition - position } protected inner class MyMoveAction(@NlsActions.ActionText text: String, @NlsActions.ActionDescription description: String?, icon: Icon, private val direction: Int) : AnAction(text, description, icon), AnActionButtonRunnable, AnActionButtonUpdater { override fun actionPerformed(e: AnActionEvent) { doMove() } private fun doMove() { getAvailableDropPosition(direction)?.let { treeModel.drop(it.first, it.second, it.third) } } override fun run(button: AnActionButton) { doMove() } override fun update(e: AnActionEvent) { e.presentation.isEnabled = isEnabled(e) } override fun isEnabled(e: AnActionEvent) = getAvailableDropPosition(direction) != null } protected inner class MyEditTemplatesAction : AnAction(ExecutionBundle.message("run.configuration.edit.default.configuration.settings.text"), ExecutionBundle.message("run.configuration.edit.default.configuration.settings.description"), AllIcons.General.Settings), PossiblyDumbAware { override fun actionPerformed(e: AnActionEvent) { showTemplatesDialog(project, selectedConfigurationType) } override fun isDumbAware(): Boolean { val configuration = selectedConfiguration return configuration != null && isEditableInDumbMode(configuration.configuration) } } protected inner class MyCreateFolderAction : DumbAwareAction(ExecutionBundle.message("run.configuration.create.folder.text"), ExecutionBundle.message("run.configuration.create.folder.description"), AllIcons.Actions.NewFolder) { override fun actionPerformed(e: AnActionEvent) { val type = selectedConfigurationType ?: return val selectedNodes = selectedNodes val typeNode = getConfigurationTypeNode(type) ?: return val folderName = createUniqueName(typeNode, "New Folder", FOLDER) val folders = ArrayList<DefaultMutableTreeNode>() collectNodesRecursively(getConfigurationTypeNode(type)!!, folders, FOLDER) val folderNode = DefaultMutableTreeNode(folderName) treeModel.insertNodeInto(folderNode, typeNode, folders.size) isFolderCreating = true try { for (node in selectedNodes) { val folderRow = tree.getRowForPath(TreePath(folderNode.path)) val rowForPath = tree.getRowForPath(TreePath(node.path)) if (getKind(node).isConfiguration && treeModel.canDrop(rowForPath, folderRow, INTO)) { treeModel.drop(rowForPath, folderRow, INTO) } } tree.selectionPath = TreePath(folderNode.path) } finally { isFolderCreating = false } } override fun update(e: AnActionEvent) { var isEnabled = false var toMove = false val selectedNodes = selectedNodes var selectedType: ConfigurationType? = null for (node in selectedNodes) { val type = getType(node) if (selectedType == null) { selectedType = type } else { if (type != selectedType) { isEnabled = false break } } val kind = getKind(node) if (kind.isConfiguration || kind == CONFIGURATION_TYPE && node.parent === root || kind == FOLDER) { isEnabled = true } if (kind.isConfiguration) { toMove = true } } e.presentation.text = if (toMove) ExecutionBundle.message("run.configuration.create.folder.description.move") else ExecutionBundle.message("run.configuration.create.folder.text") e.presentation.isEnabled = isEnabled } } protected inner class MySortFolderAction : AnAction(ExecutionBundle.message("run.configuration.sort.folder.text"), ExecutionBundle.message("run.configuration.sort.folder.description"), AllIcons.ObjectBrowser.Sorted), Comparator<DefaultMutableTreeNode>, DumbAware { override fun compare(node1: DefaultMutableTreeNode, node2: DefaultMutableTreeNode): Int { val kind1 = getKind(node1) val kind2 = getKind(node2) if (kind1 == FOLDER) { return if (kind2 == FOLDER) node1.parent.getIndex(node1) - node2.parent.getIndex(node2) else -1 } if (kind2 == FOLDER) { return 1 } val name1 = getUserObjectName(node1.userObject) val name2 = getUserObjectName(node2.userObject) return when (kind1) { TEMPORARY_CONFIGURATION -> if (kind2 == TEMPORARY_CONFIGURATION) name1.compareTo(name2) else 1 else -> if (kind2 == TEMPORARY_CONFIGURATION) -1 else name1.compareTo(name2) } } override fun actionPerformed(e: AnActionEvent) { val selectedNodes = selectedNodes val foldersToSort = ArrayList<DefaultMutableTreeNode>() for (node in selectedNodes) { val kind = getKind(node) if (kind == CONFIGURATION_TYPE || kind == FOLDER) { foldersToSort.add(node) } } for (folderNode in foldersToSort) { val children = ArrayList<DefaultMutableTreeNode>() for (i in 0 until folderNode.childCount) { children.add(folderNode.getChildAt(i) as DefaultMutableTreeNode) } children.sortWith(this) for (child in children) { folderNode.add(child) } treeModel.nodeStructureChanged(folderNode) } } override fun update(e: AnActionEvent) { val selectedNodes = selectedNodes for (node in selectedNodes) { val kind = getKind(node) if (kind == CONFIGURATION_TYPE || kind == FOLDER) { e.presentation.isEnabled = true return } } e.presentation.isEnabled = false } } private val selectedNodes: Array<DefaultMutableTreeNode> get() = tree.getSelectedNodes(DefaultMutableTreeNode::class.java, null) private val selectedNode: DefaultMutableTreeNode? get() = tree.getSelectedNodes(DefaultMutableTreeNode::class.java, null).firstOrNull() private val selectedSettings: RunnerAndConfigurationSettings? get() { val selectionPath = tree.selectionPath ?: return null return getSettings(selectionPath.lastPathComponent as DefaultMutableTreeNode) } inner class MyTreeModel(root: TreeNode) : DefaultTreeModel(root), EditableModel, RowsDnDSupport.RefinedDropSupport { override fun addRow() {} override fun removeRow(index: Int) {} override fun exchangeRows(oldIndex: Int, newIndex: Int) { //Do nothing, use drop() instead } //Legacy, use canDrop() instead override fun canExchangeRows(oldIndex: Int, newIndex: Int) = false override fun canDrop(oldIndex: Int, newIndex: Int, position: RowsDnDSupport.RefinedDropSupport.Position): Boolean { if (tree.rowCount <= oldIndex || tree.rowCount <= newIndex || oldIndex < 0 || newIndex < 0) { return false } val oldPaths = tree.selectionPaths ?: return false val newNode = tree.getPathForRow(newIndex).lastPathComponent as DefaultMutableTreeNode for (oldPath in oldPaths) { val oldNode = oldPath.lastPathComponent as DefaultMutableTreeNode if (oldNode === newNode || !canDrop(oldNode, newNode, newIndex, position)) return false } return true } fun canDrop(oldNode: DefaultMutableTreeNode, newNode: DefaultMutableTreeNode, newIndex: Int, position: RowsDnDSupport.RefinedDropSupport.Position): Boolean { val oldParent = oldNode.parent as DefaultMutableTreeNode val newParent = newNode.parent as DefaultMutableTreeNode val oldKind = getKind(oldNode) val newKind = getKind(newNode) val oldType = getType(oldNode) val newType = getType(newNode) if (oldParent === newParent) { if (oldNode.previousSibling === newNode && position == BELOW) { return false } if (oldNode.nextSibling === newNode && position == ABOVE) { return false } } when { oldType == null -> return false oldType !== newType -> { val typeNode = getConfigurationTypeNode(oldType) if (getKind(oldParent) == FOLDER && typeNode != null && typeNode.nextSibling === newNode && position == ABOVE) { return true } return getKind(oldParent) == CONFIGURATION_TYPE && oldKind == FOLDER && typeNode != null && typeNode.nextSibling === newNode && position == ABOVE && oldParent.lastChild !== oldNode && getKind(oldParent.lastChild as DefaultMutableTreeNode) == FOLDER } newParent === oldNode || oldParent === newNode -> return false oldKind == FOLDER && newKind != FOLDER -> return newKind.isConfiguration && position == ABOVE && getKind(newParent) == CONFIGURATION_TYPE && newIndex > 1 && getKind(tree.getPathForRow(newIndex - 1).parentPath.lastPathComponent as DefaultMutableTreeNode) == FOLDER !oldKind.supportsDnD() || !newKind.supportsDnD() -> return false oldKind.isConfiguration && newKind == FOLDER && position == ABOVE -> return false oldKind == TEMPORARY_CONFIGURATION && newKind == CONFIGURATION && position == ABOVE -> return false oldKind == CONFIGURATION && newKind == TEMPORARY_CONFIGURATION && position == BELOW -> return false oldKind == CONFIGURATION && newKind == TEMPORARY_CONFIGURATION && position == ABOVE -> return newNode.previousSibling == null || getKind(newNode.previousSibling) == CONFIGURATION || getKind(newNode.previousSibling) == FOLDER oldKind == TEMPORARY_CONFIGURATION && newKind == CONFIGURATION && position == BELOW -> return newNode.nextSibling == null || getKind(newNode.nextSibling) == TEMPORARY_CONFIGURATION oldParent === newParent -> //Same parent if (oldKind.isConfiguration && newKind.isConfiguration) { return oldKind == newKind//both are temporary or saved } else if (oldKind == FOLDER) { return !tree.isExpanded(newIndex) || position == ABOVE } } return true } override fun isDropInto(component: JComponent, oldIndex: Int, newIndex: Int): Boolean { val oldNode = (tree.getPathForRow(oldIndex) ?: return false).lastPathComponent as DefaultMutableTreeNode val newNode = (tree.getPathForRow(newIndex) ?: return false).lastPathComponent as DefaultMutableTreeNode return getKind(oldNode).isConfiguration && getKind(newNode) == FOLDER } override fun drop(oldIndex: Int, newIndex: Int, position: RowsDnDSupport.RefinedDropSupport.Position) { val oldPaths = tree.selectionPaths ?: return val newNode = tree.getPathForRow(newIndex).lastPathComponent as DefaultMutableTreeNode val newKind = getKind(newNode) for (oldPath in oldPaths) { val oldNode = oldPath.lastPathComponent as DefaultMutableTreeNode var newParent = newNode.parent as DefaultMutableTreeNode val oldKind = getKind(oldNode) val wasExpanded = tree.isExpanded(TreePath(oldNode.path)) // drop in folder if (oldKind.isConfiguration && newKind == FOLDER) { removeNodeFromParent(oldNode) var index = newNode.childCount if (oldKind.isConfiguration) { var middleIndex = newNode.childCount for (i in 0 until newNode.childCount) { if (getKind(newNode.getChildAt(i) as DefaultMutableTreeNode) == TEMPORARY_CONFIGURATION) { //index of first temporary configuration in target folder middleIndex = i break } } if (position != INTO) { if (oldIndex < newIndex) { index = if (oldKind == CONFIGURATION) 0 else middleIndex } else { index = if (oldKind == CONFIGURATION) middleIndex else newNode.childCount } } else { index = if (oldKind == TEMPORARY_CONFIGURATION) newNode.childCount else middleIndex } } insertNodeInto(oldNode, newNode, index) tree.expandPath(TreePath(newNode.path)) } else { val type = getType(oldNode)!! removeNodeFromParent(oldNode) var index: Int if (type !== getType(newParent)) { newParent = getConfigurationTypeNode(type)!! index = newParent.childCount } else { index = newParent.getIndex(newNode) if (position == BELOW) { index++ } } insertNodeInto(oldNode, newParent, index) } val treePath = TreePath(oldNode.path) tree.selectionPath = treePath if (wasExpanded) { tree.expandPath(treePath) } } } override fun insertNodeInto(newChild: MutableTreeNode, parent: MutableTreeNode, index: Int) { super.insertNodeInto(newChild, parent, index) if (!getKind(newChild as DefaultMutableTreeNode).isConfiguration) { return } val userObject = getSafeUserObject(newChild) val newFolderName = if (getKind(parent as DefaultMutableTreeNode) == FOLDER) parent.userObject as String else null if (userObject is SingleConfigurationConfigurable<*>) { userObject.folderName = newFolderName } } override fun reload(node: TreeNode?) { super.reload(node) val userObject = (node as DefaultMutableTreeNode).userObject if (userObject is String) { for (i in 0 until node.childCount) { val safeUserObject = getSafeUserObject(node.getChildAt(i) as DefaultMutableTreeNode) if (safeUserObject is SingleConfigurationConfigurable<*>) { safeUserObject.folderName = userObject } } } } private fun getType(treeNode: DefaultMutableTreeNode?): ConfigurationType? { val userObject = treeNode?.userObject ?: return null return when (userObject) { is SingleConfigurationConfigurable<*> -> userObject.configuration.type is RunnerAndConfigurationSettings -> userObject.type is ConfigurationType -> userObject else -> if (treeNode.parent is DefaultMutableTreeNode) getType(treeNode.parent as DefaultMutableTreeNode) else null } } } } private fun canRunConfiguration(configuration: SingleConfigurationConfigurable<RunConfiguration>?, executor: Executor): Boolean { return try { configuration != null && RunManagerImpl.canRunConfiguration(configuration.createSnapshot(false), executor) } catch (e: ConfigurationException) { false } } private fun createUniqueName(typeNode: DefaultMutableTreeNode, baseName: String?, vararg kinds: RunConfigurableNodeKind): String { val str = baseName ?: ExecutionBundle.message("run.configuration.unnamed.name.prefix") val configurationNodes = ArrayList<DefaultMutableTreeNode>() collectNodesRecursively(typeNode, configurationNodes, *kinds) val currentNames = ArrayList<String>() for (node in configurationNodes) { when (val userObject = node.userObject) { is SingleConfigurationConfigurable<*> -> currentNames.add(userObject.nameText) is RunnerAndConfigurationSettingsImpl -> currentNames.add((userObject as RunnerAndConfigurationSettings).name) is String -> currentNames.add(userObject) } } return RunManager.suggestUniqueName(str, currentNames) } private fun getType(_node: DefaultMutableTreeNode?): ConfigurationType? { var node = _node while (node != null) { (node.userObject as? ConfigurationType)?.let { return it } node = node.parent as? DefaultMutableTreeNode } return null } private fun getSettings(treeNode: DefaultMutableTreeNode?): RunnerAndConfigurationSettings? { if (treeNode == null) { return null } val settings: RunnerAndConfigurationSettings? = null return when (treeNode.userObject) { is SingleConfigurationConfigurable<*> -> (treeNode.userObject as SingleConfigurationConfigurable<*>).settings is RunnerAndConfigurationSettings -> treeNode.userObject as RunnerAndConfigurationSettings else -> settings } }
platform/execution-impl/src/com/intellij/execution/impl/RunConfigurable.kt
910682000
package eu.ssoudan.ktSpringTest.management import org.springframework.boot.actuate.health.Health import org.springframework.boot.actuate.health.AbstractHealthIndicator import org.springframework.stereotype.Service import eu.ssoudan.ktSpringTest.management.HealthCheckedService.HealthStatus import java.util.LinkedList import eu.ssoudan.ktSpringTest.configuration.HelloConfiguration import org.springframework.beans.factory.annotation.Autowired /** * Created by ssoudan on 12/6/14. * * Apache License, Version 2.0 */ Service class ServiceHealthIndicator [Autowired] (val services: List<HealthCheckedService>, val configuration: HelloConfiguration) : AbstractHealthIndicator() { fun updateStatus(status: HealthStatus, dependencies: List<HealthCheckedService.HealthInfo>): HealthStatus { var updatedStatus = status; dependencies.forEach { dep -> dep.updateStatus() if (dep.status == HealthStatus.DOWN) { updatedStatus = HealthStatus.DOWN; } } return updatedStatus } override fun doHealthCheck(p0: Health.Builder?) { if (p0 != null) { val dependencies = LinkedList<HealthCheckedService.HealthInfo>() services.forEach { i -> dependencies.add(i.healthCheck()) } val status = updateStatus(HealthStatus.UP, dependencies) p0.withDetail("dependencies", dependencies) p0.withDetail("serviceName", configuration.serviceName) if (status == HealthStatus.UP) p0.up() else p0.down() } } }
src/main/java/eu/ssoudan/ktSpringTest/management/ServiceHealthIndicator.kt
4199035884
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================================================================== */ package org.tensorflow.lite.examples.poseestimation.ml import android.graphics.Bitmap import org.tensorflow.lite.examples.poseestimation.data.Person interface PoseDetector : AutoCloseable { fun estimatePoses(bitmap: Bitmap): List<Person> fun lastInferenceTimeNanos(): Long }
lite/examples/pose_estimation/android/app/src/main/java/org/tensorflow/lite/examples/poseestimation/ml/PoseDetector.kt
3413314328
package de.fabmax.kool.modules.gltf import de.fabmax.kool.pipeline.Texture2d import de.fabmax.kool.pipeline.TextureProps import kotlinx.serialization.Serializable import kotlinx.serialization.Transient /** * A texture and its sampler. * * @param sampler The index of the sampler used by this texture. When undefined, a sampler with repeat wrapping and * auto filtering should be used. * @param source The index of the image used by this texture. When undefined, it is expected that an extension or * other mechanism will supply an alternate texture source, otherwise behavior is undefined. * @param name The user-defined name of this object. */ @Serializable data class GltfTexture( val sampler: Int = -1, val source: Int = 0, val name: String? = null ) { @Transient lateinit var imageRef: GltfImage @Transient private var createdTex: Texture2d? = null fun makeTexture(): Texture2d { if (createdTex == null) { val uri = imageRef.uri val name = if (uri != null && !uri.startsWith("data:", true)) { uri } else { "gltf_tex_$source" } createdTex = Texture2d(TextureProps(), name) { assetMgr -> if (uri != null) { assetMgr.loadTextureData(uri) } else { assetMgr.createTextureData(imageRef.bufferViewRef!!.getData(), imageRef.mimeType!!) } } } return createdTex!! } }
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/gltf/GltfTexture.kt
4022158447
package com.cout970.modeler.core.model.`object` import com.cout970.modeler.api.model.ITransformation import com.cout970.modeler.api.model.`object`.IObject import com.cout970.modeler.api.model.`object`.IObjectCube import com.cout970.modeler.api.model.material.IMaterialRef import com.cout970.modeler.api.model.mesh.IMesh import com.cout970.modeler.core.model.TRSTransformation import com.cout970.modeler.core.model.TRTSTransformation import com.cout970.modeler.core.model.material.MaterialRefNone import com.cout970.modeler.core.model.mesh.FaceIndex import com.cout970.modeler.core.model.mesh.Mesh import com.cout970.modeler.core.model.mesh.MeshFactory import com.cout970.vector.api.IVector2 import com.cout970.vector.api.IVector3 import com.cout970.vector.extensions.* import java.util.* /** * Created by cout970 on 2017/05/14. */ data class ObjectCube( override val name: String, override val transformation: ITransformation, override val material: IMaterialRef = MaterialRefNone, override val textureOffset: IVector2 = Vector2.ORIGIN, override val textureSize: IVector2 = vec2Of(64), override val visible: Boolean = true, val mirrored: Boolean = false, override val id: UUID = UUID.randomUUID() ) : IObjectCube { override val mesh: IMesh by lazy { generateMesh() } val trs get() = when (transformation) { is TRSTransformation -> transformation.toTRTS() is TRTSTransformation -> transformation else -> error("Invalid type: $transformation") } val size: IVector3 get() = trs.scale val pos: IVector3 get() = trs.translation fun generateMesh(): IMesh { val cube = MeshFactory.createCube(Vector3.ONE, Vector3.ORIGIN) return updateTextures(cube, size, textureOffset, textureSize) } fun updateTextures(mesh: IMesh, size: IVector3, offset: IVector2, textureSize: IVector2): IMesh { val uvs = generateUVs(size, offset, textureSize) val newFaces = mesh.faces.mapIndexed { index, face -> val faceIndex = face as FaceIndex FaceIndex.from(faceIndex.pos, faceIndex.tex.mapIndexed { vertexIndex, _ -> index * 4 + vertexIndex }) } return Mesh(mesh.pos, uvs, newFaces) } private fun generateUVs(size: IVector3, offset: IVector2, textureSize: IVector2): List<IVector2> { val width = size.xd val height = size.yd val length = size.zd val offsetX = offset.xd val offsetY = offset.yd val texelSize = vec2Of(1) / textureSize return listOf( //-y vec2Of(offsetX + length + width + width, offsetY + length) * texelSize, vec2Of(offsetX + length + width + width, offsetY) * texelSize, vec2Of(offsetX + length + width, offsetY) * texelSize, vec2Of(offsetX + length + width, offsetY + length) * texelSize, //+y vec2Of(offsetX + length, offsetY + length) * texelSize, vec2Of(offsetX + length + width, offsetY + length) * texelSize, vec2Of(offsetX + length + width, offsetY) * texelSize, vec2Of(offsetX + length, offsetY) * texelSize, //-z vec2Of(offsetX + length + width + length + width, offsetY + length) * texelSize, vec2Of(offsetX + length + width + length, offsetY + length) * texelSize, vec2Of(offsetX + length + width + length, offsetY + length + height) * texelSize, vec2Of(offsetX + length + width + length + width, offsetY + length + height) * texelSize, //+z vec2Of(offsetX + length + width, offsetY + length + height) * texelSize, vec2Of(offsetX + length + width, offsetY + length) * texelSize, vec2Of(offsetX + length, offsetY + length) * texelSize, vec2Of(offsetX + length, offsetY + length + height) * texelSize, //-x vec2Of(offsetX + length, offsetY + length + height) * texelSize, vec2Of(offsetX + length, offsetY + length) * texelSize, vec2Of(offsetX, offsetY + length) * texelSize, vec2Of(offsetX, offsetY + length + height) * texelSize, //+x vec2Of(offsetX + length + width + length, offsetY + length) * texelSize, vec2Of(offsetX + length + width, offsetY + length) * texelSize, vec2Of(offsetX + length + width, offsetY + length + height) * texelSize, vec2Of(offsetX + length + width + length, offsetY + length + height) * texelSize ) } override fun withVisibility(visible: Boolean): IObject = copy(visible = visible) override fun withSize(size: IVector3): IObjectCube = copy(transformation = trs.copy(scale = size)) override fun withPos(pos: IVector3): IObjectCube = copy(transformation = trs.copy(translation = pos)) override fun withTransformation(transform: ITransformation): IObjectCube = copy(transformation = transform) override fun withTextureOffset(tex: IVector2): IObjectCube = copy(textureOffset = tex) override fun withTextureSize(size: IVector2): IObjectCube = copy(textureSize = size) override fun withMesh(newMesh: IMesh): IObject = Object(name, newMesh, material, transformation, visible, id) override fun withMaterial(materialRef: IMaterialRef): IObject = copy(material = materialRef) override fun withName(name: String): IObject = copy(name = name) override fun withId(id: UUID): IObject = copy(id = id) override fun makeCopy(): IObjectCube = copy(id = UUID.randomUUID()) }
src/main/kotlin/com/cout970/modeler/core/model/object/ObjectCube.kt
702965180
t as Int
plugins/kotlin/j2k/old/tests/testData/fileOrElement/typeCastExpression/intCast.kt
2352010498
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.fixes import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.diagnosticFixFactory import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic import org.jetbrains.kotlin.idea.quickfix.AddModifierFix import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtProperty object AddLateInitFactory { val addLateInitFactory = diagnosticFixFactory(KtFirDiagnostic.MustBeInitializedOrBeAbstract::class) { diagnostic -> val property: KtProperty = diagnostic.psi if (!property.isVar) return@diagnosticFixFactory emptyList() val type = property.getReturnKtType() if (type.isPrimitive || type.canBeNull) return@diagnosticFixFactory emptyList() listOf(AddModifierFix(property, KtTokens.LATEINIT_KEYWORD)) } }
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickfix/fixes/AddLateInitFactory.kt
2000740095